app_role_assignment_required terraform

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.

Provision AKS cluster utilizing Terraform and Azure DevOps

Anil Bidary

Provision AKS cluster utilizing Terraform and Azure DevOps

Terraform with azure devops.

Azure Kubernetes Service Pipeline via Azure DevOps

Saurabh Mathuria

Azure Kubernetes Service Pipeline via Azure DevOps

What is aks:  azure kubernetes service (aks) is a managed kubernetes service provided by microsoft azure. it simplifies deploying….

app_role_assignment_required terraform

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

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

Azure Hub and Spoke Structure

Harsh Bakshi

Azure Hub and Spoke Structure

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

Azure Hub and Spoke with DNS Proxy using Terraform

Mostafa Aboubakr

Level Up Coding

Azure Hub and Spoke with DNS Proxy using Terraform

Introduction.

Text to speech

Matthew Davis

Identity, PowerShell, Azure, AWS, Okta, infrastructure automation. Documenting what I’m learning.

  • Custom Social Profile Link

Use Terraform to deploy an Azure AD application

4 minute read

This post will cover how to deploy an Azure AD application using Terraform and assign it permissions to the Microsoft Graph with User.Read scope. I’m using the latest version of Terraform (currently 1.0.3), latest version of the AzureAD provider (currently 1.0.6) and running on Ubuntu 18.04. Although this was carried out on a Ubuntu machine, it should be very similar for Windows or Mac.

The current AzureAD Terraform provider (1.0.6) uses the legacy Azure Active Directory Graph to interact with the API by default. Version 2 of the provider will be updated to use the Microsoft Graph API. For this post I’ve decided to use the Microsoft Graph which is currently in Beta support for this provider version but is not advised for production use.

This isn’t a beginners guide to Terraform or AzureAD, more of a post of how I have deployed to AzureAD with Terraform so a basic understanding of both would be beneficial.

Create application with permissions to deploy applications

The first step is we need to authenticate to be able to perform actions such as create, update and remove resources.

The easiest way to create a service principal is the Azure CLI. The Azure CLI can be installed locally or you can use it from the Azure cloud shell from the browser.

After running the above command, appID and password are displayed, keep a note of these somewhere secure such as a password manager.

Alternatively there is the guide on creating a service principal in the portal , however the Azure CLI is much quicker and easier.

Now a service principal will be created in Azure AD. You can view this by going to the AzureAD portal , selecting the Enterprise applications blade, changing the Application type to All Applications then searching tor the test-terraform-ad service principal.

Service principal in portal

Note: Because we authenticate interactively with az login , Terraform would be authenticated in that session but I want to demonstrate how to do this with Service Principal credentials so they can be used in a CI/CD pipeline in the future.

Required permissions

Assign the application administrator role to the service principal previously created test-terrafrom-ad .

You can use the Microsoft Graph API to set the role or via the portal as per screen shot below.

Go to Azure Active Directory then the Roles and administrators blade. Click on the Application administrator role, then the + Add assignments button and then Select Members link. Search for test-terrafrom-ad and confirm.

App admin role in portal

Set up Terraform

Create a new directory locally, and change directory to it.

Copy the contents of the following files.

Main file (main.tf).

Variable values file (terraform.tfvars).

Setting the credentials

Set the credentials of the Service Principal in authentication environment variables:

To initialize Terraform run the following:

This will store the state locally on your machine in the same directory.

output of terraform init

Validate everything is good by running:

The secret line is intentionally indented to keep it out of the bash history.

Plan the deployment

Now it’s time to run a plan to see what is going to be created. The plan is save to a file locally and the will be used to deploy the resources.

Deploying the application

If all looks good, it can be deployed using the output from the above plan command.

In the AzureAD portal under Azure Active Directory blade App registrations blade and All applications search for the created app.

app in portal

Select the app then the API permissions blade to see the User.Read scope granted to the app.

user read api permissions granted

The application password

Previously with the legacy Azure API you could specify the application secret however with the Microsoft Graph API, the secret is generated. To find the generated value, look in the terraform.tfstate file. Under the “type”: “azuread_service_principal_password” you’ll see “attributes” and then “value” which has the password. This is why it is very important to protect the Terraform state file (it can contain sensitive information ), especially when working with a remote backend, it should be encrypted at rest and limited access applied to the backend.

Update the application

Now the deployment has been made, the plan is stale and needs updating.

Running an apply command again will result in nothing being changed.

Change the name of the value in the tfvariables.tf file to something else and run:

A change will be displayed.

