This browser is no longer supported.

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

Configure Azure Virtual Desktop role-based access control using Terraform

  • 5 contributors

Article tested with the following Terraform and Terraform provider versions:

  • Terraform v1.1.4
  • AzureRM Provider v.2.94.0

Terraform enables the definition, preview, and deployment of cloud infrastructure. Using Terraform, you create configuration files using HCL syntax . The HCL syntax allows you to specify the cloud provider - such as Azure - and the elements that make up your cloud infrastructure. After you create your configuration files, you create an execution plan that allows you to preview your infrastructure changes before they're deployed. Once you verify the changes, you apply the execution plan to deploy the infrastructure.

This article will walk through adding our users and Microsoft Entra group and then assign the group to the "Desktop Virtualization User" role, scoped to our host pool.

In this article, you learn how to:

  • Use Terraform to read Microsoft Entra existing users
  • Use Terraform to create Microsoft Entra group
  • Role assignment for Azure Virtual Desktop

1. Configure your environment

  • Azure subscription : If you don't have an Azure subscription, create a free account before you begin.

Configure Terraform : If you haven't already done so, configure Terraform using one of the following options:

  • Configure Terraform in Azure Cloud Shell with Bash
  • Configure Terraform in Azure Cloud Shell with PowerShell
  • Configure Terraform in Windows with Bash
  • Configure Terraform in Windows with PowerShell

2. Implement the Terraform code

Create a directory in which to test the sample Terraform code and make it the current directory.

Create a file named providers.tf and insert the following code:

Create a file named main.tf and insert the following code:

Create a file named variables.tf and insert the following code:

  • Create a file named output.tf and insert the following code:

6. Initialize Terraform

Run terraform init to initialize the Terraform deployment. This command downloads the Azure provider required to manage your Azure resources.

Key points:

  • The -upgrade parameter upgrades the necessary provider plugins to the newest version that complies with the configuration's version constraints.

7. Create a Terraform execution plan

Run terraform plan to create an execution plan.

  • The terraform plan command creates an execution plan, but doesn't execute it. Instead, it determines what actions are necessary to create the configuration specified in your configuration files. This pattern allows you to verify whether the execution plan matches your expectations before making any changes to actual resources.
  • The optional -out parameter allows you to specify an output file for the plan. Using the -out parameter ensures that the plan you reviewed is exactly what is applied.

8. Apply a Terraform execution plan

Run terraform apply to apply the execution plan to your cloud infrastructure.

  • The example terraform apply command assumes you previously ran terraform plan -out main.tfplan .
  • If you specified a different filename for the -out parameter, use that same filename in the call to terraform apply .
  • If you didn't use the -out parameter, call terraform apply without any parameters.

You are now ready to build and deploy your infrastructure with role based access control.

9. Clean up resources

When you no longer need the resources created via Terraform, do the following steps:

Run terraform plan and specify the destroy flag.

Run terraform apply to apply the execution plan.

Troubleshoot Terraform on Azure

Troubleshoot common problems when using Terraform on Azure

Learn more about Configuring Azure Virtual Desktop session hosts using Terraform in Azure

Was this page helpful?

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

Submit and view feedback for

Additional resources

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.  ↩︎

NashTech Insights

nashTechLogo-red

Digital solutions for your business.

Combining strategy, technology, automation and people

Technology advisory

Navigate the fast-changing world.

Cloud engineering

Transformational change at scale and speed

Data solutions

Realise the untapped potential of data.

AI and machine learning

Leverage your data assets.

Application engineering

Optimise and grow your digital investment.

Maintenance and support

End-to-end application management.

Business process solutions

Manage business processes to reduce operating costs.

Quality solutions

Independent testing for your systems and software.

We provide solutions tailored to your sector to assist you in identifying opportunities, realising value and opening up new markets.

Financial services and insurance

Insurance, risk management, banks, and fintech

Patient empowerment, Lifesciences, and pharma

Functional and emotional customer experiences online and in-store

Airlines, online travel giants, niche disruptors

Media and publishing

Content consumption for the tech-driven audience

Hi-tech and IOT

Real-time information and operational agility and flexibility to respond to market changes

Logistics and supply chain

Reimagine a supply chain that is more flexible and resilient to change

Create an exciting and engaging digital experience for students and departments

Our thinking

The latest updates to help future-focused organisations on the issues that matter most in business.

app_role_assignment_required terraform

  • Case studies

Managing Azure Role Assignments with Terraform

  • Application Management Services , Cloud Engineering
  • September 3, 2023

Picture of Atisha Shaurya

Atisha Shaurya

Table of contents.

woman in brown jacket sitting on armchair while using her laptop

