This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Assign Azure roles using Azure Resource Manager templates

  • 13 contributors

Azure role-based access control (Azure RBAC) is the authorization system you use to manage access to Azure resources. To grant access, you assign roles to users, groups, service principals, or managed identities at a particular scope. In addition to using Azure PowerShell or the Azure CLI, you can assign roles using Azure Resource Manager templates . Templates can be helpful if you need to deploy resources consistently and repeatedly. This article describes how to assign roles using templates.

Bicep is a new language for defining your Azure resources. It has a simpler authoring experience than JSON, along with other features that help improve the quality of your infrastructure as code. We recommend that anyone new to infrastructure as code on Azure use Bicep instead of JSON.

To learn about how to define role assignments by using Bicep, see Create Azure RBAC resources by using Bicep . For a quickstart example, see Quickstart: Assign an Azure role using Bicep .

Prerequisites

To assign Azure roles, you must have:

  • Microsoft.Authorization/roleAssignments/write permissions, such as Role Based Access Control Administrator or User Access Administrator

You must use the following versions:

  • 2018-09-01-preview or later to assign an Azure role to a new service principal
  • 2020-04-01-preview or later to assign an Azure role at resource scope
  • 2022-04-01 is the first stable version

For more information, see API versions of Azure RBAC REST APIs .

Get object IDs

To assign a role, you need to specify the ID of the user, group, or application you want to assign the role to. The ID has the format: 11111111-1111-1111-1111-111111111111 . You can get the ID using the Azure portal, Azure PowerShell, or Azure CLI.

To get the ID of a user, you can use the Get-AzADUser or az ad user show commands.

To get the ID of a group, you can use the Get-AzADGroup or az ad group show commands.

Managed identities

To get the ID of a managed identity, you can use Get-AzAdServiceprincipal or az ad sp commands.

Application

To get the ID of a service principal (identity used by an application), you can use the Get-AzADServicePrincipal or az ad sp list commands. For a service principal, use the object ID and not the application ID.

Assign an Azure role

In Azure RBAC, to grant access, you assign a role.

Resource group scope (without parameters)

The following template shows a basic way to assign a role. Some values are specified within the template. The following template demonstrates:

  • How to assign the Reader role to a user, group, or application at a resource group scope

To use the template, you must do the following:

  • Create a new JSON file and copy the template
  • Replace <your-principal-id> with the ID of a user, group, managed identity, or application to assign the role to

Here are example New-AzResourceGroupDeployment and az deployment group create commands for how to start the deployment in a resource group named ExampleGroup.

The following shows an example of the Reader role assignment to a user for a resource group after deploying the template.

Role assignment at resource group scope

Resource group or subscription scope

The previous template isn't very flexible. The following template uses parameters and can be used at different scopes. The following template demonstrates:

  • How to assign a role to a user, group, or application at either a resource group or subscription scope
  • How to specify the Owner, Contributor, and Reader roles as a parameter

To use the template, you must specify the following inputs:

  • The ID of a user, group, managed identity, or application to assign the role to
  • A unique ID that will be used for the role assignment, or you can use the default ID

This template is not idempotent unless the same roleNameGuid value is provided as a parameter for each deployment of the template. If no roleNameGuid is provided, by default a new GUID is generated on each deployment and subsequent deployments will fail with a Conflict: RoleAssignmentExists error.

The scope of the role assignment is determined from the level of the deployment. Here are example New-AzResourceGroupDeployment and az deployment group create commands for how to start the deployment at a resource group scope.

Here are example New-AzDeployment and az deployment sub create commands for how to start the deployment at a subscription scope and specify the location.

Resource scope

If you need to assign a role at the level of a resource, set the scope property on the role assignment to the name of the resource.

The following template demonstrates:

  • How to create a new storage account
  • How to assign a role to a user, group, or application at the storage account scope

To deploy the previous template, you use the resource group commands. Here are example New-AzResourceGroupDeployment and az deployment group create commands for how to start the deployment at a resource scope.

The following shows an example of the Contributor role assignment to a user for a storage account after deploying the template.

Role assignment at resource scope

New service principal

If you create a new service principal and immediately try to assign a role to that service principal, that role assignment can fail in some cases. For example, if you create a new managed identity and then try to assign a role to that service principal in the same Azure Resource Manager template, the role assignment might fail. The reason for this failure is likely a replication delay. The service principal is created in one region; however, the role assignment might occur in a different region that hasn't replicated the service principal yet.

To address this scenario, you should set the principalType property to ServicePrincipal when creating the role assignment. You must also set the apiVersion of the role assignment to 2018-09-01-preview or later. 2022-04-01 is the first stable version.

  • How to create a new managed identity service principal
  • How to specify the principalType
  • How to assign the Contributor role to that service principal at a resource group scope
  • The base name of the managed identity, or you can use the default string

Here are example New-AzResourceGroupDeployment and az deployment group create commands for how to start the deployment at a resource group scope.

The following shows an example of the Contributor role assignment to a new managed identity service principal after deploying the template.

