mcpField
A
arm-templates

arm-templates

github.com/bagelhole云与 DevOps1.2k312 次安装23 周前更新
代码仓库

关于 arm-templates

本技能介绍使用 ARM 模板和 Bicep 部署 Azure 基础设施,面向采用 Azure 原生基础设施即代码的团队,涵盖模块、部署范围、验证和变更预览。

主要功能

  1. 01编写 Bicep 与 ARM 模板
  2. 02复用 Bicep 模块
  3. 03支持多个部署范围
  4. 04验证模板
  5. 05预览 What-If 变更

适用场景

  1. 01以代码方式配置 Azure 资源
  2. 02部署前预览基础设施变更
  3. 03将 ARM JSON 模板迁移到 Bicep
  4. 04在资源组或订阅范围部署

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/bagelhole/devops-security-agent-skills --skill arm-templates

安装后在 Claude Code 中输入/arm-templates确认已加载。

附带文件references/arm-syntax.md

详细介绍

ARM 模板与 Bicep

使用 ARM 模板和 Bicep 部署 Azure 基础设施。Bicep 是推荐使用的领域特定语言,可编译为 ARM JSON,并提供更简洁的语法、模块和一流的工具支持。

适用场景

  • 你需要 Azure 原生的基础设施即代码(IaC),且不依赖第三方工具。
  • 你的组织采用 Azure 标准,并希望与门户紧密集成。
  • 你需要在部署更改前进行 What-If 分析。
  • 你正在将现有 ARM JSON 模板迁移到 Bicep,以提高可维护性。
  • 你需要在资源组、订阅、管理组或租户级别设置部署范围。

前提条件

# Install Azure CLI
curl -sL https://aka.ms/InstallAzureCLIDeb | sudo bash

# Install Bicep CLI (bundled with Azure CLI 2.20+)
az bicep install
az bicep upgrade

# Verify installation
az bicep version

# Login and set subscription
az login
az account set --subscription "my-subscription-id"

Bicep 基础知识

使用虚拟网络部署资源组
// main.bicep
@description('Azure region for all resources')
param location string = resourceGroup().location

@description('Environment name used for resource naming')
@allowed(['dev', 'staging', 'prod'])
param environment string = 'dev'

@description('Base name for all resources')
param baseName string

var vnetName = '${baseName}-${environment}-vnet'
var nsgName = '${baseName}-${environment}-nsg'

resource nsg 'Microsoft.Network/networkSecurityGroups@2023-05-01' = {
  name: nsgName
  location: location
  properties: {
    securityRules: [
      {
        name: 'AllowHTTPS'
        properties: {
          priority: 100
          direction: 'Inbound'
          access: 'Allow'
          protocol: 'Tcp'
          sourcePortRange: '*'
          destinationPortRange: '443'
          sourceAddressPrefix: '*'
          destinationAddressPrefix: '*'
        }
      }
      {
        name: 'DenyAllInbound'
        properties: {
          priority: 4096
          direction: 'Inbound'
          access: 'Deny'
          protocol: '*'
          sourcePortRange: '*'
          destinationPortRange: '*'
          sourceAddressPrefix: '*'
          destinationAddressPrefix: '*'
        }
      }
    ]
  }
}

resource vnet 'Microsoft.Network/virtualNetworks@2023-05-01' = {
  name: vnetName
  location: location
  properties: {
    addressSpace: {
      addressPrefixes: [
        '10.0.0.0/16'
      ]
    }
    subnets: [
      {
        name: 'web-subnet'
        properties: {
          addressPrefix: '10.0.1.0/24'
          networkSecurityGroup: {
            id: nsg.id
          }
        }
      }
      {
        name: 'app-subnet'
        properties: {
          addressPrefix: '10.0.2.0/24'
        }
      }
      {
        name: 'data-subnet'
        properties: {
          addressPrefix: '10.0.3.0/24'
          privateEndpointNetworkPolicies: 'Enabled'
        }
      }
    ]
  }
}

output vnetId string = vnet.id
output webSubnetId string = vnet.properties.subnets[0].id
output appSubnetId string = vnet.properties.subnets[1].id
使用托管标识部署 VM
// vm.bicep
param location string = resourceGroup().location
param vmName string
param subnetId string
param adminUsername string = 'azureuser'

