Skip to content

'safe access' operator fails when used in arrayΒ #14705

Closed

Description

Bicep version
Bicep CLI version 0.29.47 (132ade5)

Describe the bug
I'm not quote sure what the issue actually is, but using the snippet provided in the 'To Reproduce' section I get the following error during deployment The template variable 'formattedRoleAssignments' is not valid: The provided arguments for template language function 'if' is not valid: all arguments should be of type 'boolean'. Please see https://aka.ms/arm-functions#if for usage details.

The corresponding failing code (that you'll find also below) is builtInRoleNames[?roleAssignment.roleDefinitionIdOrName] ?? (...)

It's quite unfortuante as we have a working implementation which however shows the warning that we should use the 'safe access' operator (Use the safe access (.?) operator instead of checking object contents with the 'contains' function), but if we do it fails.

To Reproduce
In the following I will first provide our working example that shows the warning in the Bicep template, and then the suggested fix by Bicep which fails the deployment.

Both templates are deployed/invoked using the following command
$roleAssignments = @(
    @{
        name = 'customname'
        roleDefinitionIdOrName = 'Owner'
        principalId            = '55555555-5555-5555-5555-555555555555'
        principalType          = 'ServicePrincipal'
    },
    @{
        roleDefinitionIdOrName = '/subscriptions/55555555-5555-5555-5555-555555555555/providers/Microsoft.Authorization/roleDefinitions/acdd72a7-3385-48ef-bd42-f606fba81ae7'
        principalId            = '55555555-5555-5555-5555-555555555555'
        principalType          = 'ServicePrincipal'
    }
)
New-AzDeployment -TemplateFile 'C:\temp\roleAssignmentFormatTest.bicep'  -Location 'WestEurope' -TemplateParameterObject @{ roleAssignments = $roleAssignments  } -Verbose

Before looking into the examples, here is a quick note on what they're supposed to do:

  • They're supposed to add a 'caluclated' property (roleDefinitionId) to each object of an array of objects (roleAssignments)
  • For the 'caluclation' it differentiates 3 cases
    1. If builtInRoleNames hashtable contains the roleDefinitionIdOrName value provided in the input parameter objects, grab it's value
    2. If it is not contained, check if the roleDefinitionIdOrName value provided in the input parameter objects contains the string '/providers/Microsoft.Authorization/roleDefinitions/'. If yes, just use the value of roleDefinitionIdOrName
    3. If it does not conain that string, add it as a prefix to the value of roleDefinitionIdOrName and use that combined value
Working example
@description('Optional. Array of role assignments to create.')
param roleAssignments roleAssignmentType

var builtInRoleNames = {
  Contributor: subscriptionResourceId('Microsoft.Authorization/roleDefinitions', 'b24988ac-6180-42a0-ab88-20f7382dd24c')
  Owner: subscriptionResourceId('Microsoft.Authorization/roleDefinitions', '8e3af657-a8ff-443c-a75c-2fe8c4bcb635')
  Reader: subscriptionResourceId('Microsoft.Authorization/roleDefinitions', 'acdd72a7-3385-48ef-bd42-f606fba81ae7')
}

output formattedRoles array = [
  for (roleAssignment, index) in (roleAssignments ?? []): union(roleAssignment, {
    roleDefinitionId: contains(builtInRoleNames, roleAssignment.roleDefinitionIdOrName)
      ? builtInRoleNames[roleAssignment.roleDefinitionIdOrName]
      : contains(roleAssignment.roleDefinitionIdOrName, '/providers/Microsoft.Authorization/roleDefinitions/')
          ? roleAssignment.roleDefinitionIdOrName
          : subscriptionResourceId('Microsoft.Authorization/roleDefinitions', roleAssignment.roleDefinitionIdOrName)
  })
]

// ================ //
// Definitions      //
// ================ //

type roleAssignmentType = {
  @description('Required. The role to assign. You can provide either the display name of the role definition, the role definition GUID, or its fully qualified ID in the following format: \'/providers/Microsoft.Authorization/roleDefinitions/c2f4ef07-c644-48eb-af81-4b1b4947fb11\'.')
  roleDefinitionIdOrName: string
}[]?
Log
PS C:\dev> New-AzDeployment -TemplateFile 'C:\temp\roleAssignmentFormatTest.bicep'  -Location 'WestEurope' -TemplateParameterObject @{ roleAssignments = $roleAssignments  } -Verbose
VERBOSE: Using Bicep v0.29.47
VERBOSE: Calling Bicep with arguments: build "C:\temp\roleAssignmentFormatTest.bicep" --outdir "C:\AppData\Local\Temp\d0e1f4ee-d608-4ed4-895f-cdfb6cc017ab"
VERBOSE: 
WARNING: C:\temp\roleAssignmentFormatTest.bicep(12,23) : Warning use-safe-access: Use the safe access (.?) operator instead of checking object contents with the 'contains' function. [https://aka.ms/bicep/linter/use-safe-access]

VERBOSE: 11:48:14 - Template is valid.
VERBOSE: 11:48:16 - Create template deployment 'roleAssignmentFormatTest'
VERBOSE: 11:48:16 - Checking deployment status in 5 seconds

Id                      : /subscriptions/<subId>/providers/Microsoft.Resources/deployments/roleAssignmentFormatTest
DeploymentName          : roleAssignmentFormatTest
Location                : westeurope
ProvisioningState       : Succeeded
Timestamp               : 30/07/2024 09:48:18
Mode                    : Incremental
TemplateLink            : 
Parameters              : 
                          Name               Type                       Value
                          =================  =========================  ==========
                          roleAssignments    Array                      [{"principalId":"55555555-5555-5555-5555-555555555555","name":"customname","principalType":"ServicePrincipal","roleDefinitionIdOrName":"Owner"},{"principalId":"","principalType":"ServicePrincipal","roleDefinitionIdOrName":"b24988ac-6180-42a0-ab88-20f7382dd24c"},{"principalId":"55555555-5555-5555-5555-555555555555","principalType":"ServicePrincipal","roleDefini 
                          tionIdOrName":"/subscriptions/55555555-5555-5555-5555-555555555555/providers/Microsoft.Authorization/roleDefinitions/acdd72a7-3385-48ef-bd42-f606fba81ae7"}]

Outputs                 : 
                          Name              Type                       Value
                          ================  =========================  ==========
                          formattedRoles    Array                      [{"principalId":"55555555-5555-5555-5555-555555555555","name":"customname","principalType":"ServicePrincipal","roleDefinitionIdOrName":"Owner","roleDefinitionId":"/subscriptions/<subId>/providers/Microsoft.Authorization/roleDefinitions/8e3af657-a8ff-443c-a75c-2fe8c4bcb635"},{"principalId":"","principalType":"ServicePrincipal","roleD 
                          efinitionIdOrName":"b24988ac-6180-42a0-ab88-20f7382dd24c","roleDefinitionId":"/subscriptions/<subId>/providers/Microsoft.Authorization/roleDefinitions/b24988ac-6180-42a0-ab88-20f7382dd24c"},{"principalId":"55555555-5555-5555-5555-555555555555","principalType":"ServicePrincipal","roleDefinitionIdOrName":"/subscriptions/55555555-5555-5555-5555-555555555555/providers/Microsoft.Au 
                          thorization/roleDefinitions/acdd72a7-3385-48ef-bd42-f606fba81ae7","roleDefinitionId":"/subscriptions/55555555-5555-5555-5555-555555555555/providers/Microsoft.Authorization/roleDefinitions/acdd72a7-3385-48ef-bd42-f606fba81ae7"}]

DeploymentDebugLogLevel : 
Failing example (using Bicep suggestion through autocrrection)
@description('Optional. Array of role assignments to create.')
param roleAssignments roleAssignmentType

var builtInRoleNames = {
  Contributor: subscriptionResourceId('Microsoft.Authorization/roleDefinitions', 'b24988ac-6180-42a0-ab88-20f7382dd24c')
  Owner: subscriptionResourceId('Microsoft.Authorization/roleDefinitions', '8e3af657-a8ff-443c-a75c-2fe8c4bcb635')
  Reader: subscriptionResourceId('Microsoft.Authorization/roleDefinitions', 'acdd72a7-3385-48ef-bd42-f606fba81ae7')
}

output formattedRoles array = [
  for (roleAssignment, index) in (roleAssignments ?? []): union(roleAssignment, {
    roleDefinitionId: builtInRoleNames[?roleAssignment.roleDefinitionIdOrName] ?? contains(
        roleAssignment.roleDefinitionIdOrName,
        '/providers/Microsoft.Authorization/roleDefinitions/'
      )
      ? roleAssignment.roleDefinitionIdOrName
      : subscriptionResourceId('Microsoft.Authorization/roleDefinitions', roleAssignment.roleDefinitionIdOrName)
  })
]

// ================ //
// Definitions      //
// ================ //

type roleAssignmentType = {
  @description('Required. The role to assign. You can provide either the display name of the role definition, the role definition GUID, or its fully qualified ID in the following format: \'/providers/Microsoft.Authorization/roleDefinitions/c2f4ef07-c644-48eb-af81-4b1b4947fb11\'.')
  roleDefinitionIdOrName: string
}[]?
Log
PS C:\dev> New-AzDeployment -TemplateFile 'C:\temp\roleAssignmentFormatTest.bicep'  -Location 'WestEurope' -TemplateParameterObject @{ roleAssignments = $roleAssignments  } -Verbose
VERBOSE: Using Bicep v0.29.47
VERBOSE: Calling Bicep with arguments: build "C:\temp\roleAssignmentFormatTest.bicep" --outdir "C:\AppData\Local\Temp\d1815c48-a441-4482-acee-3b4b3d668abb"
VERBOSE: 
VERBOSE: 11:48:57 - Template is valid.
VERBOSE: 11:48:58 - Create template deployment 'roleAssignmentFormatTest'
VERBOSE: 11:48:58 - Checking deployment status in 5 seconds
New-AzDeployment: 11:49:04 - The deployment 'roleAssignmentFormatTest' failed with error(s). Showing 1 out of 1 error(s).
Status Message: The template output 'formattedRoles' is not valid: The provided arguments for template language function 'if' is not valid: all arguments should be of type 'boolean'. Please see https://aka.ms/arm-functions#if for usage details.. (Code:DeploymentOutputEvaluationFailed)

CorrelationId: 1d5d6492-7158-47c4-955b-eda2053b93dc

Id                      : /subscriptions/<subId>/providers/Microsoft.Resources/deployments/roleAssignmentFormatTest
DeploymentName          : roleAssignmentFormatTest
Location                : westeurope
ProvisioningState       : Failed
Timestamp               : 30/07/2024 09:49:00
Mode                    : Incremental
TemplateLink            : 
Parameters              : 
                          Name               Type                       Value
                          =================  =========================  ==========
                          roleAssignments    Array                      [{"principalId":"55555555-5555-5555-5555-555555555555","name":"customname","principalType":"ServicePrincipal","roleDefinitionIdOrName":"Owner"},{"principalId":"","principalType":"ServicePrincipal","roleDefinitionIdOrName":"b24988ac-6180-42a0-ab88-20f7382dd24c"},{"principalId":"55555555-5555-5555-5555-555555555555","principalType":"ServicePrincipal","roleDefini 
                          tionIdOrName":"/subscriptions/55555555-5555-5555-5555-555555555555/providers/Microsoft.Authorization/roleDefinitions/acdd72a7-3385-48ef-bd42-f606fba81ae7"}]

Outputs                 : 
DeploymentDebugLogLevel : 

Activity

  1. jeskew commented on Jul 30, 2024

    @jeskew
    Contributor

    Alexander Sehr (@AlexanderSehr) if you want to keep the [?...] operator, you will need to wrap everything following the ?? in parentheses:

    output formattedRoles array = [
      for (roleAssignment, index) in (roleAssignments ?? []): union(roleAssignment, {
        roleDefinitionId: builtInRoleNames[?roleAssignment.roleDefinitionIdOrName] ?? (contains(
            roleAssignment.roleDefinitionIdOrName,
            '/providers/Microsoft.Authorization/roleDefinitions/'
          )
          ? roleAssignment.roleDefinitionIdOrName
          : subscriptionResourceId('Microsoft.Authorization/roleDefinitions', roleAssignment.roleDefinitionIdOrName))
      })
    ]

    The cause is that ternary expressions have higher precedence than any infix operator, so the formulation a ?? b ? c : d is equivalent to (a ?? b) ? c : d, whereas what you want is a ?? (b ? c : d). This seems to be documented correctly in the Bicep pseudo-grammar but incorrectly in the Microsoft Learn docs.

    Additionally, I think this is a bug in the quick fix/autocorrection -- it should probably be wrapping whatever follows the ?? in parentheses to account for this.

  2. added
    bug
    on Jul 30, 2024
  3. AlexanderSehr commented on Jul 31, 2024

    @AlexanderSehr
    ContributorAuthor

    Alexander Sehr (@AlexanderSehr) if you want to keep the [?...] operator, you will need to wrap everything following the ?? in parentheses:

    output formattedRoles array = [
      for (roleAssignment, index) in (roleAssignments ?? []): union(roleAssignment, {
        roleDefinitionId: builtInRoleNames[?roleAssignment.roleDefinitionIdOrName] ?? (contains(
            roleAssignment.roleDefinitionIdOrName,
            '/providers/Microsoft.Authorization/roleDefinitions/'
          )
          ? roleAssignment.roleDefinitionIdOrName
          : subscriptionResourceId('Microsoft.Authorization/roleDefinitions', roleAssignment.roleDefinitionIdOrName))
      })
    ]

    The cause is that ternary expressions have higher precedence than any infix operator, so the formulation a ?? b ? c : d is equivalent to (a ?? b) ? c : d, whereas what you want is a ?? (b ? c : d). This seems to be documented correctly in the Bicep pseudo-grammar but incorrectly in the Microsoft Learn docs.

    Additionally, I think this is a bug in the quick fix/autocorrection -- it should probably be wrapping whatever follows the ?? in parentheses to account for this.

    Ah that's great. Thanks Jonny Eskew (@jeskew). Just tested and can confirm πŸ’ͺ
    Getting the auto-correct 'fixed' would be great (though I guess it's just about making it more robust).
    It's what made me aware of the feature in the first place - just not with the best experience πŸ˜„

  4. added a commit that references this issue on Jul 31, 2024
    7ad70af
  5. moved this from Todo to Done in Bicepon Jul 31, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Needs: Triage πŸ”bug

    Type

    No type

    Projects

    • Status
      Done

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions