• Top of Page

the role assignment already exists arm template

Defining RBAC Role Assignments in ARM Templates

It’s no secret I’m a big fan of Azure Resource Manager (ARM) templates. Getting started with ARM templates is hard, but well worth the effort, and make it significantly easier to have reproduceable, consistent deployments of your Azure resources.

One thing that I had been feeling left out, however, was being able to assign permissions to Azure resources during creation. Azure’s Role-based Access Control (RBAC) mechanism is a powerful way to control who can manage and access your resources, and having to do this through scripting was possible, but cumbersome at times.

A few days ago, I realized that you can actually create RBAC role assignments through ARM templates just like any other resource. This capability is not new by any means, I just had missed it before!

Creating an assignment

To create an assignment, you need the following information:

  • The ID of the role you want to assign. This is a long string that contains the subscription id and the role identifier (both GUIDs).
  • The object ID of the user/group/service principal you want to grant access to.
  • The scope at which you want to assign the role, which is going to be either a subscription, resource group, or resource id.

Here’s an example of creating such an assignment:

Here we grant the members of an Azure Active Directory group the Monitoring Contributor built-in role to the resource group the template is deployed to.

Also interesting here is that you don’t need to specify a location property in the resource.

Some gotchas

There are a couple of things to watch out for when doing this.

The first one is that to assign a role, you need the objectId of the AAD user/group/principal, rather than the name. This is cumbersome because there’s no way to resolve these within the ARM template itself, so you’ll always need to pass these as input parameters.

A more significant issue, however, is the name of the roleAssignment resource, which needs to be a unique GUID.

This is a problem if, for example, you’re assigning role permissions at the resource group or individual resource level, rather than globally at the subscription.

For example, in my case I was creating a template that would be used to deploy multiple copies of the same resources into different resource groups within the same subscription.

If the GUID that defines the role assignment name is hardcoded in the template, then each time I ran the template, the scope of the role assignment would get overwritten with the id of the last resource group it was deployed to. Clearly, this is undesirable.

What we need then, is a way to ensure that each deployment to a different resource group uses a different GUID for the role assignment, but at the same time, ensure that the same one is used when deploying to the same resource group.

Clearly, providing the assignment GUID as a parameter is an easy workaround, but very cumbersome.

A better workaround comes from the guid function! It takes one or more strings that are used to calculate a hash, very much like the uniquestring function; only this one generates a string in GUID format instead.

By using the guid function with the resource group id and some other consistent stuff as input, we can solve our problem in an elegant way:

  • Azure (41) ,
  • Security (2)

the role assignment already exists arm template

Tomas Restrepo

Software developer located in Colombia.

  • ← Previous
  • Next →

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

Get the Reddit app

Terraform discussion, resources, and other HashiCorp news.

If a role assignment already exists for an Azure resource, is there some way to add it to the state?

I have several Azure resource groups. IAM roles are assigned to them already, but my .tf file for them includes azurerm_role_assignment blocks for each role, and the principal IDs themselves are drawn from mapped variables as such:

When I run tf apply, it attempts to apply the role definitions, as it should. I get errors like this, once for each azurerm_role_assignment resource:

How do I get Terraform to add those to the state and stay correlated to the map key? These assignments aren't going to change, they're one-time deals that get added when the RG gets created. They keep popping up as errors, I'd like to not have them anymore.

By continuing, you agree to our User Agreement and acknowledge that you understand the Privacy Policy .

Enter the 6-digit code from your authenticator app

You’ve set up two-factor authentication for this account.

Enter a 6-digit backup code

Create your username and password.

Reddit is anonymous, so your username is what you’ll go by here. Choose wisely—because once you get a name, you can’t change it.

Reset your password

Enter your email address or username and we’ll send you a link to reset your password

Check your inbox

An email with a link to reset your password was sent to the email address associated with your account

Choose a Reddit account to continue

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

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

Role Assignment with different name wasn't detected #322

@Camios

Camios commented Jun 23, 2023


Role Assignment with different wasn't detected as a change.


Steps to reproduce the behavior:

function. passing the bicep template file and with passing the bicep template file and , the deployment will fail with "role assignment already exists" similar to this issue


If the deployment would result in an error, then whatif should fail to validate


If applicable, add screenshots to help explain your problem.

[e.g. PowerShell, CLI, API)
PowerShell


Add any other context about the problem here.

  • 👍 1 reaction

@ghost

No branches or pull requests

@Camios

the role assignment already exists arm template

This browser is no longer supported.

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