Role assignment for a new managed identity service principal

  • Quickstart: Create and deploy ARM templates by using the Azure portal
  • Understand the structure and syntax of ARM templates
  • Create resource groups and resources at the subscription level
  • Azure Quickstart Templates

Coming soon: Throughout 2024 we will be phasing out GitHub Issues as the feedback mechanism for content and replacing it with a new feedback system. For more information see: https://aka.ms/ContentUserFeedback .

Submit and view feedback for

Additional resources

role assignment json

Wim Matthyssen

Azure infra, security & governance, azure development and ai/ml, azure identity and security, stéphane eyskens, cloud-native azure architecture, geert baeke, azure kubernetes service & containerization, maik van der gaag, azure infrastructure as code & devops, bart verboven, sammy deprez, azure ai, ml & cognitive services, sander van de velde.

role assignment json

Azure Roles

roles.png

In Azure, access and control of any resources is managed through Role based access control (RBAC). By being assinged a role, a user will be able to access or manage different aspects of a resource and it’s subordinate resources.

This guide depends on the following:

The roles will be given permissions on a Scope . To determine what a user is authorized to do in a specific scope, Azure checks what roles assignments are made to the scope you are trying to access.

Scopes can be anything from an entire tenant to a managementgroup, subscription, resourcegroup or resource, basically anything you can manage in Azure. These are referred to as the resource Id.

rbac-scope-no-label.png

Read more about scopes at Microsoft Docs

Role Assignments and Role Definitions

Role assignments are the components that tells Azure what permissions a user (identity) has been granted to a scope.

The Role assignment itself basically just links a role definition and a principal (identity) to a resource scope . The actual permissions are defined in the role definition . There can be many role assignments made for a single role definition.

All role assignments and role definitions in a certain scope, can be listed by simply looking in the Azure portal under Access control (IAM), this applies to almost any type of object you can manage in the portal.

IAM.png

You can see all assignable role- assignments in a scope by clicking the Role assignments tab.

You can see all assignable role- definitions in a scope by clicking the Roles tab in the Access control (IAM) page.

Role assignments

Open a subscription in your Azure environment and open the Access control (IAM) page and the Role Assignments tab. Here all the role assignments made for this scope will be listed. You can see in the Scope column where the role that applies for this subscription was assigned. If you don’t already have any assignments directly to this resource, try adding one by clicking the + Add button to make a new role assignment. Select the Owner role, click next, click + Select members and then add your own account, finish by clicking Review + Assign . When the assignments is ready you should see it in the list.

Let’s check the properties of this role assignment!

The portal shows a subset of the properties of the role assignment, you can get more properties by using the Azure resource manager (ARM) API, the simplest way is by using either Azure Cli or PowerShell.

To get all the role assignments for your subscription, use the PowerShell command below. The Scope should be a resource identifier, for a subscription it looks like this: /subscriptions/00000000-0000-0000-0000-000000000000 .

Replace the zeroes with your subscription Id.

You can see that each role assignment has a bunch of properties and that it’s identified with a unique RoleAssignmentId, note that the scope for the role assignment is a part of the RoleAssignmentId, this means that you can use the same roleassignment template for many different scopes.

To get the JSON representation of the role assignment you can use the ConvertTo-Json cmdlet and you can then output it to a file.

Making a role assignment

You can make a new role assignment using Azure Cli or PowerShell cmdlet New-AzRoleAssignment . However you can also make an ARM or Bicep template to deploy the role assignment, to save it in your repository “as code”. I’ve made an example with Bicep .

This is the name of the role assignment and must be a globally unique identifier (GUID). Best practice is to create a GUID using the scope, principal ID, and role ID together. You can use the bicep function guid() to generate a guid from the three values. If you plan to assign the role to a different scope that subscription, like a management group or resource group, you just replace the subscription().id with managementGroup().id or *resourceGroup.id() and change the targetscope accordingly.

properties:

Principalid:.

This is the Id of the principal (user account or managed identity) that you want to give permissions to. Here represented by a parameter.

roleDefinitionId:

This is the Id of the role definition you want to apply for this user, here represented by a parameter.

Deploy the Assignment

Role definitions.

You can see all assignable role-definitions in a scope by clicking the “Roles” tab in the Access control (IAM) page. By clicking the (Details) “View” link on the right you can see the permissions of a role. If you then click the “JSON” tab, you will see the JSON representation of the role, this is basically what you will use when you make new role-definitions as code.

You can retrieve them with PowerShell, just like you did with the role assignments.

To get the role definition for a single role as JSON to a file.

Let’s look a the JSON on the bult-in ‘owner’ role!

The displayname for the role definition.

This is the Unique Identifier for this role-definition. This id is used when doing a role-assignment.

The displayname of this role, please note that it is not unique, that means that two different role-definitions with the same name can be defined in two different scopes.

description:

A freetext description field that should briefly and simplified describe what permissions this role gives.

assignableScopes:

