基础设施即代码 #

什么是基础设施即代码? #

基础设施即代码 (IaC) 是使用代码来管理和配置基础设施的实践。

text
┌─────────────────────────────────────────────────────────────┐
│                    IaC 概览                                  │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  优势                                                        │
│  ├── 可重复:一致的部署                                     │
│  ├── 版本控制:追踪变更                                     │
│  ├── 自动化:减少手动操作                                   │
│  ├── 文档化:代码即文档                                     │
│  └── 可测试:验证配置                                       │
│                                                             │
│  Azure IaC 工具                                              │
│  ├── ARM 模板: Azure 原生 JSON 模板                         │
│  ├── Bicep: Azure 原生 DSL,推荐                            │
│  └── Terraform: 跨云平台工具                                │
│                                                             │
│  选择建议                                                    │
│  ├── 仅 Azure: Bicep                                        │
│  ├── 多云平台: Terraform                                    │
│  └── 兼容旧系统: ARM 模板                                   │
│                                                             │
└─────────────────────────────────────────────────────────────┘

Bicep #

Bicep 简介 #

Bicep 是 Azure 提供的领域特定语言 (DSL),用于部署 Azure 资源。

bicep
// main.bicep
param location string = resourceGroup().location
param storageAccountName string = 'mystorage${uniqueString(resourceGroup().id)}'

resource storageAccount 'Microsoft.Storage/storageAccounts@2023-01-01' = {
  name: storageAccountName
  location: location
  sku: {
    name: 'Standard_LRS'
  }
  kind: 'StorageV2'
  properties: {
    accessTier: 'Hot'
  }
}

output storageAccountId string = storageAccount.id

部署 Bicep 文件 #

bash
# 安装 Bicep CLI
az bicep install

# 验证 Bicep 文件
az bicep build --file main.bicep

# 部署到资源组
az deployment group create \
  --resource-group myResourceGroup \
  --template-file main.bicep

# 使用参数文件部署
az deployment group create \
  --resource-group myResourceGroup \
  --template-file main.bicep \
  --parameters parameters.json

参数和变量 #

bicep
// 参数
param location string = 'eastus'
param environment string
param vmSize string = 'Standard_D2s_v3'

@allowed([
  'dev'
  'test'
  'prod'
])
param environmentType string = 'dev'

// 变量
var storageAccountName = 'st${environment}${uniqueString(resourceGroup().id)}'
var tags = {
  Environment: environment
  Project: 'MyProject'
}

模块化 #

bicep
// modules/storage.bicep
param location string
param storageAccountName string

resource storageAccount 'Microsoft.Storage/storageAccounts@2023-01-01' = {
  name: storageAccountName
  location: location
  sku: {
    name: 'Standard_LRS'
  }
  kind: 'StorageV2'
}

output storageAccountId string = storageAccount.id

// main.bicep
module storageModule 'modules/storage.bicep' = {
  name: 'storageDeployment'
  params: {
    location: location
    storageAccountName: 'mystorageaccount'
  }
}

循环和条件 #

bicep
// 循环
param storageAccountNames array = ['storage1', 'storage2', 'storage3']

resource storageAccounts 'Microsoft.Storage/storageAccounts@2023-01-01' = [for name in storageAccountNames: {
  name: name
  location: location
  sku: {
    name: 'Standard_LRS'
  }
  kind: 'StorageV2'
}]

// 条件部署
param deployStorage bool = true

resource storageAccount 'Microsoft.Storage/storageAccounts@2023-01-01' = if (deployStorage) {
  name: storageAccountName
  location: location
  sku: {
    name: 'Standard_LRS'
  }
  kind: 'StorageV2'
}

ARM 模板 #

ARM 模板结构 #

json
{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "storageAccountName": {
      "type": "string",
      "defaultValue": "mystorageaccount"
    },
    "location": {
      "type": "string",
      "defaultValue": "[resourceGroup().location]"
    }
  },
  "variables": {},
  "resources": [
    {
      "type": "Microsoft.Storage/storageAccounts",
      "apiVersion": "2023-01-01",
      "name": "[parameters('storageAccountName')]",
      "location": "[parameters('location')]",
      "sku": {
        "name": "Standard_LRS"
      },
      "kind": "StorageV2"
    }
  ],
  "outputs": {
    "storageAccountId": {
      "type": "string",
      "value": "[resourceId('Microsoft.Storage/storageAccounts', parameters('storageAccountName'))]"
    }
  }
}

部署 ARM 模板 #

bash
# 部署到资源组
az deployment group create \
  --resource-group myResourceGroup \
  --template-file template.json \
  --parameters storageAccountName=mystorageaccount

# 部署到订阅
az deployment sub create \
  --location eastus \
  --template-file template.json

Terraform #

Terraform 配置 #

hcl
# main.tf
provider "azurerm" {
  features {}
}

resource "azurerm_resource_group" "example" {
  name     = "myResourceGroup"
  location = "East US"
}

resource "azurerm_storage_account" "example" {
  name                     = "mystorageaccount"
  resource_group_name      = azurerm_resource_group.example.name
  location                 = azurerm_resource_group.example.location
  account_tier             = "Standard"
  account_replication_type = "LRS"

  tags = {
    environment = "dev"
  }
}

Terraform 命令 #

bash
# 初始化
terraform init

# 验证配置
terraform validate

# 查看计划
terraform plan

# 应用配置
terraform apply

# 销毁资源
terraform destroy

Terraform 模块 #

hcl
# modules/storage/main.tf
variable "resource_group_name" {}
variable "location" {}
variable "storage_account_name" {}

resource "azurerm_storage_account" "example" {
  name                     = var.storage_account_name
  resource_group_name      = var.resource_group_name
  location                 = var.location
  account_tier             = "Standard"
  account_replication_type = "LRS"
}

output "storage_account_id" {
  value = azurerm_storage_account.example.id
}

# main.tf
module "storage" {
  source              = "./modules/storage"
  resource_group_name = azurerm_resource_group.example.name
  location            = azurerm_resource_group.example.location
  storage_account_name = "mystorageaccount"
}

最佳实践 #

IaC 设计建议 #

text
┌─────────────────────────────────────────────────────────────┐
│                    IaC 最佳实践                              │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  1. 模块化设计                                               │
│     └── 复用和可维护性                                      │
│                                                             │
│  2. 使用参数                                                 │
│     └── 灵活配置                                            │
│                                                             │
│  3. 环境分离                                                 │
│     └── 不同环境使用不同参数                                │
│                                                             │
│  4. 版本控制                                                 │
│     └── 追踪变更                                            │
│                                                             │
│  5. 测试验证                                                 │
│     └── 使用 what-if 预览                                   │
│                                                             │
│  6. CI/CD 集成                                               │
│     └── 自动化部署                                          │
│                                                             │
└─────────────────────────────────────────────────────────────┘

下一步 #

现在你已经掌握了基础设施即代码的使用,接下来学习 实战案例 了解完整的应用部署!

最后更新:2026-03-29