terraform azure the role assignment already exists

Member-only story

Managing Azure RBAC Roles and Assignments with Terraform

Jack Morris

Jack Morris

This a quick guide I couldn’t wait to share. Here is a way of managing a custom roles and role assignments in Azure using Terraform. The versions of Terraform, AzureRM, and the AzureAD provider I’m using are as follows:

In this example, I’m creating a custom role that allows some users to view a shared dashboard in our Azure subscription. The users should be able to view the dashboard that Terraform is already creating, which is referred to by the terraform resource azurerm_dashboard.insights-dashboard :

This role grants read access to:

  • The specific Shared Dashboard that is created elsewhere in Terraform by scoping this role just to the dashboard
  • The same read permissions as the built-in Monitoring Reader role, minus the ability to raise support tickets. Since Insights queries a ton of data — each of which is exposed in a different permissions entry, e.g. Microsoft.Insights/metricAlerts/read , Microsoft.Insights/alertRules/read , Microsoft.Insights/components/*/read — I found it easier to make the read permissions more permissive and mimic one of the built-in roles here. The scope for this role is still only assignable to the dashboard, so effectively we grant read access to whatever Insights data the dashboard surfaces.

When assigning users to a role, you need their principal ID (also called an object ID) within Azure AD to perform the assignment. Personally, I wouldn’t want to have to find out each user’s object ID through some manual process or by using the CLI before I run terraform. What we can do instead is create a variable that stores all of the email addresses (which is also their UPN, or user princiupal name) associated with the users in Azure:

Then, we pass that variable to the AzureAD provider and use the for_each argument to loop through the users:

And finally, when we want to assign all of those users to the custom role we created above, we do this using for_each again, this time providing the data resource ( azuread_user ) we created above:

And that’s it! You can now assign a batch of users to an RBAC role in Azure using Terraform.

Jack Morris

Written by Jack Morris

Solution Architect at Kainos

More from Jack Morris and ITNEXT

Six Ways to Take Your Terraform to the Next Level

Six Ways to Take Your Terraform to the Next Level

Tools and tricks for making your terraform more scalable and enjoyable to work with..

Daily bit(e) of C++ | Optimizing code to run 87x faster

Daily bit(e) of C++ | Optimizing code to run 87x faster

Daily bit(e) of c++ #474, optimizing c++ code to run 87x faster for the one billion row challenge (1brc)..

Benchmark results of Kubernetes network plugins (CNI) over 40Gbit/s network [2024]

Alexis Ducastel

Benchmark results of Kubernetes network plugins (CNI) over 40Gbit/s network [2024]

This article is a new run of my previous benchmark (2020, 2019 and 2018), now running kubernetes 1.26 and ubuntu 22.04 with cni version….

Infrastructure as Code (IaC) with Terraform & Azure DevOps

Infrastructure as Code (IaC) with Terraform & Azure DevOps

Walking through the basics of managing infrastructure with terraform and azure devops, recommended from medium.

Basic diagram of resources being deployed.

Terraform to Azure: Creating a dev environment

Using terraform to create an on-demand dev environment on azure..

Automate Your Deployment Using Azure DevOps CI CD Pipeline in 30 minutes

Mohammad Abu Humaidan

Automate Your Deployment Using Azure DevOps CI CD Pipeline in 30 minutes

What is azure pipeline(mean).

terraform azure the role assignment already exists

Coding & Development

A set of bold icons including a skull, notification bell, and hamburger

Icon Design

Image by vectorjuice on FreePik

The New Chatbots: ChatGPT, Bard, and Beyond

Close-up Shot of a Person Wearing a Robber Mask

Tech & Tools

Azure Automation Account Runbook CI/CD using Github Actions and Terraform

DevOpsWithYoge

Azure Automation Account Runbook CI/CD using Github Actions and Terraform

Hi all, this blog is about how to automate the deployment of runbooks in azure automation account by ensuring code quality during ci/cd….

Using Terraform to configure Azure Policy Parameters

Robbie Douglas

Using Terraform to configure Azure Policy Parameters

In an earlier article i looked at using terraform (tf) to deploy azure policy. now i’m going to take that one step further and explain how….

Build and Push Docker image to Azure Container Registry

Build and Push Docker image to Azure Container Registry

A step-by-step guide on how to build and push sample docker image to azure container registry using azure devops pipeline from scratch….

Azure WorkLoad Identity

Vishnu Vardhana Reddy

Azure WorkLoad Identity

Workloads deployed in kubernetes clusters require azure ad application credentials or managed identities to access azure ad protected….

Text to speech

This browser is no longer supported.

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

Azure Bicep authorization roleassignements to storage account fails with error The role assignment already exists

We are trying to assign a user-assigned managed identity to a storage account using Microsoft.Authorization/roleAssignments@2018-01-01-preview resource but it is failing and giving an error if the role already exists. we need to ignore the error to proceed ahead with bicep deployment. Is there any way to check if that role already exists on the resource and skip the assignment?

Azure Storage Accounts Globally unique resources that provide access to data management services and serve as the parent namespace for the services. 2,762 questions Sign in to follow

Microsoft Entra ID A Microsoft Entra identity service that provides identity management and access control capabilities. Replaces Azure Active Directory. 19,858 questions Sign in to follow

We also got the same problem - seems like such a beginner issue, I can't believe MS didn't think of providing a solution for it. When auto-deployments fail at the second run because a role already exists and I cannot skip the step, then they are not much of an auto-deployment...

@Kuldeep Bhatt Thank you for your post and I apologize for the delayed response!

For the RBAC side of things, if you're receiving an error similar to the below when deploying your resources with Bicep, you can check if the role already exists on the resource by navigating to Access Control (IAM).

204862-image.png

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) .
  • Select Role Assignments
  • Confirm that the User-Assigned Managed Identity has the correct role assigned

204863-image.png

I hope this helps!

If you have any other questions, please let me know. Thank you for your time and patience throughout this issue.

Please remember to " Accept Answer " if any answer/reply helped, so that others in the community facing similar issues can easily find the solution.

Hi @JamesTran-MSFT Thanks for sharing the answer, Actually I am using bicep for the deployment of resources and I have written bicep code for it. Actually, the thing is when I run the script for the first time it is getting succeeded and after that, I am changing some properties and run the bicep script another time giving the error, Ideally, it should check if role-assignment is already there it should ignore it. Due to this the bicep deployment is getting failed.

@Kuldeep Bhatt Thank you for following up on this!

I'm not too familiar with Bicep however, we do have a dedicated Azure-Bicep forum on Stack Overflow if you need assistance troubleshooting/ modifying your Bicep File.

For the RBAC side of things, here are some questions to consider to hopefully help avoid your bicep deployment failures due to RBAC.

Are you deploying multiple resources into one resource group?

  • If so, depending on the life cycle of those resources, you can try deploying them into separate resource groups.

Does the user(s) need access/control over all the resources being deployed?

  • If the user(s) don't need access/control over all the resources being deployed, you can try to scope the RBAC role directly to the resource.

Is the RBAC role being assigned at the resource group level?

  • If so, you can try to scope the RBAC role directly to the resource rather than the resource group level.

Additional Links: Best practices for Azure RBAC

@Kuldeep Bhatt I just wanted to check in and see if you had any other questions or if you were able to resolve this issue?

@JamesTran-MSFT This Azure-Bicep forum on Stack Overflow link doesn't give exact answer, but it show lots of option. Me too facing the same problem and I deep dive into microsoft docx and found nothing. Can you please help us!

Answer does not address the issue. My bicep code can't go and look at the portal gui interface. I need code to add to my bicep to skip role creation if the role already exists. Need a code solution, not a go use the gui solution. Please provide complete start to finish solutions in bicep. Lack of useful complete bicep examples is frustrating. I don't believe that Microsoft understands how their customers are attempting to use their system and their efforts, documentation, proposed soutions do not match what we need.

Gotta agree. Bicep is supposed to deal with this stuff - if a resource already exists, bicep of course doesn't give an error. It's meant to be rerun each time we want to deploy our apps.

Any updates here? I just ran into the same exact problem. I'm using version Microsoft.Authorization/roleAssignments@2022-04-01 of the resource.

I have the same problem, second deployment fails - I'm using a Group rather that a managed identity. The role assignment name is constant between deployments so it should check if it already exists? The group I am adding is a contributor on the Resource Group. I can successfully give managed identities and users the same role on the same storage account via the same method in bicep!

This is the error message

{ "error": { "code": "RoleAssignmentExists", "message": "The role assignment already exists." } } (Code:Conflict)

Frustrating!

After a bit more troubleshooting I realised a teammate had manually created the role assignment. The weird thing here is that the first bicep deploy still succeeds and you end up with 2 role assignments the same. Its only on the second bicep deploy it errors with the conflict!

I found the answer here: https://learn.microsoft.com/en-us/answers/questions/1007498/microsoft-authorization-roleassignments-devops-ci

In the end I am testing now with unique resource name for each rerun with guid(utcNow())

How then are you cleaning up all of the resources from previous runs?

Hi Michael you don't need to cleanup resources from previous runs, only think required is that role assignment name needs to be unique on each run :( This issue is there only for role assignments. But it's long time when i was implementing this.

DEV Community

DEV Community

Krzysztof Kopieczek

Posted on Oct 26, 2021

terraform apply in Azure DevOps fails with "resource with the ID already exists"

terraform init settings in the Azure DevOps Pipeline

Everything was configured properly. Code was working fine from my local machine, but in Azure DevOps, pipeline run successfully only for the first time. Every next attempt resulted in the following error: Error: The process 'C:\hostedtoolcache\windows\terraform\1.0.8\x64\terraform.exe' failed with exit code 1

And details from the log: Error: [0m[0m[1mA resource with the ID "/subscriptions/45197771-2d3e-4685-aaef-e96f62dd80b4/resourceGroups/tfexample-sample-rg" already exists - to be managed via Terraform this resource needs to be imported into the State. Please see the resource documentation for "azurerm_resource_group" for more information.[0m

The problem was in my code

It was missing the backend part! Code worked from my local machine, because terraform saved the state in local terraform.tfstate file (default terraform behavior), but in Azure DevOps the settings provided in the UI was ignored with no clear error message. terraform apply couldn't find the state file, so was creating every resource from scratch each time.

The solution

I fixed the code by adding empty properties. That was enough to have the pipeline working correctly. Note that no values are required...

Please leave some comment if this helped.

Top comments (5)

pic

Templates let you quickly answer FAQs or store snippets for re-use.

patheyacine profile image

  • Joined Jul 4, 2022

You saved me hours of struggle. Thank you so much. I implemented your suggestion and it started working :)

mohameedtrabelsi profile image

  • Joined Mar 24, 2022

hello, is this the solution ? because , i have a similare one when i create a resource using a pipeline azure and when i want to update the code with adding some resources, it give me the some error

kopieczekdev profile image

  • Location Poland
  • Joined Apr 18, 2021

hello, sorry for late response generally - yes. With this error, it's an issue with state - probably it's not stored anywhere

annapurnamaha profile image

  • Joined Mar 8, 2024

If we leave backend settings blank, then where would our state file have saved?

in Azure Dev Ops

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink .

Hide child comments as well

For further actions, you may consider blocking this person and/or reporting abuse

arindam0310018 profile image

Microsoft OpenAI Architecture

Arindam Mitra - May 12

blessingoseyenum profile image

Creating a Storage Account for a Public Website on Azure

Blessing Oseyenum - May 22

spencernguyen profile image

Azure SQL vs MySQL: What are the Differences?

Spencer Nguyen - May 9

techielass profile image

Introduction to Azure Arc Site Manager

Sarah Lean 🏴󠁧󠁢 - May 9

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

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

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

azurerm_role_assignment is not state aware #5297

@sebader

sebader commented Jan 3, 2020

@tombuildsstuff

tombuildsstuff commented Jan 8, 2020

Sorry, something went wrong.

@ghost

ghost commented Mar 29, 2020

@ghost

No branches or pull requests

@tombuildsstuff

How do I configure an Azure role assignment with Terraform?

In Terraform, you can set up an Azure role assignment using the azurerm_role_assignment resource.

This resource allows you to define a Role Assignment that is assigned to a specified Principal (like a User or a Managed Identity).

Here’s a small program that does this:

First, we need to set up the provider and connect to Azure. A provider block is used to configure the named provider, in this case azurerm .

Next, we setup the role definition and resources to which it will be applied. In real-life projects, these resources should already exist. But for simplicity, we'll define it all in this program.

Now we can create the role assignment. We're going to assign the Storage Blob Data Contributor role to the User or Principal that was set up earlier, granting them certain permissions to the storage account.

After applying this, the user should have the role permissions in the respective storage account.

Remember, you’ll need to set up your Azure credentials on the system that you’ll run the terraform commands in, so Terraform can connect and apply the changes to Azure.

For more information on azurerm_role_assignment , see the terraform documentation .

  • TS TypeScript
  • JS JavaScript
  • TF Terraform

IMAGES

  1. Azure landing zones

    terraform azure the role assignment already exists

  2. GitHub

    terraform azure the role assignment already exists

  3. List Azure role assignments using the Azure portal

    terraform azure the role assignment already exists

  4. Building Infrastructure With Azure Pipelines Using Terraform Nicholas

    terraform azure the role assignment already exists

  5. Deploy and Manage Azure Infrastructure Using Terraform, Remote State

    terraform azure the role assignment already exists

  6. Install And Configure Terraform Azure

    terraform azure the role assignment already exists

VIDEO

  1. Terraform Azure Community Call April 2023

  2. Automate the Automation PART 3: Setup an Azure DevOps Pipeline using Terraform

  3. How To Use Data Sources In Terraform

  4. 04.Understand required providers in Terraform Block

  5. Terraform Azure Parte 1

  6. #terraform

COMMENTS

  1. r/Terraform on Reddit: If a role assignment already exists for an Azure

    Alternative solution: remove the role assignment in the portal or using azure cli or powershell. Then re-run your terraform. However, none of these solutions are not going to help you long term if you don't decide the before mentioned where and when.

  2. azure

    So when you check if the role assignment exists, you can only need to check if the result of the PowerShell command is null or not. ... How to know the azure role assignment already exists. 1. Automation account rerun, a jobshedule already exist. 0. Azure powershell role assisgment using cloudshell and devops pipline. 0. Unable to Update RBAC ...

  3. When applying azurerm_role_assignment with terraform resource is

    Status=409 Code="RoleAssignmentExists" Message="The role assignment already exists." on roles.tf line 6, in resource "azurerm_role_assignment" "ra1": 6: resource "azurerm_role_assignment" "ra1" { Error: authorization.RoleAssignmentsClient#Create: Failure responding to request: StatusCode=409 -- Original Error: autorest/azure: Service returned ...

  4. azurerm_pim_eligible_role_assignment attempts to recreate ...

    Terraform should not loose the existing PIM eligible role assignment from it state and should not try to recreate it despite the role assignment still exists in Azure. The state of Terraform must be always the as the state in Azure it self. Actual Behaviour. After a period of time, circa 45 days Terraform removes the roles assignment form the ...

  5. Error in azurerm_role_assignment #12060

    Provider 2.62 removed the role assignment objects from the terraform state for a log analytics resource and so is planning to recreate the role assignements. It then fails as the assignment already exists. However when I checked another role assignment on a resource group it appears to plan with no changes as expected.

  6. Managing Azure RBAC Roles and Assignments with Terraform

    Here is a way of managing a custom roles and role assignments in Azure using Terraform. The versions of Terraform, AzureRM, and the AzureAD provider I'm using are as follows: In this example, I'm creating a custom role that allows some users to view a shared dashboard in our Azure subscription. The users should be able to view the dashboard ...

  7. azurerm_pim_eligible_role_assignment attempts to recreate ...

    Terraform attempts to recreate it and fails as it already exists. Steps to Reproduce. Update PIM settings to allow permanent role assignments, Create a PIM Role assignment without expiry, Wait circa 45 days, reapply terraform config. Important Factoids. No response. References. No response

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

  9. Role assignments that reference built-in roles are always ...

    The random GUID, used for the role assignment name, should stay the same the second time run, so if nothing else changes the assignment should be untouched. The role definition references a built-in role AcrPull. Actual Behavior. The provider sees the resource id change to <computed> so the resource gets deleted and re-created every-time. Also ...

  10. terraform apply in Azure DevOps fails with "resource with the ID

    Everything was configured properly. Code was working fine from my local machine, but in Azure DevOps, pipeline run successfully only for the first time. Every next attempt resulted in the following error: Error: The process 'C:\hostedtoolcache\windows\terraform\1..8\x64\terraform.exe' failed with exit code 1. And details from the log:

  11. azurerm_role_assignment is not state aware #5297

    Generally speaking Terraform should be erroring if trying to create a resource which already exists - however there's a known issue in 1.x versions of the Azure Provider where certain resources may instead be "adopted" into the state (due to the majority of Azure's API's being Upserts, rather than separate Create/Update endpoints) rather than ...

  12. Configuring Azure Role Assignments with Terraform

    This resource allows you to define a Role Assignment that is assigned to a specified Principal (like a User or a Managed Identity). First, we need to set up the provider and connect to Azure. A provider block is used to configure the named provider, in this case azurerm. Next, we setup the role definition and resources to which it will be applied.

  13. terraform

    To resolve the error, I assigned Owner role to the service principal under subscription like below: After assigning that role, role assignments created successfully on resource group when I ran below query again: In your case, try assigning your service principal Owner role under subscription to resolve the issue.

  14. azure

    terraform import causes Terraform to create a binding between the resource configuration you wrote and the remote object whose id you gave on the command line, which is henceforth indistinguishable to Terraform from it having created that object and recorded the binding itself in the first place.