Bicep 中的输出迭代
本文展示了如何为 Bicep 文件中的输出创建多个值。 可以在文件的 output
部分添加循环,并在部署期间动态返回多个项。
语法
循环可用于在部署过程中通过以下方式返回多个项:
使用循环索引。
output <output-name> array = [for <index> in range(<start>, <stop>): { <properties> }]
有关详细信息,请参阅循环索引。
循环访问数组。
output <output-name> array = [for <item> in <collection>: { <properties> }]
循环访问数组和索引。
output <output-name> array = [for <item>, <index> in <collection>: { <properties> }]
有关详细信息,请参阅循环数组和索引。
循环限制
Bicep 文件的循环迭代不能为负数,也不能超过 800 次。
循环索引
以下示例创建可变数量的存储帐户,并返回每个存储帐户的终结点。
param rgLocation string = resourceGroup().location
param storageCount int = 2
var baseNameVar = 'storage${uniqueString(resourceGroup().id)}'
resource stg 'Microsoft.Storage/storageAccounts@2021-02-01' = [for i in range(0, storageCount): {
name: '${i}${baseNameVar}'
location: rgLocation
sku: {
name: 'Standard_LRS'
}
kind: 'Storage'
}]
output storageEndpoints array = [for i in range(0, storageCount): stg[i].properties.primaryEndpoints.blob]
输出返回具有以下值的数组:
[
"https://0storagecfrbqnnmpeudi.blob.core.chinacloudapi.cn/",
"https://1storagecfrbqnnmpeudi.blob.core.chinacloudapi.cn/"
]
下一示例返回新存储帐户的三个属性。
param rgLocation string = resourceGroup().location
param storageCount int = 2
var baseNameVar = 'storage${uniqueString(resourceGroup().id)}'
resource stg 'Microsoft.Storage/storageAccounts@2021-02-01' = [for i in range(0, storageCount): {
name: '${i}${baseNameVar}'
location: rgLocation
sku: {
name: 'Standard_LRS'
}
kind: 'Storage'
}]
output storageInfo array = [for i in range(0, storageCount): {
id: stg[i].id
blobEndpoint: stg[i].properties.primaryEndpoints.blob
status: stg[i].properties.statusOfPrimary
}]
输出返回具有以下值的数组:
[
{
"id": "/subscriptions/{sub-id}/resourceGroups/{rg-name}/providers/Microsoft.Storage/storageAccounts/0storagecfrbqnnmpeudi",
"blobEndpoint": "https://0storagecfrbqnnmpeudi.blob.core.chinacloudapi.cn/",
"status": "available"
},
{
"id": "/subscriptions/{sub-id}/resourceGroups/{rg-name}/providers/Microsoft.Storage/storageAccounts/1storagecfrbqnnmpeudi",
"blobEndpoint": "https://1storagecfrbqnnmpeudi.blob.core.chinacloudapi.cn/",
"status": "available"
}
]
循环数组和索引
此示例同时使用数组和索引的元素。
param rgLocation string = resourceGroup().location
var stgNames = [
'demostg1'
'demostg2'
'demostg3'
]
resource stg 'Microsoft.Storage/storageAccounts@2021-02-01' = [for name in stgNames: {
name: name
location: rgLocation
kind: 'Storage'
sku: {
name: 'Standard_LRS'
tier: 'Standard'
}
}]
output stgOutput array = [for (name, i) in stgNames: {
name: stg[i].name
resourceId: stg[i].id
}]
输出返回具有以下值的数组:
[
{
"name": "demostg1",
"resourceId": "/subscriptions/{sub-id}/resourceGroups/{rg-name}/providers/Microsoft.Storage/storageAccounts/demostg1"
},
{
"name": "demostg2",
"resourceId": "/subscriptions/{sub-id}/resourceGroups/{rg-name}/providers/Microsoft.Storage/storageAccounts/demostg2"
},
{
"name": "demostg3",
"resourceId": "/subscriptions/{sub-id}/resourceGroups/{rg-name}/providers/Microsoft.Storage/storageAccounts/demostg3"
}
]
后续步骤
- 对于循环的其他使用,请参阅:
- 若要设置对循环中创建的资源的依赖关系,请参阅设置资源依赖关系。