This is a list of all the scopes where this role definition can be assigned. Microsoft uses this property in to enable moving resouces between different scopes without having to make new role-definitions and assignments, in short - use the scope you are deploying the role definition to unless you are migrating things. This list is a JSON array, all scopes will be listed within the [] .

permissions:

In this key you will define the actual permissions that the role gives. Note that the permissions key is a JSON array [ ], with (theoretical) possibility to have more than one list of permissions. However I have never tried to pull off that stunt.

Every key in a permissions item is another JSON array [ ], which means that you can make lists of actions , notActions etc.

  • actions lists all the actions that this role can make, for the owner role this is just the wildcard * for everything.
  • notActions lists every action that you explicitly want to deny from this role, by listing things here, you can take away some of the permissions that were listed in actions .
  • dataActions lists all the dataActions that this role can make, this controls what the role can do with the data inside a resource, for example access to the files in a storage account. In Azure the controlplane for resource objects is separated from the dataplane in the resources.
  • notDataActions lists every dataAction that you explicitly want to deny from this role, by listing things here, you can take away some of the permissions that were listed in dataActions .

Custom Role definitions

There might be reasons you want to make your own custom roles to limit the amount of permissions you give away in your organisation. For example you may not want your application teams to be able to cancel, rename, or create subscriptions on their own, or even move them into another organisations Azure Active directory tenant.

Craft your role definition to you liking and then you can push it to Azure, either by using the Azure portal, ARM Api, Cli or PowerShell. Here is a Custom Owner role to give you a Bicep example to start from. Basically what you see in this file is the same properties that you saw when listing a role definition with PowerShell, with the difference that the Id is not yet determined. If you need some inspiration for permissions, view a role in the Azure portal and check the permissions tab, here you can search actions and dataactions.

Deploy the bicep role definition

I recommend deploying role definitions to Scopes high up in your structure, preferably to management groups. The role definitions can then be assigned in any subordinate scopes.

To deploy the same role defintion to a managmentgroup you must change the targetScope to ‘managementGroup’, replace subscription().id with managementGroup().id in both roleDefName declaration and assignableScopes . Like This! Then you run the following PowerShell:

This was how you can define and assign roles in Azure. By using code you can automate the assignments and in a later blogpost I will also cover how you can use Azure Blueprints to make the role assignments as part of your landing zone deployments. These techniques can be another piece of the puzzle to automate your subscription deployment process.

Please follow me on LinkedIn and let me know if you like my blog.

Assignment Naming Element

Assigning policy sets or policies, assignment scopes and excluded scopes, defining parameters with json, defining overrides with json, defining noncompliancemessages with json.

  • Defining parameters, overrides and nonComplianceMessages with a CSV file

Defining resourceSelectors

Defining metadata, defining enforcementmode.

  • Policy Exemptions

Policy Assignments

This chapter describes how Policy Assignments are handled by EPAC. To learn about how custom Policy and Policy Set definitions are managed, see the Policies and Policy Set Definitions .

Assignment JSON structure

Assignment JSON is hierarchical for efficient definitions, avoiding duplication (copy/paste) of JSON. Each branch of the tree is cumulative. Each tree node must include a nodeName - an arbitrary string exclusively used by EPAC to display an error location. EPAC concatenates a leading / and the nodeName entries encountered in the tree to create a "breadcrumbs" trail; therefore, we recommend that you use / to help separate the concatenated nodeName . The following (partial and invalid) assignment tree would create this error message.

JSON Schema

The GitHub repo contains a JSON schema which can be used in tools such as VS Code to provide code completion.

To utilize the schema add a $schema tag to the JSON file.

This schema is new in v7.4.x and may not be complete. Please let us know if we missed anything.

  • Every tree branch must accumulate a definitionEntry (or definitionEntryList ), Assignment naming ( name and displayName ) and scope element.
  • The elements parameters , overrides , resourceSelectors , notScope , enforcementMode , metadata , userAssignedIdentity , managedIdentityLocations , additionalRoleAssignments and nonComplianceMessages are optional.
  • For Policy Sets with large numbers of included Policies you should use a spreadsheet (CSV file) to manage effects (parameterized or effect overrides ), parameters and optional nonComplianceMessages . We recommend the CSV approach for Policy Sets with more than 10 included Policies.
  • EPAC continues to support deprecated elements initiativeId , initiativeName and ignoreBranch , Consider using their replacements policySetId , policySetName and enforcementMode instead.

The tree is not required to be balanced. The number of levels is not restricted; however, anything beyond 3 levels is unnecessary in real scenarios and would be difficult to read and manage as the depth increases.

Tree Structure

Assignment File Overview Diagram

Each Assignment is required to have a name which is used in it's resource id. EPAC also requires a displayName . The description is optional. For the allowed location assignment you specify the component with:

Multiple assignment naming components in a tree branch are string concatenated for each of the three fields.

Azure has a limit of 24 characters for the concatenated name string. EPAC displays an error if this limit is exceeded.