@secure()
param adminPublicKey string

resource nic 'Microsoft.Network/networkInterfaces@2023-05-01' = {
  name: '${vmName}-nic'
  location: location
  properties: {
    ipConfigurations: [
      {
        name: 'ipconfig1'
        properties: {
          privateIPAllocationMethod: 'Dynamic'
          subnet: {
            id: subnetId
          }
        }
      }
    ]
  }
}

resource vm 'Microsoft.Compute/virtualMachines@2023-07-01' = {
  name: vmName
  location: location
  identity: {
    type: 'SystemAssigned'
  }
  properties: {
    hardwareProfile: {
      vmSize: 'Standard_B2s'
    }
    osProfile: {
      computerName: vmName
      adminUsername: adminUsername
      linuxConfiguration: {
        disablePasswordAuthentication: true
        ssh: {
          publicKeys: [
            {
              path: '/home/${adminUsername}/.ssh/authorized_keys'
              keyData: adminPublicKey
            }
          ]
        }
      }
    }
    storageProfile: {
      imageReference: {
        publisher: 'Canonical'
        offer: '0001-com-ubuntu-server-jammy'
        sku: '22_04-lts-gen2'
        version: 'latest'
      }
      osDisk: {
        createOption: 'FromImage'
        managedDisk: {
          storageAccountType: 'Premium_LRS'
        }
      }
    }
    networkProfile: {
      networkInterfaces: [
        {
          id: nic.id
        }
      ]
    }
    diagnosticsProfile: {
      bootDiagnostics: {
        enabled: true
      }
    }
  }
}

output vmPrincipalId string = vm.identity.principalId
output vmId string = vm.id

Bicep 模块

模块定义
// modules/storage.bicep
@description('Storage account name (3-24 chars, lowercase alphanumeric)')
param storageAccountName string

param location string = resourceGroup().location
param sku string = 'Standard_LRS'

@allowed(['Hot', 'Cool', 'Archive'])
param accessTier string = 'Hot'

resource storageAccount 'Microsoft.Storage/storageAccounts@2023-01-01' = {
  name: storageAccountName
  location: location
  sku: {
    name: sku
  }
  kind: 'StorageV2'
  properties: {
    accessTier: accessTier
    supportsHttpsTrafficOnly: true
    minimumTlsVersion: 'TLS1_2'
    allowBlobPublicAccess: false
    networkAcls: {
      defaultAction: 'Deny'
      bypass: 'AzureServices'
    }
  }
}

output storageAccountId string = storageAccount.id
output primaryBlobEndpoint string = storageAccount.properties.primaryEndpoints.blob
使用模块
// main.bicep
param location string = resourceGroup().location
param environment string = 'prod'

module storage 'modules/storage.bicep' = {
  name: 'storage-deployment'
  params: {
    storageAccountName: 'myapp${environment}sa'
    location: location
    sku: environment == 'prod' ? 'Standard_GRS' : 'Standard_LRS'
  }
}

module vnet 'modules/network.bicep' = {
  name: 'vnet-deployment'
  params: {
    location: location
    environment: environment
  }
}

// Reference module outputs
output storageBlobEndpoint string = storage.outputs.primaryBlobEndpoint

ARM JSON 模板结构

{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "storageAccountName": {
      "type": "string",
      "metadata": {
        "description": "Name of the storage account"
      }
    },
    "location": {
      "type": "string",
      "defaultValue": "[resourceGroup().location]"
    }
  },
  "variables": {
    "storageSku": "Standard_LRS"
  },
  "resources": [
    {
      "type": "Microsoft.Storage/storageAccounts",
      "apiVersion": "2023-01-01",
      "name": "[parameters('storageAccountName')]",
      "location": "[parameters('location')]",
      "sku": {
        "name": "[variables('storageSku')]"
      },
      "kind": "StorageV2",
      "properties": {
        "supportsHttpsTrafficOnly": true,
        "minimumTlsVersion": "TLS1_2"
      }
    }
  ],
  "outputs": {
    "storageId": {
      "type": "string",
      "value": "[resourceId('Microsoft.Storage/storageAccounts', parameters('storageAccountName'))]"
    }
  }
}