Azure Role-Based Access Control (RBAC) is a powerful feature that allows you to manage access to Azure resources. With Azure RBAC , you can grant specific permissions to users, groups, or applications, ensuring they have the right level of access to Azure resources. Terraform, an Infrastructure as Code (IaC) tool, can help you automate and manage Azure RBAC role assignments efficiently. In this blog post, we’ll explore the importance of Azure RBAC and guide you through how to manage role assignments using Terraform.

Why Use Azure RBAC?

Azure RBAC offers several key benefits:

  • Granular Access Control : RBAC provides fine-grained control over access to Azure resources, ensuring that users only have the permissions they need to perform their tasks.
  • Security : RBAC enhances the security of your Azure environment by reducing the risk of unauthorized access and data breaches.
  • Compliance : Many regulatory standards, such as HIPAA and GDPR, require strict access control. Azure RBAC helps you meet compliance requirements.
  • Efficiency : Automating RBAC role assignments with Terraform streamlines the access management process and reduces manual errors.

Managing Azure RBAC Role Assignments with Terraform

To manage Azure RBAC role assignments using Terraform, follow these steps:

1. Install Terraform

If you haven’t already, install Terraform by following the official installation guide: Terraform Installation Guide

2. Authenticate Azure CLI

Ensure you are authenticated with your Azure subscription using the Azure CLI:

3. Create a Terraform Configuration

Create a new directory for your Terraform configuration and create a .tf file, e.g., rbac.tf . Add the following content to define a role assignment:

In this Terraform configuration:

  • We specify the Azure provider.
  • We create an azurerm_role_assignment resource, defining the principal_id , role_definition_name , and scope .

4. Initialize and Apply the Configuration

Navigate to the directory where your Terraform configuration file is located. Initialize Terraform by running:

Then, apply the configuration to create the role assignment:

Terraform will prompt you to confirm the creation of the role assignment. Enter yes to proceed.

5. Verify the Role Assignment

Once Terraform completes the deployment, you can verify the role assignment on the Azure portal or by using Azure CLI commands. For example, to list role assignments for a specific resource group:

Managing Azure RBAC role assignments using Terraform streamlines access control, enhances security, and ensures compliance with regulatory standards. By following the steps outlined in this blog post, you can efficiently assign roles to users, groups, or applications, ensuring they have the right level of access to Azure resources. This automation simplifies access management and reduces the risk of manual errors, making your Azure environment more secure and compliant.

Share this:

Suggested article, leave a comment cancel reply.

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

Save my name, email, and website in this browser for the next time I comment.

Notify me of follow-up comments by email.

Notify me of new posts by email.

Harnessing AI for Dynamic Element Identification in Test Automation: Architectural Insights

Harnessing AI for Dynamic Element Identification in Test Automation: Architectural Insights

JavaScript

What’s New in JavaScript in 2023- ECMAScript 14th edition

Exploring .net core optimization techniques.

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

Assigning Users or Groups to an Enterprise Application in Azure #164

@VF-mbrauer

VF-mbrauer commented Oct 16, 2019

  • 👍 78 reactions

@matsest

matsest commented Oct 24, 2019 • edited

Sorry, something went wrong.

@drdamour

drdamour commented Jan 10, 2020 • edited

@no-acl

no-acl commented Mar 13, 2020

@PfisterAn

PfisterAn commented Apr 7, 2020

  • 👍 1 reaction

@manicminer

manicminer commented Jun 3, 2020

Drdamour commented jun 3, 2020.

  • 👍 12 reactions

@waqarkhan3389

waqarkhan3389 commented Jul 6, 2020

@ghost

ghost commented Sep 2, 2020

  • 👍 8 reactions

@randywallace

randywallace commented Nov 10, 2020 • edited

  • 👍 6 reactions
  • 🚀 1 reaction

@bryancpowell

bryancpowell commented Dec 17, 2020

  • 👍 10 reactions

@CaptainStealthy

CaptainStealthy commented Jan 21, 2021 • edited

Manicminer commented jan 21, 2021.

@adamrushuk

t-l-k commented Feb 2, 2021

Manicminer commented feb 2, 2021, randywallace commented feb 3, 2021.

@treyhendon

treyhendon commented Mar 8, 2021

Captainstealthy commented apr 20, 2021.

@Yanson

dekimsey commented May 5, 2021 • edited

@Fresa

Fresa commented May 7, 2021

Dekimsey commented may 8, 2021, fresa commented may 26, 2021.

@reifnir

reifnir commented Aug 27, 2021 • edited

  • ❤️ 2 reactions

@github-actions

github-actions bot commented Sep 23, 2021

  • 🎉 1 reaction

github-actions bot commented Oct 24, 2021

@github-actions

Successfully merging a pull request may close this issue.