Each assignment assigns either a Policy or Policy Set. In EPAC this is done with a definitionEntry or a definitionEntryList . Exactly one occurrence must exist in any collated tree branch. For each entry, you need to specify one of the following:

  • policyName - custom Policy managed by EPAC. Specifying just the name allows EPAC to inject the correct definition scope.
  • policySetName - custom Policy Set managed by EPAC.
  • policyId - resource id for builtin Policy.
  • policySetId - resource id for builtin Policy Set.

displayName is an optional field to document the entry if the Policy name is a GUID. Builtin Policies and Policy Sets use a GUID.

Using definitionEntryList allows you to save on copy/paste tree branches. Without it, the number of branches would need to be duplicated as many times as the list has entries.

Each entry in the list creates an Assignment at each leaf of the tree. Since assignments must have unique names at a specific scope, the Assignment naming component must be amended for each list entry. In this sub-component you can decide if you want to concatenate the string by appending or prepending them by specifying append boolean value.

In the above example one of the children (leaf node) has the following Assignment name.

This example generates two assignments at the "prod" leaf per scope:

  • /providers/Microsoft.Management/managementGroups/ Contoso-Prod /providers/Microsoft.Authorization/policyAssignments/ pr-asb
  • displayName = "Prod Azure Security Benchmark"
  • description = "Prod Environment controls enforcement with Azure Security Benchmark Initiative."
  • /providers/Microsoft.Management/managementGroups/ Contoso-Prod /providers/Microsoft.Authorization/policyAssignments/ pr-nist-800-53-r5
  • displayName = "Prod NIST SP 800-53 Rev. 5"
  • description = "Prod Environment controls enforcement with NIST SP 800-53 Rev. 5 Initiative."

scope is required exactly once in each tree branch. Excluded scopes ( notScope ) are cumulative from global-settings.json and the entire tree branch; however, once a scope is defined notScope may not be defined at any child node.

Both scope and notScope are specific to an EPAC Environment using the pacSelector name , e.g., epac-dev and tenant .

notScope works the same. In addition "*" means all EPAC Environments which is most often used for resourceGroupPatterns .

Managed Identities and role assignments

Policies with a DeployIfNotExists or Modify effect need a Managed Identity (MI) and role assignments to execute remediation task. EPAC calculates the necessary role assignments based on the roleDefinitionIds in the Policy definition. By default EPAC uses a system-assigned Manged Identity. The team maintaining EPAC recommend system-assigned identities; however, your organization may have role assignment reasons to use user-assigned Managed Identities.

Defining managedIdentityLocations

Policy assignments requiring a Managed Identity (system-assigned or user-assigned) require a location managedIdentityLocations . You must specify the location based on EPAC Environment or use "*" to use the same location for all of the EPAC Environments. You can specify them in global-settings.jsonc or at any node in the tree. The last (closest to the leaf node) is the one chosen if multiple managedIdentityLocations entries are encountered in a tree branch.

Defining optional additionalRoleAssignments

In some scenarios you will need additionalRoleAssignments ; e.g., for diagnostics settings to Event Hubs, the target resource might be in a different Management Group and therefore the Managed Identity requires additional role assignments. You must specify the additionalRoleAssignments based on EPAC Environment or use "*" to use the same additionalRoleAssignments for all of the EPAC Environments.

User-assigned Managed Identities

Azure Policy can use a user-defined Managed Identity and EPAC allows you to use this functionality (new in version 7.0). You must specify the user-defined Managed Identity based on EPAC Environment or use "*" to use the same identity for all of the EPAC Environments (only possible in single tenant scenarios). Within each EPAC Environment entry, you can specify just the URI string indicating to use the same identity even if we are using a definitionEntryList , or in the case of a definitionEntryList can assign a different identity based on the definitionEntryList by specifying a matching policyName , policyId , policySetName or policySetId .

The rest (below) of the node components are optional.

parameters have a simple JSON structure. You do not need the additional value indirection Azure requests (EPAC will inject that indirection).

Too enable definitionEntryList , parameters not present in the Policy or Policy Set definition are quietly ignored.

overrides are in the same format as documented by Azure . They are cumulative in each tree branch. The selectors element is only used for Assignments of Policy Sets. They are not valid for Assignments of a single Policy.

If using definitionEntryList , you must add the policyName , policyId , policySetName or policySetId as used in the definitionEntryList item.

Assign a non-compliance message to the assignment, or individual non-compliance messages if the assignment is for an Policy Set. This value is an array of objects - each containing a message, and in the case of an initiative a policyDefinitionReferenceId. See this link for details.

If you use single definitionEntry , place them normally. If you use a definitionEntryList place them in the respective list entry.

Defining parameters , overrides and nonComplianceMessages with a CSV file

Assigning single or multiple security and compliance focused Policy Sets (Initiatives), such as Azure Security Benchmark, NIST 800-53 r5, PCI, NIST 800-171, etc, with just JSON parameters becomes very complex fast. Add to this the complexity of overriding the effect if it is not surfaced as a parameter in the Policy Set using overrides . Finally, adding the optional nonComplianceMessages further increases the complexity.