How to check if resource already exists in the ARM template

I would like to automate the process of ARM deployment in which resource should not get deployed if it already exists.

Trying to implement the below code but getting an error

https://learn.microsoft.com/en-us/azure/azure-resource-manager/templates/conditional-resource-deployment

Azure Policy An Azure service that is used to implement corporate governance and standards at scale for Azure resources. 860 questions Sign in to follow Follow

Hello @Eashendra Singh !

Would you mind Accepting the answer ?

It will help others with a similar question to get an Accepted Answer as feedback !

Thank you !

I understand that you want to validate whether a resource exists already before deploying an ARM template within the JSON.

ARM Templates cannot do that. You have to find a new method

For the provide code :

In the following ARM template, if the 'newOrExisting' parameter is set to 'new', then the storage account will be created. If it is set to 'existing', the storage account will not be created.

User's image

I hope this helps!

Kindly mark the answer as Accepted and Upvote in case it helped!

Konstantinos Passadis Thank you so much for your time and effort to bring into my notice that ARM is unable to perform the task which I am looking for. Fortunately, I have created a script to fulfil my requirement.

Thats great @Eashendra Singh !

If my answer helped kindly mark it as Accepted !

  • 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.

How to check the resource exists in the arm template

How do i identify the azure resource is exists or not in the ARM templates by the resource type and identifier

  • azure-resource-manager
  • azure-rm-template