部署命令

# Validate a Bicep template before deployment
az deployment group validate \
  --resource-group mygroup \
  --template-file main.bicep \
  --parameters environment='prod' baseName='myapp'

# Preview changes with What-If
az deployment group what-if \
  --resource-group mygroup \
  --template-file main.bicep \
  --parameters environment='prod' baseName='myapp'

# Deploy Bicep to resource group
az deployment group create \
  --resource-group mygroup \
  --template-file main.bicep \
  --parameters environment='prod' baseName='myapp' \
  --name "deploy-$(date +%Y%m%d-%H%M%S)"

# Deploy ARM JSON with parameter file
az deployment group create \
  --resource-group mygroup \
  --template-file template.json \
  --parameters @parameters.prod.json

# Subscription-level deployment (e.g., resource groups, policies)
az deployment sub create \
  --location eastus \
  --template-file subscription-level.bicep \
  --parameters @params.json

# Management group deployment
az deployment mg create \
  --management-group-id my-mg \
  --location eastus \
  --template-file mg-policy.bicep

# Export resource group to ARM JSON
az group export --name mygroup --output json > exported-template.json

# Decompile ARM JSON to Bicep
az bicep decompile --file exported-template.json

# Build Bicep to ARM JSON (for inspection)
az bicep build --file main.bicep --outfile main.json

# List deployments and their status
az deployment group list \
  --resource-group mygroup \
  --output table

# Delete a failed deployment
az deployment group delete \
  --resource-group mygroup \
  --name my-failed-deployment

参数文件

// parameters.prod.json
{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentParameters.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "environment": { "value": "prod" },
    "baseName": { "value": "myapp" },
    "adminPublicKey": {
      "reference": {
        "keyVault": {
          "id": "/subscriptions/{sub-id}/resourceGroups/{rg}/providers/Microsoft.KeyVault/vaults/{vault}"
        },
        "secretName": "ssh-public-key"
      }
    }
  }
}

链接模板和嵌套模板

// Deploy to a different resource group
module networkInSharedRg 'modules/network.bicep' = {
  name: 'shared-network'
  scope: resourceGroup('shared-networking-rg')
  params: {
    location: location
  }
}

// Conditional deployment
param deployMonitoring bool = true

module monitoring 'modules/monitoring.bicep' = if (deployMonitoring) {
  name: 'monitoring-deployment'
  params: {
    location: location
  }
}

// Loop deployment
param storageAccounts array = [
  { name: 'logs', sku: 'Standard_LRS' }
  { name: 'data', sku: 'Standard_GRS' }
]

module storageLoop 'modules/storage.bicep' = [for account in storageAccounts: {
  name: 'storage-${account.name}'
  params: {
    storageAccountName: '${baseName}${account.name}sa'
    sku: account.sku
    location: location
  }
}]

故障排查

症状原因解决方法
InvalidTemplate 错误ARM JSON 或 Bicep 中存在语法错误运行 az bicep build 检查编译错误
部署期间出现 ResourceNotFound未声明资源依赖关系添加 dependsOn,或在 Bicep 中使用隐式引用
DeploymentFailed 并提示配额错误超出订阅配额申请提高配额或使用其他区域
AuthorizationFailedRBAC 权限不足在目标资源组上分配 Contributor 角色
源代码管理中的参数文件包含机密机密以纯文本形式存储在参数文件中使用 Key Vault 引用
部署耗时很长大量资源按顺序部署谨慎使用 dependsOn,以允许并行部署
What-If 显示意外删除使用了 Complete 模式而非 Incremental 模式使用 --mode Incremental(默认值),避免删除未托管的资源
找不到 Bicep 模块相对路径不正确确认路径是相对于使用该模块的文件

相关技能

  • terraform-azure -- 支持更广泛提供商的多云 IaC 替代方案。
  • azure-networking -- 模板中引用的 VNet、NSG 和防火墙配置。
  • azure-vms -- 虚拟机规格选择和配置详情。
  • azure-aks -- Bicep/ARM 的 Kubernetes 集群定义。

评论

支持 Markdown