To address the problem of reading and maintaining hundreds or thousands of JSON lines, EPAC can use the content of a spreadsheet (CSV) to create parameters , overrides and optionally nonComplianceMessages for a single Policy assignment definitionEntry or multiple Policy definitions ( definitionEntryList ).

This approach is best for very large Policy Sets such as Azure Security Benchmark, NIST 800-53, etc. Smaller Policy Sets should still be handled with JSON parameters , overrides and nonComplianceMessages .

Start by generating documentation for one or more of those Policy Sets , then modify the effect and parameter columns for each type of environment types you will use. In the example header below the infrastructure environments prod, test, dev, and sandbox are used as prefixes to the columns for Effect and Parameters respectively. Optionally you can add a column for nonComplianceMessages . If you want to switch from JSON to CSV, you can generate this CSV file frm your already deployed Assignment(s) .

The CSV file generated contains the following headers/columns:

name,referencePath,policyType,category,displayName,description,groupNames,policySets,allowedEffects,allowedOverrides,prodEffect,testEffect,devEffect,sandboxEffect,prodParameters,testParameters,devParameters,sandboxParameters,nonComplianceMessages

Column explanations:

  • name is the name of the policyDefinition referenced by the Policy Sets being assigned.
  • referencePath is only used if the Policy is used more than once in at least one of the Policy Sets to disambiguate them. The format is <policySetName>//<policyDefinitionReferenceId> .
  • policyType , category , displayName , description , groupNames , policySets , allowedEffects are optional and not used for deployment planning. They assist you in filling out the <env>Effect columns.
  • <env>Effect columns must contain one of the allowedValues or allowedOverrides values. You define which scopes define each type of environment and what short name you give the environment type to use as a column prefix.
  • <env>Parameters can contain additional parameters. You can also specify such parameters in JSON. EPAC will use the union of all parameters.
  • nonComplianceMessages column is optional. The documentation script does not generate this columns.

EPAC will find the effect parameter name for each Policy in each Policy Set and use them. If no effect parameter is defined by the Policy Set, EPAC will use overrides to set the effect. EPAC will generate the policyDefinitionReferenceId for nonComplianceMessages .

After building the spreadsheet, you must reference the CSV file and the column prefix in each tree branch. parameterFile can be overridden in a child node; however, it is often used once per tree branch and defined adjacent to the 'definitionEntry or definitionEntryList .

In the child nodes specifying the scope(s) specify which column prefix to use for selecting the CSV columns with parameterSelector . The actual prefix names have no meaning; they only need to match between the JSON below and the CSV file.

The element nonComplianceMessageColumn may appear anywhere in the tree. Definitions at a child override the previous setting. If no nonComplianceMessageColumn is specified, the spreadsheet is not used for the (optional) nonComplianceMessages .

resourceSelectors may appear anywhere in the tree and are cumulative in any branch. They follow the standard Azure Format .

metadata is sometimes used to track tickets for changes. Do NOT specify EPAC-reserved elements roles and pacOwnerId . For the final metadata EPAC creates the union of instances in the entire tree branch.

enforcementMode is similar to the deprecated ignoreBranch ; it deploys the assignment and sets the assignment to Default or DoNotEnforce . DoNotEnforce allows a what-if analysis. enforcementMode may appear anywhere in the tree. Definitions at a child override the previous setting.

Example assignment files

Simple policy assignment (allowed locations).

In the simple case an assignment is a single assignment or with no difference in assignment , parameters , and definitionEntry across multiple scopes. In many scenarios "Allowed Locations" is such a simple Assignment. Such Assignments do not have child nodes, just the root node.

  • nodeName is required for error messages; it's value is immaterial. EPAC concatenates them in the current tree branch.
  • definitionEntry specifies that the custom Policy Set general-allowed-locations-policy-set from our starter kit. displayName has no meaning - it is for readability and in this instance is superfluous.
  • assignment fields name , displayName and description are used when creating the assignment.
  • This assignment has no metadata . You don't need an empty collection. EPAC will add pacOwnerId and roles metadata . Do not add them manually.
  • enforcementMode is set to default - it is superfluous.
  • parameters are obvious. Note: you don't add the value layer Azure inserts - EPAC takes care of that.
  • During Policy resource development (called epac-dev ) the Assignment is deployed to an EPAC development Management Group Epac-Mg-1 .
  • During Policy prod deployments ( tenant -wide), it is deployed to the tenant Management Group Epac-Mg-1 .
  • No notScope entries are specified.

If we remove the empty and superfluous entries, we arrive at:

Security-Focused Policy Assignment with JSON parameters

  • In the following example we named our root node ( nodeName ) /security/ . Since it is only used in case of error messages produced by EPAC during planning it's actual value doesn't matter as long as it's unique.
  • We use a definitionEntryList to create two assignments at every leaf (six assignments total).
  • For assignment string concatenation we append the strings in the definitionEntryList to the strings in the child nodes. You can see this best when you look at the description string in the child nodes. It will form a sentence when concatenated by append ing the definitionEntryList assignment field description .
  • The parameters specified in the children are specific to the IaC environment types and their scope . Note: a real assignment would define many more parameters. The set here is abbreviated since the actual set could easily exceed a hundred entries for each of the IaC environments. We'll see in the next example how to simplify large Policy Set parameters with a CSV file.

