Welcome to Pedholtlab

Export role assignments for all Azure subscriptions

Microsoft has done it straightforward to get an overview of Azure role assignments for a subscription. They have added the  Download role assignments  button in the Azure portal under Subscriptions. When I’m working with customers that have many subscriptions, I’ll like to get an overview of all the subscriptions at once. Therefore I use PowerShell the export role assignments for all Azure subscriptions at once.

azure role assignment multiple subscriptions

Script parameters

There are 2 parameters in the script, $OutputPath and $SelectCurrentSubscription . None of them are mandatory.

$OutputPath: If defined, a CSV file will be exported to the chosen location. Example:  .\Export-RoleAssignments.ps1 -OutputPath C:\temp

$SelectCurrentSubscription: Will only export role assignments from the subscription that are selected. Example:  .\Export-RoleAssignments.ps1 -SelectCurrentSubscription

Run  Get-Azcontext  to view which subscription is selected.

Script Output

Besides getting an overview of the overall role assignments in an Azure subscription, I also like to know if a role is a Custom or Built-in role. The script will check each assignment if CustomRole is True or False.

Output Example in Powershell Console

azure role assignment multiple subscriptions

Output Example to CSV File

azure role assignment multiple subscriptions

The PowerShell Script

The Powershell script will be available on my account Github . Go there for the latest updates (article script will not be synced with the GitHub version).

3 thoughts on “ Export role assignments for all Azure subscriptions ”

' src=

Can you edit the script that when roles assigned to groups the group members are also exported in that csv?

' src=

getting the following error on azuread part:

PS C:\scripts> .\azure.ps1 -OutPutPath C:\temp VERBOSE: Running for all subscriptions in tenant VERBOSE: Changing to Subscription Access to Azure Active Directory VERBOSE: Getting information about Role Assignments… WARNING: We have migrated the API calls for this cmdlet from Azure Active Directory Graph to Microsoft Graph. Visit https://go.microsoft.com/fwlink/?linkid=2181475 for any permission issues. Get-AzRoleAssignment : Operation returned an invalid status code ‘BadRequest’ At C:\scripts\azure.ps1:39 char:14 + $roles = Get-AzRoleAssignment | Select-Object RoleDefinitionName, … + ~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : CloseError: (:) [Get-AzRoleAssignment], ErrorResponseException + FullyQualifiedErrorId : Microsoft.Azure.Commands.Resources.GetAzureRoleAssignmentCommand

' src=

You have to edit the script for it to work again. You will have to change the API call to Microsoft Graph. Maybe I will do it at some point.

Leave a Reply Cancel reply

Your email address will not be published.

Azure RBAC: role assignments and ARM templates

John Reilly

This post is about Azure's role assignments and ARM templates. Role assignments can be thought of as "permissions for Azure".

If you're deploying to Azure, there's a good chance you're using ARM templates to do so. Once you've got past "Hello World", you'll probably find yourself in a situation when you're deploying multiple types of resource to make your solution. For instance, you may be deploying an App Service alongside Key Vault and Storage .

One of the hardest things when it comes to deploying software and having it work, is permissions. Without adequate permissions configured, the most beautiful code can do nothing . Incidentally, this is a good thing. We're deploying to the web; many people are there, not all good. As a different kind of web-head once said:

Spider-man saying with great power, comes great responsibility

Azure has great power and suggests you use it wisely .

Access management for cloud resources is critical for any organization that uses the cloud. 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. Designating groups or individual roles responsible for specific functions in Azure helps avoid confusion that can lead to human and automation errors that create security risks. Restricting access based on the need to know and least privilege security principles is imperative for organizations that want to enforce security policies for data access.

This is good advice. With that in mind, how can we ensure that the different resources we're deploying to Azure can talk to one another?

Role (up for your) assignments ​

The answer is roles. There's a number of roles that exist in Azure that can be assigned to users, groups, service principals and managed identities. In our own case we're using managed identity for our resources. What we can do is use "role assignments" to give our managed identity access to given resources. Arturo Lucatero gives a great short explanation of this:

Whilst this explanation is delightfully simple, the actual implementation when it comes to ARM templates is a little more involved. Because now it's time to talk "magic" GUIDs. Consider the following truncated ARM template, which gives our managed identity (and hence our App Service which uses this identity) access to Key Vault and Storage:

Let's take a look at these three variables:

The three variables above contain the subscription resource ids for the roles Storage Blob Data Contributor , Key Vault Secrets Officer and Key Vault Crypto Officer . The first question on your mind is likely: "what is ba92f5b4-2d11-453d-a403-e96b0029c9fe and where does it come from?" Great question! Well, each of these GUIDs represents a built-in role in Azure RBAC. The ba92f5b4-2d11-453d-a403-e96b0029c9fe represents the Storage Blob Data Contributor role.

How can I look these up? Well, there's two ways; there's an article which documents them here or you could crack open the Cloud Shell and look up a role by GUID like so:

Or by name like so:

As you can see, the Actions section of the output above (and in even more detail on the linked article ) provides information about what the different roles can do. So if you're looking to enable one Azure resource to talk to another, you should be able to refer to these to identify a role that you might want to use.

Creating a role assignment ​

So now we understand how you identify the roles in question, let's take the final leap and look at assigning those roles to our managed identity. For each role assignment, you'll need a roleAssignments resource defined that looks like this:

