之前已经介绍了不少BICEP的基础操作,接下来再分享一些算是初步入门的技巧,包括循环的使用,array的用法
array是个实实在在的好东西,可以把多个信息定义在一个array里,这样可以很大程度上减少代码的冗余,提升可阅读性,举个简单例子,像是subnet这种资源,是可以有多个的,可以把这些信息都定义在array里,这样就算有10个subnet,代码也不会显得太过冗余
比如下边这段就定义了一个包含两个subnet的VNET,subnet的信息首先定义在array里,然后通过for循环就可以直接把subnet的信息定义在一个变量里
param addressPrefix string = '10.10.0.0/16'
param subnets array = [
{
name: 'frontend'
ipAddressRange: '10.10.0.0/24'
}
{
name: 'backend'
ipAddressRange: '10.10.1.0/24'
}
]
var subnetsProperty = [for subnet in subnets: {
name: subnet.name
properties: {
addressPrefix: subnet.ipAddressRange
}
}]
resource virtualNetwork 'Microsoft.Network/virtualNetworks@2020-11-01' = {
name: 'vnet'
location: resourceGroup().location
properties:{
addressSpace:{
addressPrefixes:[
addressPrefix
]
}
subnets: subnetsProperty
}
}
for循环的使用在BICEP中非常类似Python或者.NET的用法,可以用在变量,resource,output等多种地方,下边就是个简单的例子
var storageAccountNames = [
'sa1${take(uniqueString(resourceGroup().id), 10)}'
'sa2${take(uniqueString(resourceGroup().id), 10)}'
'sa3${take(uniqueString(resourceGroup().id), 10)}'
]
resource storageaccount 'Microsoft.Storage/storageAccounts@2021-02-01' = [for storage in storageAccountNames: {
name:storage
location: resourceGroup().location
kind: 'StorageV2'
sku: {
name: 'Standard_LRS'
}
}]
可以看到在BICEP中使用for循环,基本和高级语言中的体验非常类似了
另外,微软还提供了方法,可以直接将ARM Template转为BICEP文件,只需要运行AZ CLI命令即可
ARM Template
{
"$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"webAppName": {
"type": "string",
"defaultValue": "[concat('webApp-', uniqueString(resourceGroup().id))]",
"minLength": 2,
"metadata": {
"description": "Web app name."
}
},
"location": {
"type": "string",
"defaultValue": "[resourceGroup().location]",
"metadata": {
"description": "Location for all resources."
}
},
"sku": {
"type": "string",
"defaultValue": "F1",
"metadata": {
"description": "The SKU of App Service Plan."
}
},
"linuxFxVersion": {
"type": "string",
"defaultValue": "DOTNETCORE|3.0",
"metadata": {
"description": "The Runtime stack of current web app"
}
}
},
"variables": {
"appServicePlanPortalName": "[concat('AppServicePlan-', parameters('webAppName'))]"
},
"resources": [
{
"type": "Microsoft.Web/serverfarms",
"apiVersion": "2020-06-01",
"name": "[variables('appServicePlanPortalName')]",
"location": "[parameters('location')]",
"sku": {
"name": "[parameters('sku')]"
},
"kind": "linux",
"properties": {
"reserved": true
}
},
{
"type": "Microsoft.Web/sites",
"apiVersion": "2020-06-01",
"name": "[parameters('webAppName')]",
"location": "[parameters('location')]",
"dependsOn": [
"[resourceId('Microsoft.Web/serverfarms', variables('appServicePlanPortalName'))]"
],
"properties": {
"serverFarmId": "[resourceId('Microsoft.Web/serverfarms', variables('appServicePlanPortalName'))]",
"siteConfig": {
"linuxFxVersion": "[parameters('linuxFxVersion')]"
}
}
}
]
}
运行命令
az bicep decompile --file .\azuredeploy.json
转换完成