Security-Focused Policy Assignment with CSV file parameters

This example is the same as the previous, except we replaced inline JSON parameters with a CSV file and use the column prefixes in the CSV file to select which parameter values we use by:

  • Setting the file name at the root node with

json "parameterFile": "security-baseline-parameters.csv",

  • Setting the column prefix with parameterSelector to prod , nonprod and sandbox . For example:

The CSV file is explained above . The entire file is:

Inverted Policy Assignment (Tag Inheritance and Required Tags)

As mentioned above sometimes it is advantageous (to reduce the number of repetitions) to turn a definition on its head:

  • Common parameters , scope , definitionEntryList (with two Policies) at the root ( nodeName is /Tags/ ).
  • Start of the assignment strings ( append is defaulted to false ). Again look at description which will be a concatenated sentence.
  • The children define the tagName parameter and the second part of the strings for assignment . The set of parameters is the union of the root node and the child node.
  • This creates six Assignments (number of Policies assigned times number of children).

Non-Compliance Messages in a Policy Definition Assignment

An example of a policy assignment for a single policy definition with a default non-compliance message.

Non-Compliance Messages in a Policy Set Definition Assignment

An example of a policy assignment for a policy set definition with a default non-compliance message and a policy specific non-compliance message.

Non-Compliance Messages in a Policy Set Definition Assignment with a definitionEntryList

An example of how to use a non-compliance message when using a definitionEntryList list in the assignment.

Azure Authorization Assignment

This page shows how to write Terraform and Azure Resource Manager for Authorization Assignment and write them securely.

Review your .tf file for Azure best practices

Shisho Cloud, our free checker to make sure your Terraform configuration follows best practices, is available (beta).

azurerm_role_assignment (Terraform)

The Assignment in Authorization can be configured in Terraform with the resource name azurerm_role_assignment . The following sections describe 10 examples of how to use the resource and its parameters.

  • Example Usage from GitHub

Review your Terraform file for Azure best practices

  • condition optional - string
  • condition_version optional - string
  • description optional - string
  • id optional computed - string
  • name optional computed - string
  • principal_id required - string
  • principal_type optional computed - string
  • role_definition_id optional computed - string
  • role_definition_name optional computed - string
  • scope required - string
  • skip_service_principal_aad_check optional computed - bool
  • create optional - string
  • delete optional - string
  • read optional - string
  • update optional - string

>> from Terraform Registry

  • Explanation in Terraform Registry
Assigns a given Principal (User or Group) to a given Role.

Tips: Best Practices for The Other Azure Authorization Resources

In addition to the azurerm_role_definition, Azure Authorization has the other resources that should be configured for security reasons. Please check some examples of those resources and precautions.

azurerm_role_definition

Ensure to grant targeted permissions for roles

It is better to avoid giving too many permissions to a role. By following the principle of least privilege, you can reduce the risk of credential leakage.

Review your Azure Authorization settings

In addition to the above, there are other security points you should be aware of making sure that your .tf files are protected in Shisho Cloud.

Microsoft.Authorization/roleAssignments (Azure Resource Manager)

The roleAssignments in Microsoft.Authorization can be configured in Azure Resource Manager with the resource name Microsoft.Authorization/roleAssignments . The following sections describe how to use the resource and its parameters.

  • name required - string
  • type required - string
  • apiVersion required - string
The role definition ID used in the role assignment.
The principal ID assigned to the role. This maps to the ID inside the Active Directory. It can point to a user, service principal, or security group.

>> from Azure Resource Manager Documentation

The Other Related Azure Authorization Resources

Azure Authorization Azure User Assigned Identity

Azure Authorization Definition

  • Frequently asked questions

What is Azure Authorization Assignment?

Azure Authorization Assignment is a resource for Authorization of Microsoft Azure. Settings can be wrote in Terraform.

Where can I find the example code for the Azure Authorization Assignment?

For Terraform, the SamPoddar/caf-terraform-landingzones-starter , Elgeario/Starter and joshfranzen/caf-terraform-landingzones-starter source code examples are useful. See the Terraform Example section for further details.

For Azure Resource Manager, the LRuttenCN/cloud-custodian , LRuttenCN/cloud-custodian and juggernauthk108/pastebin source code examples are useful. See the Azure Resource Manager Example section for further details.

Automate config file reviews on your commits

Fix issues in your infrastructure as code with auto-generated patches.

Table of Contents

role assignment json

  • Best Practces for The Other Resources

role assignment json

Gain insights into your Azure role assignments on subscription level

Gain insights into your Azure role assignments on subscription level

List Azure role assignments and custom role definitions recursively with PowerShell and Azure CLI.

Jump to recipe

