本文說明如何使用 for 語法遍歷集合中的項目。 此功能從 v0.3.1 開始支援。 您可以使用迴圈來定義資源、模組、變數、屬性或輸出的多個副本。 使用迴圈可避免在 Bicep 檔案中重複語法,並在部署期間動態設定要建立的副本數量。 請參閱 快速入門:在 Bicep 中建立多個資源實例 ,以取得如何使用不同 for 語法在 Bicep 中建立多個資源實例的快速入門。
若要使用迴圈來建立多個資源或模組,每個實例都必須有 屬性的唯一值 name 。 您可以使用索引值或陣列或集合中的唯一值來建立名稱。
迴圈語法
迴圈可以透過以下方式宣告:
使用整數索引。 當您的情境是「我想建立這麼多執行個體」時,此選項適用。range 函數會建立一個從起始索引開始並包含指定元素數量的整數陣列。 在迴圈中,您可以使用整數索引修改值。 如需更多資訊,請參閱整數索引。
[for <index> in range(<startIndex>, <numberOfElements>): { ... }]使用 陣列中的專案:當您的案例是「我想要為陣列中的每個元素建立實例」時,此選項可運作。在迴圈中,您可以使用目前陣列元素的值來修改值。 如需更多資訊,請參閱陣列元素。
[for <item> in <collection>: { ... }]在 字典物件中使用項目:當您的案例為「我想要為字典物件中的每個項目建立實例」時,此選項可運作。items 函式 會將物件轉換成陣列。 在迴圈中,您可以使用物件的屬性來建立值。 如需更多資訊,請參閱字典物件。
[for <item> in items(<object>): { ... }]在 陣列中使用整數索引和元素:此選項適用於您的案例:「我想為陣列中的每個元素建立實例,但我也需要目前的索引來建立另一個值。」如需詳細資訊,請參閱 迴圈陣列和索引。
[for (<item>, <index>) in <collection>: { ... }]新增 條件式部署:此選項適用於您的案例為「我想要建立多個實例,但在條件成立時,我只想要部署每個實例」。如需詳細資訊,請參閱 迴圈與條件。
[for <item> in <collection>: if(<condition>) { ... }]
迴圈限制
在 Bicep 中使用迴圈有以下限制:
- Bicep 迴圈僅適用於可在部署開始時確定的值。
- 迴圈迭代次數不能為負數,也不能超過 800 次。
- 由於資源無法對巢狀子資源進行迴圈,請將子資源改為頂層資源。 如需詳細資訊,請參閱 子資源的反覆處理。
- 若要在多個屬性層級上執行迴圈,請使用 Lambda
map函式。
整數索引
如需使用索引的簡單範例,請建立包含字串陣列的 變數 :
param itemCount int = 5
var stringArray = [for i in range(0, itemCount): 'item${(i + 1)}']
output arrayResult array = stringArray
輸出傳回包含以下值的陣列:
[
"item1",
"item2",
"item3",
"item4",
"item5"
]
下一個範例會依照 storageCount 參數中指定的數量建立儲存體帳戶。 它會針對每個記憶體帳戶傳回三個屬性:
param location string = resourceGroup().location
param storageCount int = 2
resource storageAcct 'Microsoft.Storage/storageAccounts@2025-06-01' = [for i in range(0, storageCount): {
name: '${i}storage${uniqueString(resourceGroup().id)}'
location: location
sku: {
name: 'Standard_LRS'
}
kind: 'Storage'
}]
output storageInfo array = [for i in range(0, storageCount): {
id: storageAcct[i].id
blobEndpoint: storageAcct[i].properties.primaryEndpoints.blob
status: storageAcct[i].properties.statusOfPrimary
}]
請注意,在建立儲存體帳戶資源名稱時使用了索引 i。
下一個範例會多次部署模組:
param location string = resourceGroup().location
param storageCount int = 2
var baseName = 'store${uniqueString(resourceGroup().id)}'
module stgModule './storageAccount.bicep' = [for i in range(0, storageCount): {
name: '${i}deploy${baseName}'
params: {
storageName: '${i}${baseName}'
location: location
}
}]
output storageAccountEndpoints array = [for i in range(0, storageCount): {
endpoint: stgModule[i].outputs.storageEndpoint
}]
陣列元素
下列範例會針對 storageNames 參數中提供的每個名稱建立一個儲存體帳戶。 請注意,每個資源實體的名稱屬性必須是唯一的:
param location string = resourceGroup().location
param storageNames array = [
'contoso'
'fabrikam'
'coho'
]
resource storageAcct 'Microsoft.Storage/storageAccounts@2025-06-01' = [for name in storageNames: {
name: '${name}${uniqueString(resourceGroup().id)}'
location: location
sku: {
name: 'Standard_LRS'
}
kind: 'Storage'
}]
下一個範例會反覆存取陣列以定義某個屬性。 它會在虛擬網路中建立兩個子網路。 請注意,子網名稱必須是唯一的:
param rgLocation string = resourceGroup().location
var subnets = [
{
name: 'api'
subnetPrefix: '10.144.0.0/24'
}
{
name: 'worker'
subnetPrefix: '10.144.1.0/24'
}
]
resource vnet 'Microsoft.Network/virtualNetworks@2025-01-01' = {
name: 'vnet'
location: rgLocation
properties: {
addressSpace: {
addressPrefixes: [
'10.144.0.0/20'
]
}
subnets: [for subnet in subnets: {
name: subnet.name
properties: {
addressPrefix: subnet.subnetPrefix
}
}]
}
}
陣列和索引
下列範例會在定義記憶體帳戶時,同時使用數位元素和索引值:
param storageAccountNamePrefix string
var storageConfigurations = [
{
suffix: 'local'
sku: 'Standard_LRS'
}
{
suffix: 'geo'
sku: 'Standard_GRS'
}
]
resource storageAccountResources 'Microsoft.Storage/storageAccounts@2025-06-01' = [for (config, i) in storageConfigurations: {
name: '${storageAccountNamePrefix}${config.suffix}${i}'
location: resourceGroup().location
sku: {
name: config.sku
}
kind: 'StorageV2'
}]
下一個範例會使用陣列元素和索引來輸出新資源的相關資訊:
param location string = resourceGroup().location
param orgNames array = [
'Contoso'
'Fabrikam'
'Coho'
]
resource nsg 'Microsoft.Network/networkSecurityGroups@2025-01-01' = [for name in orgNames: {
name: 'nsg-${name}'
location: location
}]
output deployedNSGs array = [for (name, i) in orgNames: {
orgName: name
nsgName: nsg[i].name
resourceId: nsg[i].id
}]
Dictionary 物件
若要迭代字典物件中的元素,請使用 items 函數,將物件轉換成陣列。 使用 value 屬性可取得物件上的屬性。 請注意 nsg 資源名稱必須是唯一的。
param nsgValues object = {
nsg1: {
name: 'nsg-westus1'
location: 'westus'
}
nsg2: {
name: 'nsg-east1'
location: 'eastus'
}
}
resource nsg 'Microsoft.Network/networkSecurityGroups@2025-01-01' = [for nsg in items(nsgValues): {
name: nsg.value.name
location: nsg.value.location
}]
具有條件的迴圈
對於資源和模組,您可以在迴圈語法中加入 if 運算式,以條件式部署集合。
下列範例示範了將迴圈與條件陳述式結合使用。 在此範例中,單一條件會套用至模組的所有實例:
param location string = resourceGroup().location
param storageCount int = 2
param createNewStorage bool = true
var baseName = 'store${uniqueString(resourceGroup().id)}'
module stgModule './storageAccount.bicep' = [for i in range(0, storageCount): if(createNewStorage) {
name: '${i}deploy${baseName}'
params: {
storageName: '${i}${baseName}'
location: location
}
}]
下一個範例示範如何套用特定於陣列中當前元素的條件:
resource parentResources 'Microsoft.Example/examples@2024-06-06' = [for parent in parents: if(parent.enabled) {
name: parent.name
properties: {
children: [for child in parent.children: {
name: child.name
setting: child.settingValue
}]
}
}]
批次部署
根據預設,Azure 資源會以平行方式部署。 當您使用迴圈建立某個資源類型的多個執行個體時,這些執行個體會同時部署。 無法保證它們的建立順序。 除了 Bicep 檔案中 800 個資源的總限制以外,平行部署的資源數目沒有限制。
您可能不想同時更新某個資源類型的所有執行個體。 例如,在更新生產環境時,您可能希望逐步更新,每次只允許一定數量的更新。 您可以指定一部分執行個體分批一起部署。 其他執行個體會等候該批次完成。
若要串行化部署資源的實例,請新增 batchSize 裝飾專案。 將其值設定為要並行部署的執行個體數量。 在迴圈中的先前實例期間會建立相依性,因此在上一個批次完成之前不會啟動一個批次。
param location string = resourceGroup().location
@batchSize(2)
resource storageAcct 'Microsoft.Storage/storageAccounts@2025-06-01' = [for i in range(0, 4): {
name: '${i}storage${uniqueString(resourceGroup().id)}'
location: location
sku: {
name: 'Standard_LRS'
}
kind: 'Storage'
}]
若要進行序列部署,請將批次大小設定為 1。
batchSize 裝飾項目位於 sys 命名空間中。 如果您需要將此裝飾項目與其他同名項目區分,可在裝飾項目前加上 sys:@sys.batchSize(2)
子資源的反覆運算
若要建立一個以上的子資源執行個體,下列兩種 Bicep 檔案皆支援此工作:
巢狀子資源
param location string = resourceGroup().location
resource stg 'Microsoft.Storage/storageAccounts@2025-06-01' = {
name: 'examplestorage'
location: location
kind: 'StorageV2'
sku: {
name: 'Standard_LRS'
}
resource service 'fileServices' = {
name: 'default'
resource share 'shares' = [for i in range(0, 3): {
name: 'exampleshare${i}'
}]
}
}
頂層子資源
resource stg 'Microsoft.Storage/storageAccounts@2025-06-01' = {
name: 'examplestorage'
location: resourceGroup().location
kind: 'StorageV2'
sku: {
name: 'Standard_LRS'
}
}
resource service 'Microsoft.Storage/storageAccounts/fileServices@2025-06-01' = {
name: 'default'
parent: stg
}
resource share 'Microsoft.Storage/storageAccounts/fileServices/shares@2025-06-01' = [for i in range(0, 3): {
name: 'exampleshare${i}'
parent: service
}]
參考資源或模組集合
Azure Resource Manager 範本 (ARM 範本) references 函式會傳回代表資源集合運行時間狀態的物件數位。 由於 Bicep 中沒有明確的 references 函式,而且會直接使用符號集合使用方式,因此 Bicep 會將它轉譯為 ARM 範本,以在程式碼產生時利用 ARM 範本 references 函式。 針對使用 函 references 式將符號集合轉換成 ARM 範本的轉譯功能,必須有 Bicep CLI 0.20.X 版或更高版本。 此外,在 bicepconfig.json 檔案中, symbolicNameCodegen 應該呈現設定並設定為 true。
在整數索引中的兩個範例之輸出可寫成如下:
param location string = resourceGroup().location
param storageCount int = 2
resource storageAcct 'Microsoft.Storage/storageAccounts@2025-06-01' = [for i in range(0, storageCount): {
name: '${i}storage${uniqueString(resourceGroup().id)}'
location: location
sku: {
name: 'Standard_LRS'
}
kind: 'Storage'
}]
output storageInfo array = map(storageAcct, store => {
blobEndpoint: store.properties.primaryEndpoints
status: store.properties.statusOfPrimary
})
output storageAccountEndpoints array = map(storageAcct, store => store.properties.primaryEndpoints)
此 Bicep 檔案會編譯成下列 ARM JSON 範本,該範本使用 references 函式:
{
"$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
"languageVersion": "1.10-experimental",
"contentVersion": "1.0.0.0",
"parameters": {
"location": {
"type": "string",
"defaultValue": "[resourceGroup().location]"
},
"storageCount": {
"type": "int",
"defaultValue": 2
}
},
"resources": {
"storageAcct": {
"copy": {
"name": "storageAcct",
"count": "[length(range(0, parameters('storageCount')))]"
},
"type": "Microsoft.Storage/storageAccounts",
"apiVersion": "2023-04-01",
"name": "[format('{0}storage{1}', range(0, parameters('storageCount'))[copyIndex()], uniqueString(resourceGroup().id))]",
"location": "[parameters('location')]",
"sku": {
"name": "Standard_LRS"
},
"kind": "Storage"
}
},
"outputs": {
"storageInfo": {
"type": "array",
"value": "[map(references('storageAcct', 'full'), lambda('store', createObject('blobEndpoint', lambdaVariables('store').properties.primaryEndpoints, 'status', lambdaVariables('store').properties.statusOfPrimary)))]"
},
"storageAccountEndpoints": {
"type": "array",
"value": "[map(references('storageAcct', 'full'), lambda('store', lambdaVariables('store').properties.primaryEndpoints))]"
}
}
}
請注意在前述的 ARM JSON 範本中,languageVersion 必須設定為 1.10-experimental,且資源項目為物件而非陣列。
後續步驟
若要瞭解如何建立 Bicep 檔案,請參閱 Bicep 檔案結構和語法。