Run the apply command to update the application.

Refresh the Overview page and you’ll see the new Application name.

update name displaying in portal

Destroy the application

Clean up the application and service principal using the destroy command.

Because the auto-approve option is not specified, a prompt will ask to confirm.

The resources managed by Terraform will be deleted.

I’ve created another post on how to configure Azure blob storage to save the state file remotely so it can be used in a team environment so if you want to follow along with that, keep the service principal otherwise it can be removed by running the Azure CLI:

Now all the resources for this post will be removed.

You May Also Enjoy

How to call a python script from powershell.

1 minute read

Call a Python script passing an argument and saving return value in variable example.

How to create JSON Web Key Sets (JWKS) with Python

Creating a JSON Web Key Sets (JWKS) with Python for use with an Okta service application to authenticate with Terraform.

Airthings consumer API with Python

How to authenticate and query the Airthings API with Python

Query Workday API using Python and the Zeep package

3 minute read

How to authenticate with the Workday SOAP API and query for a worker by worker ID using Python and Zeep.

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

New Property on azuread_application #886

@rohrerb

rohrerb commented Sep 14, 2022

@manicminer

naitmare01 commented Oct 25, 2022

Sorry, something went wrong.

@manicminer

manicminer commented Oct 26, 2022

  • 👍 1 reaction

@github-actions

github-actions bot commented Nov 26, 2022

@github-actions

No branches or pull requests

@manicminer

SoliDeoGloria.tech

Technology for the Glory of God

Grant Admin Consent for an Azure AD Application With Terraform

  • 21 Feb 2024

One challenge we often run into when provisioning Azure AD applications with Terraform is a need to grant admin consent for API permissions. Sadly there is not a native resource within Terraform to make this happen, however with some creative use of provisioners (yes, I feel bad about it too) we can ensure that admin consent is granted for our applications.

To start with, we deploy our Azure AD application as normal. As part of the configuration, we also assign the required API permissions.

If you run the above Terraform code, and then find your application in Azure AD, you will see that it helpfully reminds you that administrative consent is required for these permissions.

Admin consent required

So how do we get over this last hurdle?

Update: So, it turns out that Terraform does have a resource for granting consent. My thanks to Jonas Gschwend for reaching out and letting me know that I had completely missed the azuread_app_role_assignment resource. And to my shame, it’s not like this is a new resource. It first arrived in the v2.4.0 provider, more than 2 years ago. So I’ve updated the solution to use this resource. The original solution is left below that for ~humility~ posterity.

Enter the azuread_app_role_assignment resource. It allows us to specify which role assignments should be approved for a specific service principal. In addition to being a native resource, it also allows us to only approve the permissions we have allocated. With the orginal script option, if someone managed to add a permission to the app before we ran the approval, that permission would also be granted.

Aside: The azuread_app_role_assignment resource requires a service principal (Enterprise Application) to be created, while the original solution could operate on the application registration. In most situations that won’t matter as we normally create the service principal in additon to the registration. But we need to account for this and turn off login and display to users if we don’t need the SP.

However nothing is quite a straightforward as it seems. The azuread_app_role_assignment requires us to pass the object_id of the service principal to which we are granting access. However this is not used in the required_resource_access block on the application, so we don’t have direct access to it. To do this we need to get the details of all the service principals available to us.

We can then use this data resource in a for_each block

And just like that, we have approvals of the API permissions for the application!

Original solution:

While Terraform doesn’t provide a resource to grant admin consent, the Azure CLI does. The az ad app permission admin-consent command will grant admin consent for all assigned permissions, if you have the correct permissions. 1

Enter the Terraform provisioner block . A local-exec provisioner allows us to run a command on the local machine after creating a resource. Perfect! we might say. There is one catch however. The provisioner command only runs once, after the resource is created. While that is fine for 99% of requirements, in some situations we may want to be able to run the command after a change to the resource — in our case, we want it to also run if we change the permissions assigned to the application.

So enter the Terraform null_resource . One of the features of the null_resouce is the ability to define a map which will trigger the recreation of the resource (and therefore the running of the provisioner) if the values change.

For the triggers, we loop through the list of required_resource_access blocks created in the azuread_application (the outer for loop), and then loop through the actual permissions granted for each app (the inner for loop). We then build a map of values, where the key is the combination of the application ID and the role ID, and the value is the type of permission granted.

What this means is that if we add or remove a permission from the application, this map will change, which will then trigger the null_resource to be recreated. On recreation, the admin consent CLI command will run (after a 30 second pause to allow Azure AD to catch up to the creation of the application if required) and the permissions will be consented.