Let's go through the above, significant property by significant property (it's also worth checking the official reference here ):

  • type - the type of role assignment we want to create, for a key vault it's "Microsoft.KeyVault/vaults/providers/roleAssignments" , for storage it's "Microsoft.Storage/storageAccounts/providers/roleAssignments" . The pattern is that it's the resource type, followed by "/providers/roleAssignments" .
  • dependsOn - before we can create a role assignment, we need the service principal we desire to permission (in our case a managed identity) to exist
  • properties.roleDefinitionId - the role that we're assigning, provided as an id. So for this example it's the keyVaultCryptoOfficer variable, which was earlier defined as [subscriptionResourceId('Microsoft.Authorization/roleDefinitions', 'ba92f5b4-2d11-453d-a403-e96b0029c9fe')] . (Note the use of the GUID)
  • properties.principalId - the id of the principal we're adding permissions for. In our case this is a managed identity (a type of service principal).
  • properties.scope - we're modifying another resource; our key vault isn't defined in this ARM template and we want to specify the resource we're granting permissions to.
  • properties.principalType - the type of principal that we're creating an assignment for; in our this is "ServicePrincipal" - our managed identity.

There is an alternate approach that you can use where the type is "Microsoft.Authorization/roleAssignments" . Whilst this also works, it displayed errors in the Azure tooling for VS Code . As such, we've opted not to use that approach in our ARM templates.

Many thanks to the awesome John McCormick who wrangled permissions with me until we bent Azure RBAC to our will.

  • Role (up for your) assignments
  • Creating a role assignment

azure role assignment multiple subscriptions

avatar

Manage Azure Role Assignments Like a Pro with PowerShell

Azure Governance Future Trends and Predictions - AzureIs.Fun

Today’s blog post is a little bit different. I have a couple of examples of how you can use PowerShell snippets and simple commandlets to get or set role assignmnets in your Azure Subscriptions.

PowerShell examples for managing Azure Role assignments

List all role assignments in a subscription, get all role assignments for a specific resource group, get all role assignments for a specific user, add a role assignment to a user, remove a role assignment for a user, remove all role assignments for a specific user, list all built-in roles, list all custom roles, create a custom role, update a custom role, delete a custom role, list all users or groups assigned to a specific role, list all permissions granted by a specific role, list all resource groups that a user has access to, create a role assignment for a service principal, powershell script to manage azure role assignments.

And now there is a script that combines some of these examples into one usable function:

I hope this was useful. Let me know if you liked the format of this blog and if you want me to include more of these examples.

Vukasin Terzic

Recent Update

  • Writing your first Azure Terraform Configuration
  • Transition from ARM Templates to Terraform with AI
  • Getting started with Terraform for Azure
  • Terraform Configuration Essentials: File Types, State Management, and Provider Selection
  • Dynamically Managing Azure NSG Rules with PowerShell

Trending Tags

Retrieve azure resource group cost with powershell api.

The Future Of Azure Governance: Trends and Predictions

Further Reading

In my previous blog posts, I wrote about how simple PowerShell scripts can help speed up daily tasks for Azure administrators, and how you can convert them to your own API. One of these tasks is...

Azure Cost Optimization: 30 Ways to Save Money and Increase Efficiency

As organizations continue to migrate their applications and workloads to the cloud, managing and controlling cloud costs has become an increasingly critical issue. While Azure provides a robust s...

Custom PowerShell API for Azure Naming Policy

To continue our PowerShell API series, we have another example of a highly useful API that you can integrate into your environment. Choosing names for Azure resources can be a challenging task. ...

4sysops

  • IT Administration Forum
  • PowerShell Forum
  • Community Forum
  • PowerShell Group
  • Earning as 4sysops member
  • Member Ranks
  • Member Leaderboard – This Month
  • Member Leaderboard – This Year
  • Member Leaderboard – All-time
  • Author Leaderboard – 30 Days
  • Author Leaderboard – 365 Days
  • Cloud Computing
  • Write for 4sysops

Apply governance policy to multiple Azure subscriptions with management groups

4sysops - The online community for SysAdmins and DevOps

Avatar

Understanding management groups

Security-related prerequisite, creating management groups, adding subscriptions to a management group, apply governance to a management group.

  • Recent Posts

Timothy Warner

  • Install Ansible on Windows - Thu, Jul 20 2023
  • Use Azure Bastion as a jump host for RDP and SSH - Tue, Apr 18 2023
  • Azure Virtual Desktop: Getting started - Fri, Apr 14 2023

The industry analyst Gartner defines IT governance (ITG) as the processes that ensure the effective and efficient use of IT in enabling an organization to achieve its goals.

With respect to Microsoft Azure, you may have issues getting your team on the same page with ensuring:

  • Resources are created only in authorized regions
  • Virtual machines (VMs) use only approved instance sizes
  • Resources are always linked to proper taxonomic tags

The good news is that Azure Policy allows you to create and enforce this type of operational compliance. The bad news was that before management groups, Azure administrators needed to redefine and reapply Azure Policy to each subscription individually. Not cool!

I will cover Azure Policy in a separate 4sysops blog post; today I want to teach you how to create and control Azure management groups. Let's get right to work!

Note that management groups apply not only to the Pay-As-You-Go (PAYG) offer, but also to enterprise agreement (EA) customers. This is good news because if you are an EA customer, you almost certainly juggle multiple Azure subscriptions in your business.

As you see in the following Visio diagram I made for you, you can nest management groups (the "keep it simple" rule applies here as it does to any inheritance-based administration scheme) to suit your organizational requirements.

A representative Azure management group hierarchy

A representative Azure management group hierarchy

The Tenant Root Group is a predefined management group; you can modify but not delete it. By default, any RBAC or Azure Policy you define at this level cascades by inheritance to administrator-defined management groups.

As you can do with, say, NTFS permissions, you can override inheritance by setting explicit Azure or RBAC policy at the child management group.

Presumably for security reasons, you must elevate your user account access to modify the root management group. Log into the Azure portal with your Azure Active Directory (AD) global administrator account. Then navigate to the Properties blade and set the Global admin can manage Azure Subscriptions and Management Groups field to Yes . Be careful with this ultra-powerful setting! You may want to enable this option only while you work with the root management group.

