Phil
Phil

Reputation: 2365

Azure Bicep contains for loop: For-expressions are not supported in this context

I would like to provide backward compatibility with an existing set of parameters.json files, so that if the property inboundSecurityRules doesn't exist, then we just use an empty array that can be unioned together with other Security rules, and passed to the nsg resource.


param p_subnet object;

var inboundSecurityRules = contains(p_subnet, 'inboundSecurityRules') ? [for rule in p_subnet.inboundSecurityRules: {
  name         : rule.name
  properties   : union(
    rule.properties,
    { destinationAddressPrefix: p_subnet.addressPrefix }
  )
}] : []

Bicep error:

For-expressions are not supported in this context. For-expressions may be used as values of resource, module, variable, and output declarations, or values of resource and module properties.

Does anyone know how can this functionality could be achieved with this limitation?

Cheers

Upvotes: 1

Views: 1352

Answers (1)

giaour
giaour

Reputation: 4071

ARM doesn't allow looping constructs within an if() function expression (which is what a Bicep ternary gets compiled down to), but you can nest the ternary within the for expression (instead of nesting the for expression within the ternary) to get around this limitation:

param p_subnet object

var inboundSecurityRules = [for rule in (contains(p_subnet, 'inboundSecurityRules') ? p_subnet.inboundSecurityRules : []): {
  name         : rule.name
  properties   : union(
    rule.properties,
    { destinationAddressPrefix: p_subnet.addressPrefix }
  )
}]

Upvotes: 3

Related Questions