Coder Perfect

In Bicep, how do I get the resource id?

Problem

How can we acquire the output string while creating the subnet and how do we output resource id in bicep? Virtual network syntax is mentioned here.

  "" resource virtualNetwork 'Microsoft.Network/virtualNetworks@2019-11-01' = {
      name: vnetName
      location: resourceGroup().location
      properties: {
        addressSpace: {
          addressPrefixes: [
            '10.0.0.0/16'
          ]
        }
        subnets: [
          {
            name: 'subnetpoc-1'
            properties: {
              addressPrefix: '10.0.3.0/24'
            }
          }
          {
            name: 'subnetnetpoc-2'
            properties: {
              addressPrefix: '10.0.4.0/24'
            }
          }
        ]
      }
    }

    // output subnet string = ""

Asked by cloudcop

Solution #1

You can do this with the resourceId function:

param vnetName string

resource virtualNetwork 'Microsoft.Network/virtualNetworks@2019-11-01' = {
  name: vnetName
  ...
}

// Return the 1st subnet id
output subnetId1 string = resourceId('Microsoft.Network/VirtualNetworks/subnets', vnetName, 'subnetpoc-1')

// Return the 2nd subnet id
output subnetId2 string = resourceId('Microsoft.Network/VirtualNetworks/subnets', vnetName, 'subnetpoc-2')

// Return as array
output subnetIdsArray array = [
  resourceId('Microsoft.Network/VirtualNetworks/subnets', vnetName, 'subnetpoc-1')
  resourceId('Microsoft.Network/VirtualNetworks/subnets', vnetName, 'subnetpoc-2')
]

// Return as object
output subnetIdsObject object = {
  subnetId1: resourceId('Microsoft.Network/VirtualNetworks/subnets', vnetName, 'subnetpoc-1')
  subnetId2: resourceId('Microsoft.Network/VirtualNetworks/subnets', vnetName, 'subnetpoc-2')
}



Answered by Thomas

Post is based on https://stackoverflow.com/questions/69654443/how-to-output-resource-id-in-bicep