Elevating your Azure AD permissions

Elevating your Azure AD permissions

You can then use the Access control (IAM) blade to assign RBAC roles to distribute management group administrative authority to child management groups. The two built-in RBAC roles are:

  • Management Group Contributor
  • Management Group Reader

In the Azure portal, visit the Management groups blade and click Add management group to get started. Next, fill in the Add management group section, specifying the following metadata:

  • Management group ID : This is the Azure AD-wide unique identifier for your management group—you provide the name
  • Management group display name : Self-explanatory 😉

Creating a new management group

Creating a new management group

You should now see your new management group show up in the list. Let me call out a few salient points:

  • The My Role column shows your account as an RBAC Owner of the resource, which should make sense because you created the management group
  • The Tenant Root Group Settings blade is hidden behind the small (details) hyperlink

In fact, you need to click that small (details) link to manage your new management group's settings as well. That seems like an odd user interface design choice, but nobody at Microsoft asked me for my opinion on that.

Management group Properties blade

Management group Properties blade

As you can observe in my previous screenshot, click Add subscription to populate your new management group with an Azure subscription.

Likewise, you can add a new or preexisting management group as a child of the current one by clicking Add management group from the toolbar. I need to stress you should be careful as you make these assignments because any subscriptions or child management groups you add to the current one will potentially change Azure Policy and RBAC role assignments.

In the next screenshot, you see that I added a child management group and three subscriptions to my management group.

A populated Azure management group

A populated Azure management group

You can apply both RBAC permissions as well as Azure Policy definitions to your management group from its Settings blade. Please understand that RBAC permissions authorize Azure users to perform operations on Azure resources. For instance, membership in the Virtual Machine Contributors role gives users the ability to deploy and manage VMs.

RBAC permissions at the management group level

RBAC permissions at the management group level

By contrast, Azure Policy manages the options those authorized users can reach on those resources. For example, the built-in policy Audit VMs that do not use managed disks flags any such VMs as non-compliant and notifies your designated administrative staff of the issue.

Other built-in policies, like Allowed locations , actually block deployment for resources assigned to non-compliant Azure regions.

Defining an Azure Policy using a built in definition

Subscribe to 4sysops newsletter!

Many of my Azure consulting clients were overjoyed when Microsoft released management groups. For businesses that have more than one subscription, management groups can greatly simplify how you govern your cloud infrastructure.

IT Administration News

  • Apple Intelligence Available in These Additional 7 Countries Next Year – MacRumors
  • OpenAI Says It’s Fixed Issue Where ChatGPT Appeared to Be Messaging Users Unprompted
  • Microsoft unveils Office LTSC 2024 for users that remain stubbornly offline
  • Meta to Train AI Models Using Public U.K. Facebook and Instagram Posts
  • How Google and the C2PA are increasing transparency for gen AI content

Read All IT Administration News

Join our IT community and read articles without ads!

Do you want to write for 4sysops? We are looking for new authors.

Checking the SSH port on Ubuntu 24.04 Linux

How to change the SSH port on Ubuntu 24.04

Avatar

Manage Microsoft 365 from Active Directory Users and Computers (ADUC) with Easy365Manager

Avatar

Block AI scrapers and other web parasites with Cloudflare

Key package in the ADSI-Editor.

Recover data from corrupted BitLocker drives with repair-bde and key packages

Avatar

How not to block AI crawlers: robots.txt, authentication, CAPTCHA

Overview of fine grained password policies in the Active Directory Administrative Center

Determine effective password policy for AD users with PowerShell

Lightsail offers instances with various operating systems

Amazon Lightsail vs. AWS EC2: Pricing and flexibility

Health roll-up showing a red status for the entire dashboard

SquaredUp Cloud: Comprehensive monitoring and dashboard solution for a wide range of on-prem and cloud services

AI Hub displays visits to AI assistants flagged by the Insider Risk Policy

Microsoft Purview AI Hub – Monitor and block AI applications

Avatar

High Volume Email in Microsoft 365: Overcoming sending limits

Group Policy setting for notifying users about an expiring password

Send email notifications about expiring Active Directory passwords with a PowerShell script

Microsoft 365 Backup supports OneDrive, Exchange, and SharePoint (source Microsoft)

What is Microsoft 365 Backup?

Vulnerability and patch management in Endpoint Centra featured image

Unifying endpoint management and security: An overview of ManageEngine Endpoint Central

Azure AD PowerShell seamlessly integrates with Entra PowerShell within a single PowerShell session

Microsoft Entra PowerShell module, successor to the Azure AD PowerShell module

Daily retrieval of critical vulnerability alerts

Receive critical Microsoft security alerts by email

Upgrading the openssh-server

Addressing OpenSSH vulnerabilities CVE-2024-6387 and CVE-2024-6409

Avatar

Install AWS CloudShell in a VPC

Avatar

Authenticator backup: Microsoft, Google, Amazon, Authy

Finding the eDiscovery search ID using Microsoft Graph Explorer

Search and delete Copilot data in Microsoft 365

Explore delegated Managed Service Account (dMSA) attributes using AD Explorer

Delegated Managed Service Accounts in Windows Server 2025

Avatar

Leave a reply Click here to cancel the reply

Please enclose code in pre tags: <pre></pre>

Your email address will not be published. Required fields are marked *

Notify me of followup comments via e-mail. You can also subscribe without commenting.

Receive new post notifications

Twitter

Subscribe to Newsletter

Follow 4sysops.

Please ask IT administration questions in the forums . Any other messages are welcome.

Log in with your credentials

or      Create an account

Forgot your details?

Create account.

Navigation Menu

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 You must be signed in to change notification settings

Assign Multiple RoleAssignments at Different Scopes #5926

@ArtiomLK

{{editor}}'s edit

Artiomlk feb 10, 2022.