Either Privileged Role Administrator or Global Administrator is required.  ↩︎

IMAGES

  1. How to deploy high-availability web app using Terraform

    app_role_assignment_required terraform

  2. Azure App Service Terraform Module

    app_role_assignment_required terraform

  3. Deploy a Dapr application to Azure Container Apps with Terraform

    app_role_assignment_required terraform

  4. azure

    app_role_assignment_required terraform

  5. Deploy your first container app using Terraform and GitHub Actions

    app_role_assignment_required terraform

  6. GitHub

    app_role_assignment_required terraform

VIDEO

  1. Creating and deleting Azure Function app using Terraform

  2. YouTube Live on Terraform PROD level course

  3. Terraform

  4. Simple & Secure Networking

  5. How to Use Terraform

  6. 04.Understand required providers in Terraform Block

COMMENTS

  1. Retrieved assigned App Roles using Terraform

    The final goal is assign an App roles only if it's not already assigned. There is no direct way via Terraform, you can use a PowerShell script inside Terraform by employing the null_resource. Here is the PowerShell script to check the app roles for the user and assign the role if it is not already assigned. script.ps1.

  2. Can I assign an app role access to a managed identity with Terraform?

    It is possible to assign app role access for an app registration in terraform using required_resource_access for azuread_application. This will give access to a custom role to my API to another application/service principal. ... resource "azuread_app_role_assignment" "example" { app_role_id = azuread_service_principal.msgraph.app_role_ids["User ...

  3. Import AzureAD app role assignments into Terraform state

    Import existing app role assignments into the Terraform state. Having the app role assignment ID in a variable named ASSIGNMENT_ID and the AzureAD enterprise application for Snowflake having ID ...

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

  5. azuread_app_role_assignment -- required AppRoleAssignment ...

    I am currently working with the azuread_app_role_assignment resource and per documentation it requires AppRoleAssignment.ReadWrite.All permissions. This permission level is extremely robust and gives a Service Principal Name (SPN) access to manage all applications, which is not acceptable in our enterprise environment.

  6. Add additional app_role & app_role_assignment to existing application

    For the additional added app_role a application role in the azuread_application, a group in azuread and the assignment of the group to the app_role is done as it will be done within the inital setup. Actual Behavior. After adding a additional app_role, terraform plan ends up with Error: Invalid index ╷ │ Error: Invalid index │

  7. Use Terraform to deploy an Azure AD application

    You can use the Microsoft Graph API to set the role or via the portal as per screen shot below. Go to Azure Active Directory then the Roles and administrators blade. Click on the Application administrator role, then the + Add assignments button and then Select Members link. Search for test-terrafrom-ad and confirm.

  8. Error: Could not create app role assignment #736

    This app role must be exposed in the appRoles property on the resource application's service principal (resourceId). If the resource application has not declared any app roles, a default app role ID of 00000000-0000-0000-0000-000000000000 can be specified to signal that the principal is assigned to the resource app without any specific app roles.

  9. New Property on azuread_application #886

    This helps our maintainers find and focus on the active issues. If you have found a problem that seems similar to this, please open a new issue and complete the issue template so we can capture all the details necessary to investigate further. Request to add Assignment Required to azuread_application. Image of the field in Azure AD:

  10. Managing Active Directory with Azure AD Terraform Provider

    Note: New versions of Terraform will be placed under the BUSL license, but everything created before version 1.5.x stays open-source. OpenTofu is an open-source version of Terraform that will expand on Terraform's existing concepts and offerings. It is a viable alternative to HashiCorp's Terraform, being forked from Terraform version 1.5.6.

  11. Grant Admin Consent for an Azure AD application with Terraform

    Original solution: While Terraform doesn't provide a resource to grant admin consent, the Azure CLI does. The az ad app permission admin-consent command will grant admin consent for all assigned permissions, if you have the correct permissions. 1. Enter the Terraform provisioner block . A local-exec provisioner allows us to run a command on ...

  12. Getting Error on the Terraform code while Azure App Registration Log

    Thank you for your response, Youcef Laidan. There is other issue I have identified in this resource block : resource "azuread_service_principal" "LogAnalyticsApi" { application_id = data.azuread_application_published_app_ids.log.result.LogAnalyticsAPI use_existing = true owners = [data.azuread_client_config.current.object_id] } The application_id = "ca7f3f0b-7d91-482c-8e09-c5d840d0eac5" #Data ...