@dekimsey

IMAGES

  1. Azure landing zones

    app_role_assignment_required terraform

  2. Provisioning RBAC with Terraform

    app_role_assignment_required terraform

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

    app_role_assignment_required terraform

  4. azure

    app_role_assignment_required terraform

  5. Azure landing zones

    app_role_assignment_required terraform

  6. How to create App Service(WebApp) in Azure using Terraform

    app_role_assignment_required terraform

VIDEO

  1. Terraform + Ansible Assignment

  2. N01619259 Terraform Assignment

  3. ENGLISH ASSIGNMENT (required) Transactional Conversation entitled "Plan to Holiday"

  4. Advance-Terraform-Day-2 || Mutable Vs Immutable infrastructure || Softwares required for Terraform

  5. Gitpod for data teams in 120 seconds

  6. S01 E34: User, Role, and Grants Provisioning in Snowflake

COMMENTS

  1. Terraform Registry

    <div class="navbar header-navbar"> <div class="container"> <div class="navbar-brand"> <a href="/" id="ember34" class="navbar-brand-link active ember-view"> <span id ...

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

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

  4. Azure Authorization Role Assignment Module

    AVM Terraform module for role assignments. Contribute to Azure/terraform-azurerm-avm-res-authorization-roleassignment development by creating an account on GitHub.

  5. Azuread_app_role_assignment: Provider produced inconsistent result

    @alxy That sounds like a separate issue as the original report is about the azuread_app_role_assignment resource rather than the app_role block on the azuread_application resource.. However, due to the way app roles (and permission scopes) have to be disabled before they can be updated or removed, we do our best to only affected the roles/scopes which have actually been changed.

  6. Configure Azure Virtual Desktop Role-Based access control using Terraform

    Configure your environment. Azure subscription: If you don't have an Azure subscription, create a free account before you begin. 2. Implement the Terraform code. Create a directory in which to test the sample Terraform code and make it the current directory. required_providers {. azurerm = {.

  7. Terraform Registry

    id - The Role Assignment ID. principal_type - The type of the principal_id, e.g. User, Group, Service Principal, Application, etc. Timeouts. The timeouts block allows you to specify timeouts for certain actions: create - (Defaults to 30 minutes) Used when creating the Role Assignment. update - (Defaults to 30 minutes) Used when updating the ...

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

  9. Managing Azure Role Assignments with Terraform

    Azure Role-Based Access Control (RBAC) is a powerful feature that allows you to manage access to Azure resources. With Azure RBAC, you can grant specific permissions to users, groups, or applications, ensuring they have the right level of access to Azure resources. Terraform, an Infrastructure as Code (IaC) tool, can help you automate and manage Azure RBAC role assignments efficiently.

  10. 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 │

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

  12. 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:

  13. Terraform Registry

    description - (Optional) The description for this Role Assignment. Changing this forces a new resource to be created. skip_service_principal_aad_check - (Optional) If the principal_id is a newly provisioned Service Principal set this value to true to skip the Azure Active Directory check which may fail due to replication lag. This argument is only valid if the principal_id is a Service ...

  14. How do I automatically create service principals or MSIs with Terraform

    I'm using Terraform, of course, to provision resources. If I do all of this without terraform (manually or with a bash script), I use azure cli I start setting permissions by doing the following: az login; az account set -s <my-subscription-id> I am the owner of my subscription. I can run all commands, create SPs, MSIs, assign roles, etc, with ...

  15. Terraform Registry

    hashicorp/terraform-provider-azuread latest version 2.48.0. Published 5 days ago. Overview ... Authentication; Upgrade Guides; Administrative Units; App Role Assignments; Applications. Resources. azuread_ application azuread_ application_ api_ access azuread_ application_ app_ role azuread_ application_ certificate azuread_ application ...

  16. azurerm_role_assignment doesn't seem to work with registered apps

    Create the role assignment using an application id. The equivalent az ad command is (I have verified this command works as well): az role assignment create --assignee <app_id> --role Owner --scope . Actual Behavior. Terraform fails on assigning the role when an app_id is provided. If you try to provide the object id Azure rejects this. Steps to ...

  17. How to add role assignment on System Assigned Identity using terraform?

    I already explore terraform official documentation but it lacks examples on how to specify adding role assignment. ... Required, but never shown Post Your ... Assign a managed identity access to an application role using Terraform. 0.

  18. Assigning Users or Groups to an Enterprise Application in Azure

    @JoeSainsburys and @randywallace great contributions, thanks, question though: this relies on the ambient Azure CLI authentication credential, right?. Users who may wish to use the same access token that is in use, by say, the azurerm provider, are going to have a challenge to get said access token out of said provider (and even then, has it all the necessary scopes).