I want to create user ID (Managed Identities) and assign them multiple rbac at different scopes. For instance:

ID A would have Owner and Contributor roles at rg-app
ID B would have Reader role at rg-dns
ID B would have Private DNS Zone Contributor at rg-dns/pdnsz-resource

In order to achieve this,

The main question:
is it possible to do multiple role assignments on different resources which were not created as part of such bicep file

For example:

= 'subscription' // ... resource vnet 'Microsoft.Network/virtualNetworks@2021-02-01' existing = { name: 'vnet' scope: resourceGroup(subscription().id, 'rg_hub_n') } module idDeployment 'components/id/id.bicep' = { name: 'id-aks-deploy' scope: appRg params: { id_n: id_n tags: tags } } // only allows rg scope module idRoleAssignmentDeployment 'components/id/roleAssignments.bicep' = [for id_role in id_roles_arr : { name: 'id-role-assignment-deploy-${id_role}' scope: resourceGroup(id_scope_obj.sub, id_scope_obj.rg) params: { name: guid(subscription().id, env, id_role) principalId: idDeployment.outputs.principalId roleDefinitionId: '/subscriptions/${id_scope_obj.sub}/providers/Microsoft.Authorization/roleDefinitions/${id_role}' } dependsOn: [ idDeployment ] }] // The root resource scope must match that of the Bicep file. To deploy a resource to a different root scope, use a module. resource roleAssignment 'Microsoft.Authorization/roleAssignments@2020-08-01-preview' = { name: 'some random unique name' scope: vnet properties: { principalId: 'principalId' roleDefinitionId: 'roleDefinitionId' principalType: 'ServicePrincipal' } }

Beta Was this translation helpful? Give feedback.

This is possible... I would recommend to read over this thread of some of the complexities.

Also this blog which I believe was based on some of the discussions in that thread via @JFolberth

https://blog.johnfolberth.com/nested-loops-in-azure-bicep-with-an-rbac-example/

Then please share back any questions or follows up that you have here.

Essentially to do a role assignment, you deploy into the Scope of the resource E.g. the resource group, Then you use an existing reference, then you can do the role assignment at that scope of that resource.

So if you have 2 resource groups, you need to have a module to deploy into the scope of those resources groups Etc.

Here is also an alternate …

Replies: 1 comment · 6 replies

Brwilkinson feb 10, 2022 maintainer.

This is possible... I would recommend to read over this thread of some of the complexities.

Also this blog which I believe was based on some of the discussions in that thread via

Then please share back any questions or follows up that you have here.

Essentially to do a role assignment, you deploy into the Scope of the resource E.g. the resource group,
Then you use an existing reference, then you can do the role assignment at that scope of that resource.

So if you have 2 resource groups, you need to have a module to deploy into the scope of those resources groups Etc.

Here is also an alternate less complex scenario on this than the above thread. Since it's just a single resource.

@brwilkinson

Yes that is my preferred approach as well.