Azure Role-Based Access Control (RBAC)

Azure role-based access control (Azure RBAC) helps you manage who has access to Azure resources, what they can do with those resources, and what areas they have access to. Using RBAC in Azure for granular permissions makes it easy to assign permissions to users, groups, service principals, or managed identities. You can assign only the amount of access that users need to perform their jobs, thereby adhering to the principle of least privilege.

You have a ton of builtin roles to choose from, and you can also create your own custom roles if none of the builtin roles fit your use case.

I will not write a thesis on Azure RBAC, as you can find the necessary information on the Azure RBAC documentation page . I will, however, highlight a few shortcomings and how I worked around some of them.

List Azure role definitions

You can list role definitions in the portal , with Azure CLI , or PowerShell .

All these links read List all roles . That is a bit misleading, as they only list the roles in your current scope with any inherited from above (management groups). Any custom roles created in different subscriptions than the current one (or the one provided in scope parameter) will not be listed. A best practice is to create custom roles higher up in management groups so that they are inherited by all subscriptions below. This is not always done, and you might end up with custom roles in different subscriptions.

List Azure role assignments

You can list role assignments in the portal , with PowerShell , or with Azure CLI . There are different ways of listing role assignments, but no way to list all role assignments in your hierarchy recursively. You can list role assignments at a certain scope, with inherited assignments included. You can also find all role assignments for a specific user or group in Azure AD .

Shortcomings

As far as I can see, there are a few shortcomings. These are not critical, and there are other issues with the RBAC model, but I will not go into them here.

  • There is no central listing of role assignments for all scopes
  • There is no central listing of custom role definitions for all scopes
  • Role assignments and role definitions are not linked in any way other than in backend. If you try to delete a custom role definition still in use, you get an error message. You have to find all role assignments using the custom role definition and delete them first.
  • Role assignments and role definitions are not listed in Azure AD

Recently I was tasked with cleaning some clickOps’ed custom role definitions and converting them to Terraform. I needed to find all custom role definitions and all role assignments in all subscriptions in all management groups. I also needed to find all role assignments using the custom role definitions I was going to delete. Because of reasons I needed to create new role definitions, and could not import them into Terraform. Because of the shortcomings mentioned above, I had to write a script to list all role definitions and role assignments for all scopes.

I did not want to click through all of the subscriptions and management groups, so I wrote a script to do it for me.

Azure Governance Visualizer

At this point I would be remiss not to mention the Azure Governance Visualizer . It is a great tool created by Julian Hayward for visualizing your total Azure Governance. It lists all custom role definitions and every other detail you would need from your environment regarding RBAC and lot of other useful information. In this case it is too complex, and I wanted to focus on the RBAC part. Anyway, check it out if you need a great tool for visualizing your Azure Governance.

Log in with both Azure CLI and PowerShell

Recursively find all management groups and subscriptions, list all custom roles in all subscriptions, list all role assignments with relevant custom roles in all subscriptions, write everything to json files for documentation or investigation, prerequisites.

  • A user with Reader role on the management group level to list all management groups.
  • A user with Reader role on the subscription level to list all subscriptions and their assignments/definitions.
  • Azure PowerShell installed
  • Azure CLI installed

The script can be found in all its glory in GitHub . I will explain the different sections below.

I did not want the script to force a login of both PowerShell and Azure CLI every time I ran it. Therefore I needed some logic to check for login status and login if necessary.

Since there could be several management groups in different levels, I need to recursively find the management groups to list all subscriptions.

This part is a simple loop through all subscriptions and list all custom role definitions. I could have used the PowerShell cmdlet Get-AzRoleDefinition , but I wanted to use the Azure CLI command az role definition list to get some more relevant information. The other actions done for each subscription are also done in the same foreach loop.

This part is a simple loop through all custom roles in the current subscription and list all assignments. Exports them if required with exportAssignments parameter.

This part is a simple conversion from PowerShell objects to json with ConvertTo-Json and dumpt to json file.

  • Azure PowerShell

Some parameters are necessary in this script to make it dynamic.

  • topLvlMgmtGroup - [String] Id of your top level management group to start recursive listing.
  • customRolesOnly - [String] Set to true if exporting only custom roles. Defaults to true .
  • excludeRegexPattern - [String] Any exclusion RegEx pattern to use. Remember escape chars!
  • rolesFolder - [String] Folder where role definitions will be exported. Defaults to output .
  • exportAssignments - [Switch] Whether to export assignments to file or not.
  • subscription - [String] Subscription Id or name for when exporting in a single subscription.

Resulting json

Running the script results in some output to json files.

Role Definitions

It makes sense to only export custom role definitions, because the builtin ones are already pretty well documented.

For each custom role definition found, one file will be written. This is an example role and all guids are randomly generated.

Role Assignments

All role assignments will be exported if the relevant parameter is set.

Output to a single assignments.json:

I had some fun with this task, and maybe created an over engineered solution. Also I had the chance to practice my PowerShell-skills, which is a welcomed exercise!