abatishchev's user avatar

  • ARM templates are declarative in nature (so in theory this isn't needed) - what's your scenario, there may be another way to do what you're thinking... –  bmoore-msft Commented Jul 8, 2019 at 13:04
  • learn.microsoft.com/en-us/azure/azure-resource-manager/… –  RClemens Commented Mar 22, 2023 at 0:12

4 Answers 4

It is actually kind of possible. You can use resource group tags to mark a current deployed version and skip deployment if the tag is set. All this could be achieved via linked template. Note that we don't check for resource existence per se but we still allow writing ARM template that could contain one time initialization templates. The last will restore the resource if resource group was deleted and resources were lost (given that you created the resource group again). You can extend this to support per-resource tags which will be more useful in some cases.

The template that starts the deployment may look like this:

The linked template's condition looks into tags and returns true only if current version (stored in the tag) is less than the requested one. You don't actually have to maintain versioning: just don't set the DeploymentVersion parameter and it will deploy only for the first time. If you decide to redeploy anyway you have always an option to increase the version, which will cause deployment of the linked template (aka "main deployment").

The main deployment template is on you, but it should contain a tags resource in order to maintain the logic.

Remark for those who didn't understand the union() and rgWithDefaultVersion thing. ARM template deployment will fail if referenced object doesn't contain a property. In our case we have two such properties: 'tags' and 'Version' . 'Tags' will exist only if particular resource group has or ever had tags. 'Version' will exist only after we already wrote it once (in the main deployment). Therefore before we access them we perform union() operation on returned object with a proper default one, ensuring that we can safely access the mentioned properties.

Gustavo Mori's user avatar

  • 1 Very nice, and just what I needed today.. and I wasn't even the one who asked the question. Thanks! –  Razoll Commented May 1, 2020 at 4:07
  • That's a great workaround, thank you! The trick with union is marvelous –  Vladislav Commented Jul 15, 2020 at 12:52
  • Nice answer Benny! is there a way to PATCH tags? (i.e. merge , instead of replace ) When having multiple resources effected by the state kept as RG tags, it becomes a problem to main the tags without losing some due to some race conditions when running ARM template steps in parallel instead of sequence. –  johni Commented Jul 28, 2020 at 12:11
  • 1 Mate, are you relalized the way you did are useless complexity? Are you going to apply the conditions to each resource in ARM templates? Secondary, if the real resourse has configuration drift, it would be never rollbacked, if the tag of version is not changed on that resource. –  BMW Commented Apr 26, 2021 at 1:42
  • 1 i mean, this is pretty much what I mentioned in my answer, but (similarly to @BMW) I discourage this approach. templates are meant to not really care about state that is present now. they should just "make it so". you've got git to track previous states. –  4c74356b41 Commented Apr 26, 2021 at 15:49

there is no way of doing that in an arm template. you can use some external source (like powershell) to determine that and pass in parameter with appropriate value, alternatively you can use tags to figure that out (have a tag that represents an existence\absence of a resource).

4c74356b41's user avatar

Resource Manager provides the following functions for getting resource values: Resource functions for Azure Resource Manager templates

You could wrap your template with a piece of powershell\whatever, that would determine if the resource exists, and pass in the parameter value depending on that and use a conditional statement in the template that would decide what to do based on the input (but the input has to come from elsewhere)

SumanthMarigowda-MSFT's user avatar

I needed a solution to this recently to basically do an incremental update to a SQL server. Since you can't do this; the template will fail with a NameAlreadyExists error. So I needed to check the resource doesn't exist and only create if it doesn't.

Add a "condition" check for the azure resource id exists; don't create if it does.

You can do this for any resource type.

user1930735's user avatar

  • This does not work, because the resourceId function does not actually check if a resource exists, it simply returns what the ID would be for the given resource group, type and name. See the docs for more - learn.microsoft.com/en-us/azure/azure-resource-manager/… –  David Gard Commented Sep 5, 2019 at 10:04
  • 4 this answer is straight out wrong. who upvotes this? –  4c74356b41 Commented Oct 16, 2019 at 6:45
  • 2 It should be noted that the reason this approach is wrong is because when a resource ID cannot be found, this results in an error, not an empty string. If an empty string were returned, then it looks like it would work. –  The Gilbert Arenas Dagger Commented Apr 27, 2020 at 22:30

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 azure-resource-manager azure-rm-template or ask your own question .

  • The Overflow Blog
  • At scale, anything that could fail definitely will
  • Best practices for cost-efficient Kafka clusters
  • Featured on Meta
  • Announcing a change to the data-dump process
  • Bringing clarity to status tag usage on meta sites
  • What does a new user need in a homepage experience on Stack Overflow?
  • Feedback requested: How do you use tag hover descriptions for curating and do...
  • Staging Ground Reviewer Motivation

Hot Network Questions

  • Do all instances of a given string get replaced under a rewrite rule?
  • Why doesn’t dust interfere with the adhesion of geckos’ feet?
  • Nearly stalled on takeoff after just 3 hours training on a PPL. Is this normal?
  • Can I arxive a paper that I had already published in a journal(EPL, in my case), so that eveyone can access it?
  • How would humans actually colonize mars?
  • How do I apologize to a lecturer
  • What is an overview of utilitarian arguments in support of exclusive relationships?
  • Can Christian Saudi Nationals visit Mecca?
  • How do I safely download and run an older version of software for testing without interfering with the currently installed version?
  • How to load a function from a Vim9 script and call it?
  • Whats the safest way to store a password in database?
  • "The earth was formless and void" Did the earth exist before God created the world?
  • Why is notation in logic so different from algebra?
  • Is this schematic ready to be made into a circuit?
  • Asked to suggest referees 9 months after submission: what to do?
  • If a Palestinian converts to Judaism, can they get Israeli citizenship?
  • Light switch that is flush or recessed (next to fridge door)
  • Why is a USB memory stick getting hotter when connected to USB-3 (compared to USB-2)?
  • How would you slow the speed of a rogue solar system?
  • How best to cut (slightly) varying size notches in long piece of trim
  • What rules of legal ethics apply to information a lawyer learns during a consultation?
  • Can I Use A Server In International Waters To Provide Illegal Content Without Getting Arrested?
  • In roulette, is the frequency of getting long sequences of reds lower than that of shorter sequences?
  • Creating Layout of 2D Board game

the role assignment already exists arm template

COMMENTS

  1. Prevent error from redundant deploy: Error: "role assignment already

    Role Assignment template. Issue Details. I was wondering about a technical issue with this template. When you deploy a web app or storage account with an ARM and it already exists, there is no error; the ARM just skips or updates the resource. With role assignments, if you try running it multiple times, you get an error:

  2. Microsoft.Authorization/roleAssignments

    A template that creates role assignments of user assigned identity on resources that Azure Machine Learning workspace depends on: ... The user deploying the template must already have the Owner role assigned at the tenant scope. ... this ARM template will ease the job: Download, Extract and Import into an existing Storage Account Blob Container

  3. azure

    I think there should be something to make sure about the role assignment. For the same scope or resource, you can only assign the same role to a service principal once. In this case, it means you can only assign the role "Storage Blob Data Contributor" of the storage account to your app identity once.

  4. 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.

  5. Microsoft.Authorization/roleAssignments DevOps CI / ARM Template Issue

    The resources are not nested within the storage account; they're in the main resources section of the template. The issue is that the resource provider, despite my deployment being incremental, does not respect the fact that the assignments already exist. The pipeline output is: [error]RoleAssignmentExists: The role assignment already exists.

  6. Deployment fails when Role Assignment already exists #548

    I have the same experience as well, using the 101-template with advanced networking. The issue presents itself if the role is already assigned to the subnet. If the role is removed before deploying the template it does works. So the incremental mode for applying the role assignment doesn't seem to work properly.

  7. Defining RBAC Role Assignments in ARM Templates

    Creating an assignment. To create an assignment, you need the following information: The ID of the role you want to assign. This is a long string that contains the subscription id and the role identifier (both GUIDs). The object ID of the user/group/service principal you want to grant access to. The scope at which you want to assign the role ...

  8. Example with an ARM template

    A separate Service Principal (SP) credentials are used to try and deploy the ARM template. Initially the all Role Assignments for the SP are deleted, then as the utility starts getting ...

  9. Azure RBAC: role assignments and ARM templates

    John Reilly. OSS Engineer - TypeScript, Azure, React, Node.js, .NET. 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 ...

  10. Quickstart: Assign an Azure role using an ARM template

    Azure role-based access control (Azure RBAC) is the way that you manage access to Azure resources. In this quickstart, you create a resource group and grant a user access to create and manage virtual machines in the resource group. This quickstart uses an Azure Resource Manager template (ARM template) to grant the access.

  11. Role Assignment conflicts when assignment is scoped to BLOB ...

    Bicep version run bicep --version via the Bicep CLI, az bicep version via the AZ CLI or via VS code by navigating to the extensions tab and searching for Bicep. Bicep CLI version 0.19.5 (87ca110)Describe the bug A clear and concise description of what the bug is vs what you expected to happen. We have several BLOB Storage Accounts with several different containers.

  12. Azure Bicep authorization roleassignements to storage account fails

    Failed to add <<user-assigned managed identity name>> as <<RBAC role>> for <<Resource>>: The role assignment already exists. Check Role Assignment: Depending on the scope (Resource Group, Resource, etc.) that you're trying to assign the RBAC role at. Navigate to your Storage Account. In the navigation menu (left side), click Access control (IAM ...

  13. Deployment fails when Role Assignment already exists #4014

    The cluster deploys fine but the arm template throws the below error: Deployment fails when Role Assignment already exists ge\":\"{\\r \\\"... Skip to content Navigation Menu

  14. If a role assignment already exists for an Azure resource, is ...

    │ │ with azurerm_role_assignment.role-vdi-vdiuser["Team4"], │ on AzureVDI.tf line 41, in resource "azurerm_role_assignment" "role-vdi-vdiuser": │ 41: resource "azurerm_role_assignment" "role-vdi-vdiuser" {How do I get Terraform to add those to the state and stay correlated to the map key? These assignments aren't going to change, they ...

  15. Add Azure role assignment conditions using Azure Resource Manager templates

    In this article. An Azure role assignment condition is an additional check that you can optionally add to your role assignment to provide more fine-grained access control. For example, you can add a condition that requires an object to have a specific tag to read the object. This article describes how to add conditions for your role assignments using Azure Resource Manager templates.

  16. Role Assignment with different name wasn't detected #322

    In Azure Portal, manually create role assignment on an App Config Service for an APIM; In a bicep deployment script, define that same role assignment using a GUID that is generated from the guid function. Run New-AzDeployment passing the bicep template file and with -WhatIf:True; WhatIf doesn't list the role assignment as being different

  17. Dive into ARM template from a Function App

    This makes it impossible for the ARM template to pre-specify the Connection String of Storage (and it is also not secure). Instead, ARM uses functions like listKeys to dynamically obtain the related Connection String from the already created Storage resource and use it as a parameter for the Function App to communicate with Storage in the future.

  18. How to know the azure role assignment already exists

    1. well, you are using the right command, you just need to build some logic around it to be able to determine if the assignment already exists. If you know the GUID beforehand: Is the easiest way to check. Its output is : Microsoft.Azure.Commands.Resources.Models.Authorization.PSRoleAssignment How can i know it has 'Storage Blob Data ...

  19. How to check if resource already exists in the ARM template

    1 answer. I understand that you want to validate whether a resource exists already before deploying an ARM template within the JSON. ARM Templates cannot do that. You have to find a new method. In the following ARM template, if the 'newOrExisting' parameter is set to 'new', then the storage account will be created.

  20. How to check the resource exists in the arm template

    ARM template deployment will fail if referenced object doesn't contain a property. In our case we have two such properties: 'tags' and 'Version'. 'Tags' will exist only if particular resource group has or ever had tags. 'Version' will exist only after we already wrote it once (in the main deployment).