dp_Deployment_RBAC 'sub-RBAC.bicep' = if (bool(Stage.RBAC)) { name: 'dp${Deployment}-RBAC' params: { // move these to Splatting later DeploymentID: DeploymentID DeploymentInfo: DeploymentInfo Environment: Environment Extensions: Extensions Global: Global Prefix: Prefix Stage: Stage } dependsOn: [ dp_Deployment_RG ] }

Calls nested deployment/Module sub-RBAC.bicep

: [ { "Name": "BW", "RBAC": [ { "Name": "Contributor" }, { "Name": "Key Vault Administrator" }, { "Name": "Virtual Machine Administrator Login" }, { "Name": "Azure Kubernetes Service RBAC Cluster Admin" }, { "Name": "Load Test Owner" } ] } RBAC 'sub-RBAC-ALL.bicep' = [for (role, index) in rolesInfo: if (bool(Stage.RBAC)) { name: 'dp-rbac-role-${Prefix}-${role.name}' params: { Deployment: deployment Prefix: Prefix rgName: rg Enviro: enviro Global: Global roleInfo: role providerPath: '' namePrefix: '' providerAPI: '' } }]

Calls nested deployment/Module sub-RBAC-ALL.bicep

RBACRARG 'sub-RBAC-ALL-RA-RG.bicep' = [for (rbac, index) in roleAssignment: if (Enviro != 'G0' && Enviro != 'M0') { name: replace('dp-rbac-all-ra-${roleInfo.name}-${index}','@','_') scope: resourceGroup(rbac.DestSubscriptionID,'${rbac.DestPrefix}-${Global.OrgName}-${rbac.DestApp}-RG-${rbac.DestRG}') params:{ description: roleInfo.name name: rbac.GUID roledescription: rbac.RoleName roleDefinitionId: '${rbac.DestSubscription}/providers/Microsoft.Authorization/roleDefinitions/${rbac.RoleID}' principalType: rbac.principalType principalId: providerPath == 'guid' ? roleInfo.name : length(providerPath) == 0 ? rolesLookup[roleInfo.name] : /* */ reference('${rbac.DestSubscription}/resourceGroups/${rbac.SourceRG}/providers/${providerPath}/${Deployment}${namePrefix}${roleInfo.Name}',providerAPI).principalId } }]

This references another nested deployment/Module e.g. sub-RBAC-ALL-RA-RG.bicep

Which actually does the role assignment within the RG....

This example is on the RG itself, however see below for a Resource Scoped Role assignement that you can call from here instead.

roleDefinitionId string param principalId string param principalType string param name string #disable-next-line no-unused-params param description string // leave these for loggin in the portal #disable-next-line no-unused-params param roledescription string // leave these for loggin in the portal resource RA 'Microsoft.Authorization/roleAssignments@2020-04-01-preview' = { name: name properties: { roleDefinitionId: roleDefinitionId principalType: principalType principalId: principalId } }

resourceId string param Global object param roleInfo object param principalType string = '' var rolesLookup = json(Global.RolesLookup) var rolesGroupsLookup = json(Global.RolesGroupsLookup) var roleAssignment = [for rbac in roleInfo.RBAC: { RoleName: rbac.Name RoleID: rolesGroupsLookup[rbac.Name].Id principalType: principalType GUID: guid(roleInfo.Name, rbac.Name, resourceId) FriendlyName: 'user: ${roleInfo.Name} --> roleInfoName: ${rbac.Name} --> resourceId: ${resourceId}' }] module RBACRAResource 'x.RBAC-ALL-RA-Resource.bicep' = [for (rbac, index) in roleAssignment: { name: replace('dp-rbac-all-ra-${roleInfo.name}-${index}', '@', '_') params: { resourceId: resourceId description: roleInfo.name roledescription: rbac.RoleName name: rbac.GUID roleDefinitionId: rbac.RoleID principalId: rolesLookup[roleInfo.name] principalType: rbac.principalType } }] output RoleAssignments array = roleAssignment

Just to add I would start with creating a single form json object that describes your role assignments, such as below then just process them through the layers.. Subscription --> Resource group --> Resource Role Assignment.

: [ { "vnetName": "vneta", "rgName": "rg-a", "principalId": "9ed16e1c-f8ce-46fe-b097-81bd5947ef06", "roleDefinitionId": "4d97b98b-1d4f-4787-a291-c67834d212e7", "resourceType": "Microsoft.Network/virtualNetworks" }, { "vnetName": "vnetb", "rgName": "rg-b", "principalId": "9ed16e1c-f8ce-46fe-b097-81bd5947ef06", "roleDefinitionId": "4d97b98b-1d4f-4787-a291-c67834d212e7", "resourceType": "Microsoft.Network/virtualNetworks" }, { "vnetName": "vnetc", "rgName": "rg-c", "principalId": "9ed16e1c-f8ce-46fe-b097-81bd5947ef06", "roleDefinitionId": "4d97b98b-1d4f-4787-a291-c67834d212e7", "resourceType": "Microsoft.Network/virtualNetworks" } ] }

@ArtiomLK

ArtiomLK Feb 10, 2022 Author

Those are pretty cool scenarios over sub, rg and res scopes. Thanks for sharing.

The last link:

which sends me to the ARM json template

From where I can see that, it set the scope to a string resource ID within the roleAssignment.

: "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#", "contentVersion": "1.0.0.0", "parameters": { "scope": { "type": "string" }, "name": { "type": "string" }, "roleDefinitionId": { "type": "string" }, "principalId": { "type": "string" }, "principalType": { "type": "string" } }, "resources": [ { "type": "Microsoft.Authorization/roleAssignments", "apiVersion": "2020-08-01-preview", "scope": "[parameters('scope')]", "name": "[parameters('name')]", "properties": { "roleDefinitionId": "[resourceId('Microsoft.Authorization/roleDefinitions', parameters('roleDefinitionId'))]", "principalId": "[parameters('principalId')]", "principalType": "[parameters('principalType')]" } } ], "outputs": { "roleAssignmentId": { "type": "string", "value": "[extensionResourceId(parameters('scope'), 'Microsoft.Authorization/roleAssignments', parameters('name'))]" } } }

Is it possible to achieve it from bicep, such as passing the res id within the scope as you did above. For instance:

= 'subscription' // ... module idRoleAssignmentDeployment 'components/id/roleAssignments.bicep' = [for id_role in id_roles_arr : { name: 'id-role-assignment-deploy-${id_role}' scope: resourceGroup(id_scope_obj.sub, id_scope_obj.rg) params: { name: guid(subscription().id, env, id_role) principalId: idDeployment.outputs.principalId roleDefinitionId: '/subscriptions/${id_scope_obj.sub}/providers/Microsoft.Authorization/roleDefinitions/${id_role}' } }]

components/id/roleAssignments.bicep

name string param principalId string param roleDefinitionId string param res_id string resource vnet 'Microsoft.Network/virtualNetworks@2021-02-01' existing = { name: 'vnet_n' // scope: resourceGroup(subscription().id, 'rg_hub_n') } resource roleAssignment 'Microsoft.Authorization/roleAssignments@2020-08-01-preview' = { name: name scope: vnet // if I uncomment the vnet res scope I get, The root resource scope must match that of the Bicep file. To deploy a resource to a different root scope, use a module.bicep(BCP139) // scope: res_id ? properties: { principalId: principalId roleDefinitionId: roleDefinitionId principalType: 'ServicePrincipal' } }

Yes, that (Bicep template file) will work perfectly for your scenario, if you only want to do role assignments for a single resource type e.g. VNET.

The reason behind the JSON template is because it provides the ability to have a generic template that can take a 'resourceId' for , including things like a file share or blob container or storage account or KeyVault Etc.

brwilkinson Feb 16, 2022 Maintainer

How did you go with this one ?

Not a trivial process.

I have been making a few udpates to those links that I shared.

I am happy now that I can create a Managed Identity OR reference a User or Group, then later on assign it as a role assignment on any resource. So far I implemented assigning keyvault access or blob or file share access. However using generic modules means you can just use the following code for any resource type.

rolesInfo = contains(container, 'rolesInfo') ? container.rolesInfo : [] module RBAC 'x.RBAC-ALL.bicep' = [for (role, index) in rolesInfo: { name: 'dp-rbac-role-${SAContainers.name}-${role.name}' params: { resourceId: SAContainers.id Global: Global roleInfo: role Type: contains(role,'Type') ? role.Type : 'lookup' deployment: deployment } }]

Where the input is:

: [ { "name": "adldata", "rolesInfo": [ { "Name": "BW", "RBAC": [ { "Name": "Storage Blob Data Contributor" } ] }, { "Name": "SynapseDataContributor", "Type": "UAI", "RBAC": [ { "Name": "Storage Blob Data Contributor" } ] } ] } ]

@ArtiomLK

  • Numbered list
  • Unordered list
  • Attach files

Select a reply

Setting up access controls across multiple Azure subscriptions

To set up access controls across multiple Azure subscriptions, you'll want to create Role Assignments in each subscription. Role Assignments allow you to define who has what access to resources within a subscription. You can assign roles to user identities (including users, groups, and service principals) at various scopes, such as a specific subscription, a resource group, or a single resource.

We'll use the azure-native.authorization.RoleAssignment resource from Pulumi's Azure Native provider to apply role assignments across subscriptions. It's important that the Azure subscriptions are under the same Azure Active Directory tenant, as role assignments cannot span different tenants. You should have the necessary privileges to assign roles across these subscriptions.

Here's a Pulumi program written in TypeScript which demonstrates how to create a role assignment. Replace the principalId , roleDefinitionId , and scope accordingly for each subscription. The principalId is the unique ID of the user or service principal to which the role should be assigned, and the roleDefinitionId corresponds to the role you want to assign (e.g., Contributor, Owner, Reader).

Before running this program, you need to:

  • Log in to your Azure account using the Azure CLI with az login .
  • Set the Azure Active Directory principalId and the roleDefinitionId you wish to assign in the Pulumi configuration with pulumi config set principalId <value> and pulumi config set roleDefinitionId <value> .
  • Provide the list of subscription IDs into the Pulumi configuration with pulumi config set subscriptionIds '["sub1", "sub2", ...]' .

This program creates a role assignment within each Azure subscription defined in the subscriptionIds list. It will assign the specified role to the principal at the subscription scope. The roleAssignmentName ensures each assignment has a unique name, which is a requirement in Azure for each role assignment. The export statement at the end will output the names of the role assignments for your reference.

Remember that roles in Azure are hierarchical, and role assignments are inherited down the resource hierarchy. If you set the scope to a higher level, like the subscription, the role assignment applies to all resources within that subscription. Adjust the scope accordingly if you want to restrict roles to more specific resources, such as resource groups or individual resources within the subscriptions.

  • TS TypeScript
  • JS JavaScript
  • TF Terraform

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 PowerShell

  • 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. This article describes how to assign roles using Azure PowerShell.

We recommend that you use the Azure Az PowerShell module to interact with Azure. To get started, see Install Azure PowerShell . To learn how to migrate to the Az PowerShell module, see Migrate Azure PowerShell from AzureRM to Az .

Prerequisites

To assign roles, you must have:

  • Microsoft.Authorization/roleAssignments/write permissions, such as Role Based Access Control Administrator
  • PowerShell in Azure Cloud Shell or Azure PowerShell
  • The account you use to run the PowerShell command must have the Microsoft Graph Directory.Read.All permission.

Steps to assign an Azure role

To assign a role consists of three elements: security principal, role definition, and scope.

Step 1: Determine who needs access

You can assign a role to a user, group, service principal, or managed identity. To assign a role, you might need to specify the unique ID of the object. The ID has the format: 11111111-1111-1111-1111-111111111111 . You can get the ID using the Azure portal or Azure PowerShell.

For a Microsoft Entra user, get the user principal name, such as [email protected] or the user object ID. To get the object ID, you can use Get-AzADUser .

For a Microsoft Entra group, you need the group object ID. To get the object ID, you can use Get-AzADGroup .

Service principal

For a Microsoft Entra service principal (identity used by an application), you need the service principal object ID. To get the object ID, you can use Get-AzADServicePrincipal . For a service principal, use the object ID and not the application ID.

Managed identity

For a system-assigned or a user-assigned managed identity, you need the object ID. To get the object ID, you can use Get-AzADServicePrincipal .

Step 2: Select the appropriate role

Permissions are grouped together into roles. You can select from a list of several Azure built-in roles or you can use your own custom roles. It's a best practice to grant access with the least privilege that is needed, so avoid assigning a broader role.

To list roles and get the unique role ID, you can use Get-AzRoleDefinition .

Here's how to list the details of a particular role.

For more information, see List Azure role definitions .

Step 3: Identify the needed scope

Azure provides four levels of scope: resource, resource group , subscription, and management group . It's a best practice to grant access with the least privilege that is needed, so avoid assigning a role at a broader scope. For more information about scope, see Understand scope .

Resource scope

For resource scope, you need the resource ID for the resource. You can find the resource ID by looking at the properties of the resource in the Azure portal. A resource ID has the following format.

Resource group scope

For resource group scope, you need the name of the resource group. You can find the name on the Resource groups page in the Azure portal or you can use Get-AzResourceGroup .

Subscription scope

For subscription scope, you need the subscription ID. You can find the ID on the Subscriptions page in the Azure portal or you can use Get-AzSubscription .

Management group scope

For management group scope, you need the management group name. You can find the name on the Management groups page in the Azure portal or you can use Get-AzManagementGroup .

Step 4: Assign role

To assign a role, use the New-AzRoleAssignment command. Depending on the scope, the command typically has one of the following formats.

Assign role examples

Assign a role for all blob containers in a storage account resource scope.

Assigns the Storage Blob Data Contributor role to a service principal with object ID 55555555-5555-5555-5555-555555555555 and Application ID 66666666-6666-6666-6666-666666666666 at a resource scope for a storage account named storage12345 .

Assign a role for a specific blob container resource scope

Assigns the Storage Blob Data Contributor role to a service principal with object ID 55555555-5555-5555-5555-555555555555 and Application ID 66666666-6666-6666-6666-666666666666 at a resource scope for a blob container named blob-container-01 .

Assign a role for a group in a specific virtual network resource scope

Assigns the Virtual Machine Contributor role to the Pharma Sales Admins group with ID aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa at a resource scope for a virtual network named pharma-sales-project-network .

Assign a role for a user at a resource group scope

Assigns the Virtual Machine Contributor role to [email protected] user at the pharma-sales resource group scope.

Alternately, you can specify the fully qualified resource group with the -Scope parameter:

Assign a role for a user using the unique role ID at a resource group scope

There are a couple of times when a role name might change, for example:

  • You are using your own custom role and you decide to change the name.
  • You are using a preview role that has (Preview) in the name. When the role is released, the role is renamed.

Even if a role is renamed, the role ID does not change. If you are using scripts or automation to create your role assignments, it's a best practice to use the unique role ID instead of the role name. Therefore, if a role is renamed, your scripts are more likely to work.

The following example assigns the Virtual Machine Contributor role to the [email protected] user at the pharma-sales resource group scope.

Assign a role for an application at a resource group scope

Assigns the Virtual Machine Contributor role to an application with service principal object ID 77777777-7777-7777-7777-777777777777 at the pharma-sales resource group scope.

Assign a role for a user at a subscription scope

Assigns the Reader role to the [email protected] user at a subscription scope.

Assign a role for a user at a management group scope

Assigns the Billing Reader role to the [email protected] user at a management group scope.

  • List Azure role assignments using Azure PowerShell
  • Tutorial: Grant a group access to Azure resources using Azure PowerShell
  • Manage resources with Azure PowerShell

Was this page helpful?

Additional resources

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Is it possible to assign multiple roles to a user or group in Azure AD?

When I add an appRoles section to my application manifest in Azure AD, I can assign users and groups to roles in the management portal.

However, the UI only allows me to assign a single role to a user or group.

I can't find how to assign multiple roles to a user or group. I can add the user to multiple groups and assign roles to members of that group, which will result in multiple role claims in the token for that user, but this seems awkward.

Am I missing something? Is there a way to assign multiple roles to a user or group?

  • authorization
  • azure-active-directory

MvdD's user avatar

3 Answers 3

You can assign multiple roles to the same user in the same app, but it is very limited. Basically add the same user again and select a different role:

enter image description here

The mechanism is very cumbersome and will not scale. If you have AAD Premium Lvl 2, you can associate application roles with groups and a when you assign a user to that group, they will gain the roles automatically. The automatic assignment only works for Premium Lvl 2 though.

BgRva's user avatar

  • 1 Yeah, this question was asked and answered when the new portal did not exist yet. Seems silly that they only made this workable for Premium 2 users. –  MvdD Commented May 16, 2018 at 16:38
  • I see someone plays world of warcraft ;) –  Jason King Commented Jan 12, 2022 at 4:48
  • 1 + 50 DKP to you –  BgRva Commented Jan 13, 2022 at 13:29
  • 2 This doesn't seem to work in the current version of Azure AD –  Atif Commented Sep 29, 2022 at 11:26
  • 1 @Atif I seem to be able to add the same user multiple times with different roles. –  Sam Morris Commented Jan 16, 2023 at 15:58

This turns out to be a limitation of the Azure management portal . In this blog comment , the AAD PM explains it is possible to assign multiple roles to a user or group through the GraphAPI.

For more info, see section ' Assigning application roles ' in this MSDN blog article .

  • Unfortunately those last two blog links are dead. –  dmikester1 Commented Nov 3, 2023 at 20:09

Had the same problem and with the current version of the azure portal the workaround was

  • Create two groups (group_for_perm1, group_for_perm2)
  • Add the same user to both groups ( [email protected] )
  • Go into Azure AD->Enterprise applications
  • Change the "Application type" filter to "All applications"
  • Search for your app
  • Select "Users and Groups"
  • Hit "+ Add user/group" at the top, and assign group_for_perm1 permission1
  • Hit "+ Add user/group" at the top, Assign group_for_perm2 permission2

Note if the "+ Add user/group" button is greyed out, you either didn't add App Roles to the App registration, or aren't in the owner group for the "Enterprise application". It appears you can be the owner of the App Registration and not be the owner of the Enterprise Application.

The token should now have a roles section with your two permissions. Take the JWT to jwt.io and you should see something like

Atif's user avatar

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged azure authorization roles azure-active-directory or ask your own question .

  • The Overflow Blog
  • Looking under the hood at the tech stack that powers multimodal AI
  • Featured on Meta
  • User activation: Learnings and opportunities
  • Preventing unauthorized automated access to the network
  • What does a new user need in a homepage experience on Stack Overflow?
  • Announcing the new Staging Ground Reviewer Stats Widget

Hot Network Questions

  • Does "Speak with animals" allow you to improve the attitude of an animal like "wild empathy"?
  • string quartet + chamber orchestra + symphonic orchestra. Why?
  • Is "Canada's nation's capital" a mistake?
  • Is it ok if I was wearing lip balm and my bow touched my lips by accident and then that part of the bow touched the wood on my viola?
  • Why believe in the existence of large cardinals rather than just their consistency?
  • How uncommon/problematic is a passport whose validity period (period between issue and expiry) is a non-whole number of years?
  • What's "jam" mean in "The room reeled and he jammed his head down" (as well as the sentence itself)?
  • Why are Jesus and Satan both referred to as the morning star?
  • Why did mire/bog skis fall out of use?
  • Emergency belt repair
  • How to interpret odds ratio for variables that range from 0 to 1
  • Why should the simulator be PPT in simulation-based security?
  • Terminated employee will not help the company locate its truck
  • Trinitarian Christianity says Jesus was fully God and Fully man. Did Jesus (the man) know this to be the case?
  • Consequences of registering a PhD at german university?
  • Combustion gas of gas generator right through nozzle?
  • If morality is real and has causal power, could science detect the moment the "moral ontology" causes a measurable effect on the physical world?
  • Model looks dented but geometry is correct
  • What does St Paul mean by ' height or depth' in Romans 8:39?
  • Why does constexpr prevent auto type deduction in this statement?
  • How is AC and DC defined?
  • What is a “bearded” oyster?
  • What's the origin of "she's no better than she should be"?
  • Does General Relativity predict Mercury's orbital precession without other planets?

azure role assignment multiple subscriptions

IMAGES

  1. Explore Azure costs for multiple subscriptions with cost analysis

    azure role assignment multiple subscriptions

  2. Organize and manage multiple Azure subscriptions

    azure role assignment multiple subscriptions

  3. Choosing the best Azure subscription service model

    azure role assignment multiple subscriptions

  4. Azure roles, Microsoft Entra roles, and classic subscription

    azure role assignment multiple subscriptions

  5. Analyze Azure costs for multiple subscriptions with Cost Analysis

    azure role assignment multiple subscriptions

  6. Add User Access Administrator Role to Multiple Azure Subscriptions

    azure role assignment multiple subscriptions

VIDEO

  1. Lesson108- Flow Azure key vault

  2. Azure Interview Questions and Answers || Part-3 || PDF download #shorts #shortsfeed #shortvideo

  3. Administering customer subscriptions: The publisher experience

  4. Terraforming Entra ID Users & Azure Role Assignments with AzureRM & AzureAD

  5. How to create Azure Policy assignment Terraform Scenario

  6. Creating Custom Roles for managing Azure resources

COMMENTS

  1. Assign a user as an administrator of an Azure subscription with

    Learn how to make a user an administrator of an Azure subscription with conditions using the Azure portal and Azure role-based access control (Azure RBAC).

  2. Understand Azure role assignments

    Role assignments enable you to grant a principal (such as a user, a group, a managed identity, or a service principal) access to a specific Azure resource. This article describes the details of role assignments.

  3. Adding role assignments to multiple Azure subscriptions for a managed

    I have an Azure function app that is hosted in subscription &quot;sub-test1&quot; and I want to add role assignment to give the managed system identity(for app) access to the subscription &quot;sub...

  4. Export role assignments for all Azure subscriptions

    When I'm working with customers that have many Subscriptions, I'll like to get an overview of all the subscriptions at once. Therefore I use PowerShell the export role assignments for all Subscriptions at once.

  5. Azure roles, Microsoft Entra roles, and classic subscription

    In the Azure portal, role assignments using Azure RBAC appear on the Access control (IAM) page. This page can be found throughout the portal, such as management groups, subscriptions, resource groups, and various resources.

  6. Delegate Azure role assignment management using conditions

    We're excited to share the public preview of delegating Azure role assignment management using conditions. This preview gives you the ability to enable others to assign Azure roles but add restrictions on the roles they can assign and who they can assign roles to.

  7. Azure RBAC: role assignments and ARM templates

    ARM templates can help define Azure Role-Based Access Control. By creating role assignments, users can grant Managed Identities access to resources.

  8. A Beginner's Guide To Role-Based Access Control on Azure

    The way you control access to resources using RBAC is to create role assignments. This is a key concept to understand - it's how permissions are enforced. A role assignment consists of three elements: security principal, role definition, and scope. User - An individual who has a profile in Azure Active Directory.

  9. Manage Azure Role Assignments Like a Pro with PowerShell

    Learn how to manage Azure Role assignments using PowerShell snippets and simple commandlets. Discover examples for listing all role assignments, adding and removing assignments for users or service principals, creating custom roles, and more. Plus, check out a script that combines some of these examples into a single function. Written by Vukasin Terzic.

  10. Apply governance policy to multiple Azure subscriptions with ...

    Management groups in Microsoft Azure solve the problem of needing to impose governance policy on more than one Azure subscription simultaneously.

  11. Assign Azure roles using Azure CLI

    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. This article describes how to assign roles using Azure CLI.

  12. Assign Multiple RoleAssignments at Different Scopes · Azure bicep

    I want to create user ID (Managed Identities) and assign them multiple rbac at different scopes. For instance: ID A would have Owner and Contributor roles at rg-app ID B would have Reader role at r...

  13. Organize your resources with management groups

    Another scenario where you would use management groups is to provide user access to multiple subscriptions. By moving multiple subscriptions under a management group, you can create one Azure role assignment on the management group. The role will inherit that access to all the subscriptions.

  14. Assigning Azure Roles Across Subscriptions

    TypeScript To set up access controls across multiple Azure subscriptions, you'll want to create Role Assignments in each subscription. Role Assignments allow you to define who has what access to resources within a subscription. You can assign roles to user identities (including users, groups, and service principals) at various scopes, such as a specific subscription, a resource group, or a ...

  15. Assign Azure roles using Azure PowerShell

    Learn how to grant access to Azure resources for users, groups, service principals, or managed identities using Azure PowerShell and Azure role-based access control (Azure RBAC).

  16. How can I see a list of all users and the roles assigned to them in Azure?

    Navigate to the resource/resource group/subscription in the portal -> Access control (IAM) -> Role assignments, you can filter with the parameters you want. Or you can use the Azure powershell Get-AzRoleAssignment or REST API, it depends on your requirement. Sample: 1.You have a list of ObjectIds of the users, you can use the script as below.

  17. azure

    │ Inappropriate value for attribute "role_definition_name": string required. I am already using for_each to pull in a list of principal_ids within the resource block, so I am wondering if there is a way to set this in a loop, so both the roles are applicable to the concerned principal_id.

  18. Is it possible to assign multiple roles to a user or group in Azure AD?

    28 You can assign multiple roles to the same user in the same app, but it is very limited. Basically add the same user again and select a different role: The mechanism is very cumbersome and will not scale.