If you are using Bicep to create Azure resources, you might have encountered a situation where you need to assign a built-in role to a parameter. However, the Bicep syntax for role assignments requires you to use the role definition ID, which is a GUID value. This makes the code painful to read and maintain.
To fix this annoyance, you can use the following PowerShell script that creates a Bicep file with a variable for each built-in role:
# Run the Azure CLI command to list role definitions and store the output in a variable
$roleDefinitions = az role definition list | ConvertFrom-Json
# Initialize the output string with the opening of the Roles object
$output = "@export()`nvar Roles = {"
# Loop through each role definition to construct the body of the Roles object
foreach ($role in $roleDefinitions) {
# Remove characters not allowed in variable names and construct the line
$roleName = $role.roleName -replace '[()./-]', '' -replace ' ', ''
$output += "`n ${roleName}: '$($role.name)'"
}
# Close the Roles object
$output += "`n}"
# Output to a file
$output | Out-File -FilePath roletypes.bicep
The script fetches all the current roles, removes special characters and adds them to the Roles -variable.
Now you could take the roletypes.bicep in use in your Bicep by importing it like this:
@description('List of all Azure RBAC roles')
import {
Roles
} from 'roletypes.bicep'
And now where you would need to pass a role, you can do it like this:
roleDefinitionIds: [
Roles.Owner
]
You might want to run the script periodically to get the latest added new roles.
Author:Jani Nevalainen
More stories about Azure