Please let me know if you have a one-liner for this that I can use in the future 🙂

Search code, repositories, users, issues, pull requests...

Provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

  • Notifications

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement . We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

"Create all role assignments" from json missing from the article #105825

@rolyon

sopopa2 commented Feb 27, 2023

@issues-automation

AjayBathini-MSFT commented Feb 27, 2023

Sorry, something went wrong.

@YashikaTyagii

rolyon commented Feb 22, 2024

@prmerger-automator

No branches or pull requests

@rolyon

IMAGES

  1. Create or update Azure custom roles using the Azure portal

    role assignment json

  2. Enumeración de asignaciones de roles de Azure mediante Azure Portal

    role assignment json

  3. Create role assignments for different scopes with Bicep

    role assignment json

  4. List Azure role assignments using the Azure portal

    role assignment json

  5. Using Bicep to Deploy Azure Cosmos DB SQL Role Assignments

    role assignment json

  6. Assign Azure roles using the Azure portal

    role assignment json

VIDEO

  1. Fall 2023

  2. English Final Assignment : Role Play Class: 12

  3. Week 7 Organizational Role Play Video Assignment

  4. GROUP 11 ( PRESENTATION ASSIGNMENT 2 ROLE PLAY DISCUSSION)

  5. Assignment 8c Narrative Therapy Role play

  6. Create API (JSON/REST) Controller in C# Razor Project

COMMENTS

  1. Assign Azure roles using Azure Resource Manager templates

    How to assign the Reader role to a user, group, or application at a resource group scope. To use the template, you must do the following: Create a new JSON file and copy the template. Replace <your-principal-id> with the ID of a user, group, managed identity, or application to assign the role to. JSON. Copy.

  2. AZ-104: Create Custom Roles in Azure RBAC with JSON Files

    Step 2: Assign Roles to Users or Groups. Identify users or groups by their identifiers and associate roles: Replace <User or Group ID> with the actual Object IDs of users or the Microsoft Entra ID ...

  3. azure-docs/articles/role-based-access-control/role-assignments ...

    You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window.

  4. Scripting Azure AD application role assignments

    .\aad-apply-role-assignments.ps1 -TenantId xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx -ConfigFilePath ".\aad-role-assignments.json" If you are interested, this is how the script looks like: This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that ...

  5. Azure Roles :: theAutomationDude

    Role Assignments and Role Definitions. Role assignments are the components that tells Azure what permissions a user (identity) has been granted to a scope. The Role assignment itself basically just links a role definition and a principal (identity) to a resource scope. The actual permissions are defined in the role definition. There can be many ...

  6. Policy Assignments

    Assignment JSON structure JSON Schema Key Points Tree Structure Assignment Naming Element Assigning Policy Sets or Policies ... EPAC calculates the necessary role assignments based on the roleDefinitionIds in the Policy definition. By default EPAC uses a system-assigned Manged Identity. The team maintaining EPAC recommend system-assigned ...

  7. Azure Authorization Assignment

    For Azure Resource Manager, the LRuttenCN/cloud-custodian, LRuttenCN/cloud-custodian and juggernauthk108/pastebin source code examples are useful. See the Azure Resource Manager Example section for further details. Learn more about Azure Authorization Assignment - 10 code examples and parameters in Terraform and Azure Resource Manager.

  8. azure-rest-api-specs/roleAssignments.json at main

    "description": "If the number of role assignments to be listed exceeds the maxResults limit, a continuation token is returned in this response header. When a continuation token is returned in the response, it must be specified in a subsequent invocation of the list operation to continue listing the role assignments.",

  9. Azure custom RM role definition with special AssignableScopes

    AFAIK, you could not use wildcard within assignableScopes, the New-AzureRmRoleDefinition powershell command essentially calls the Role Definitions - Create Or Update REST API, the assignableScopes only accept three types, refer to this link. If you want to specify AssignableScopes to only some subset of subscription resource groups, you need to ...

  10. codewithme.cloud

    Azure Role-Based Access Control (RBAC) Azure role-based access control (Azure RBAC) helps you manage who has access to Azure resources, what they can do with those resources, and what areas they have access to. Using RBAC in Azure for granular permissions makes it easy to assign permissions to users, groups, service principals, or managed ...

  11. "Create all role assignments" from json missing from the article

    This guide tells us how to "Save all role assignments" to a file using: az role assignment list --all --include-inherited --output json > roleassignments.json. But it doesn't tell us how to "Create all role assignments" from the json file that we just exported using the above command. Can the article be updated to include the necessary information?

  12. Class RoleAssignment

    The role assignment ID. String name. The role assignment name. String type. The role assignment type. String scope. The role assignment scope. String roleDefinitionId. The role definition ID. String principalId. The principal ID. String principalType. The principal type of the assigned principal ID.

  13. python

    How do I get the role assignments like data curators, collection admins and the name of the users and service principals. You need to make below calls to get the name of the users and service principals. I am getting all the roles and Ids of users and service principal assigned to it using below URL.