Bicep Template for Azure Role Assignment

In this post, we go through a Bicep template for assigning a built-in role to a user principal.

Motivation 

It is time to use Bicep to lift another task for us. Azure role assignment.  

In a previous blog post, we learned how to create a virtual machine using a flexible Bicep template.  

After provisioning the virtual machine (VM), we needed to do another manual step to assign a role to the VM administrator. Now, we want to automate that step, so the entire process of VM provisioning is automated. 

However, this template along with the provided script can be used to assign any built-in AAzure role to any user principal.  

Requirements 

This template creates a role assignment for a specific User principal on the scope of a specified resource group. You need to have “User Access Administrator” role to assign a role to other principals.  

The Bicep template for role assignment requires the unique principal ID and the unique role ID. We provided a script which will retrieve those IDs using Azure CLI commands. At the time of writing this blog post, there is not a way to retrieve those parameters through the Bicep template itself.  

Template Code  

Complete files for this project can be found on GitHub. The directory has three files. 

  • The “role-assignment.bicep” file is the template file. 
  • The “deploy.sh” file. This script will be used to fetch roleDefinitionId and principalId which is required for deployment. The same script will also run the deployment command. 
  • The “README.md” file. Explains how to use the template. 

Deployment and Parameters 

This Bicep template does not have a common parameters file. We retrieve and set the parameters using a script (deploy.sh). The same script also creates a deployment using the provided Bicep template (role-assignment.bicep).  

When running the “deploy.sh” script, you will be prompted for 4 inputs.  

1. Email address of the User principal (e.g. [email protected]

2. The name of the built-in role (e.g. Contributor (or) Virtual Machine Administrator Login) 

3. The “Deployment Name” that you provide will be the name you will see on Azure portal (RG -> Settings -> Deployments) 

4. Resource group name. Use the name of an existing target resource group in the script when prompted. 

Once all the parameters are provided, the script will create a deployment based on the Bicep template with provided parameters. You should receive a success message when finished.  

Conclusions 

As mentioned above, this template can be used along with the virtual machine template to automate the entire process. Currently, these two steps are not chained together. A next step to improve the solution is to create a new template which consists of both templates.