Search code examples
azureazure-resource-managerazure-keyvaultazure-bicepinfrastructure-as-code

Using a loop in bicep gives casting error


I've read about for loops in bicep files and finally comes to this code. It has 2 arrays for users and app _(both needs different permissions). For access policies I loop over each item.

param keyVault_name string
param webapp_principleId string
param functionsApp_principleId string
param location string
param user_id string

var userPermission = [
  user_id 
]

var appPermission = [
  webapp_principleId
  functionsApp_principleId
]

resource keyVault_resource 'Microsoft.KeyVault/vaults@2022-07-01' = {
  name: keyVault_name
  location: location
  properties:{
    accessPolicies:[[for (app, index) in appPermission: {
      objectId: app
      tenantId: tenant().tenantId
      permissions: {
        secrets: [ 'get', 'list' ]
      }
    }], [for (user, index) in userPermission: {
      objectId: user
      tenantId: tenant().tenantId
      permissions: {
        secrets: [ 'get', 'list', 'set' ]
      }
    }]]
    sku: {
      family: 'A'
      name: 'standard'
    }
    tenantId: tenant().tenantId
  }
}

But code above gives me next error:

The enclosing array expected an item of type AccessPolicyEntry, but the provided item was of type object[]. bicep(BCP034)

According the documentation I've found it doesn't work like the code example. Is there a cast I need to do?


Solution

  • You are passing an array of array to the accessPolicies property, you would need to concat both arrays:

    param keyVault_name string
    param webapp_principleId string
    param functionsApp_principleId string
    param location string
    param user_id string
    
    var userPermission = [
      user_id 
    ]
    
    var appPermission = [
      webapp_principleId
      functionsApp_principleId
    ]
    
    var userAccessPolicies = [for (user, index) in userPermission: {
      objectId: user
      tenantId: tenant().tenantId
      permissions: {
        secrets: [ 'get', 'list', 'set' ]
      }
    }]
    
    var appAccessPolicies = [for (app, index) in appPermission: {
      objectId: app
      tenantId: tenant().tenantId
      permissions: {
        secrets: [ 'get', 'list' ]
      }
    }]
    
    var accessPolicies = concat(userAccessPolicies, appAccessPolicies)
    resource keyVault_resource 'Microsoft.KeyVault/vaults@2022-07-01' = {
      name: keyVault_name
      location: location
      properties:{
        accessPolicies:accessPolicies
        sku: {
          family: 'A'
          name: 'standard'
        }
        tenantId: tenant().tenantId
      }
    }