如何使用 Bicep 引用对象数组中的对象

How to reference an object in an array of objects using Bicep

我正在尝试在创建具有 4 个子网的虚拟网络的模块中输出每个子网的 referenceId。我可以得到第一个,[0],但是当我尝试输出其他的时,[1], [2], [3] 部署失败并抛出错误:

The language expression property array index "1" is out of bounds

下面是创建虚拟网络和子网的代码:

resource virtualNetwork 'Microsoft.Network/virtualNetworks@2018-11-01' = {
  name: vNetName
  location: location
  tags: tags
  properties: {
    addressSpace: {
      addressPrefixes: [
        addressPrefix
      ]
    }
    subnets: subnets
  }
}

subnets是数组类型的变量:

var subnets = [
  {
    name: mgmtSubnetName
    properties: {
      addressPrefix: mgmtSubnetAddressPrefix
    }
  }
  {
    name: intSubnetName
    properties: {
      addressPrefix: intSubnetAddressPrefix
    }
  }
  {
    name: extSubnetName
    properties: {
      addressPrefix: extSubnetAddressPrefix
    }
  }
  {
    name: vdmsSubnetName
    properties: {
      addressPrefix: vdmsSubnetAddressPrefix
    }
  }
]

当我使用下面的输出行时,它 returns 和具有 4 个对象的数组...每个创建的子网一个:

output subnets array = virtualNetwork.properties.subnets

每个对象的格式如下:

{
    "name":"<value>",
    "id":"<value>",
    "etag":"<value>",
    "properties":{
        "provisioningState":"Succeeded",
        "addressPrefix":"<value>",
        "ipConfigurations":[
            {
                "id":"<value>"
            }
        ],
        "delegations":[]
    },
    "type":"Microsoft.Network/virtualNetworks/subnets"
}

当我使用下面的输出行时,它 returns 子网数组中的第一个对象:

output subnet1 object = virtualNetwork.properties.subnets[0]

当我使用下面的输出行时,它 returns 第一个子网的 resourceId:

output subnet1 string = virtualNetwork.properties.subnets[0].id

我无法使用索引 1, 2,3.

检索数组中的其他对象

我也尝试过 resourceId 函数(下面的示例),但对于索引 1, 2,3:

的行为完全相同

output subnet1Id string = resourceId('Microsoft.Network/VirtualNetworks/subnets', name, subnets[0].name)

您可以使用下面的 bicep 模板部署 vnet 和子网并输出子网和子网 ID's,如下所示:

var subnets = [
  {
    name: 'vm-subnet'
    properties: {
      addressPrefix:'10.0.0.0/24'
    }
  }
  {
    name: 'webapp-subnet'
    properties: {
      addressPrefix:'10.0.1.0/24'
    }
  }
  {
    name: 'appgw-subnet'
    properties: {
      addressPrefix:'10.0.2.0/24'
    }
  }
  {
    name: 'bastion-subnet'
    properties: {
      addressPrefix:'10.0.3.0/24'
    }
  }
]
resource virtualNetwork 'Microsoft.Network/virtualNetworks@2018-11-01' = {
  name: 'ansuman-vnet'
  location: 'east us'
  properties: {
    addressSpace: {
      addressPrefixes: [
        '10.0.0.0/16'
      ]
    }
    subnets: subnets
  }
}

output subnets array = [for (name, i) in subnets :{
  subnets : virtualNetwork.properties.subnets[i]
}]

output subnetids array = [for (name, i) in subnets :{
  subnets : virtualNetwork.properties.subnets[i].id
}]

output subnetappgw string = virtualNetwork.properties.subnets[2].id

output webappsubnet object = virtualNetwork.properties.subnets[1]

输出:

注意:我使用的是最新的 Bicep 版本,即 Bicep CLI version 0.4.1124