This browser is no longer supported.

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

Quickstart: Create a policy assignment to identify non-compliant resources using Terraform

  • 6 contributors

The first step in understanding compliance in Azure is to identify the status of your resources. This quickstart steps you through the process of creating a policy assignment to identify virtual machines that aren't using managed disks.

At the end of this process, you identify virtual machines that aren't using managed disks across subscription. They're non-compliant with the policy assignment.

When assigning a built-in policy or initiative definition, it's optional to reference a version. Policy assignments of built-in definitions default to the latest version and automatically inherit minor version changes unless otherwise specified.

Prerequisites

  • If you don't have an Azure subscription, create a free account before you begin.
  • Terraform version 0.12.0 or higher configured in your environment. For instructions, see Configure Terraform using Azure Cloud Shell .
  • This quickstart requires that you run Azure CLI version 2.13.0 or later. To find the version, run az --version . If you need to install or upgrade, see Install Azure CLI .

Create the Terraform configuration, variable, and output file

In this quickstart, you create a policy assignment and assign the Audit VMs that do not use managed disks definition. This policy definition identifies resources that aren't compliant to the conditions set in the policy definition.

Configure the Terraform configuration, variable, and output files. The Terraform resources for Azure Policy use the Azure Provider .

Create a new folder named policy-assignment and change directories into it.

Create main.tf with the following code:

To create a Policy Assignment at a Management Group use the azurerm_management_group_policy_assignment resource, for a Resource Group use the azurerm_resource_group_policy_assignment and for a Subscription use the azurerm_subscription_policy_assignment resource.

Create variables.tf with the following code:

A scope determines what resources or grouping of resources the policy assignment gets enforced on. It could range from a management group to an individual resource. Be sure to replace {scope} with one of the following patterns based on the declared resource:

  • Subscription: /subscriptions/{subscriptionId}
  • Resource group: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}
  • Resource: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]

Create output.tf with the following code:

Initialize Terraform and create plan

Initialize Terraform to download the necessary providers and then create a plan.

Run the terraform init command. This command downloads the Azure modules required to create the Azure resources in the Terraform configuration.

Screenshot of running the terraform init command that shows downloading the azurerm module and a success message.

Authenticate with Azure CLI for Terraform. For more information, see Azure Provider: Authenticating using the Azure CLI .

Create the execution plan with the terraform plan command and out parameter.

Screenshot of running the terraform plan command and out parameter to show the Azure resource that would be created.

For information about persisting execution plans and security, see Terraform Plan: Security Warning .

Apply the Terraform execution plan

Apply the execution plan.

Run the terraform apply command and specify the assignment.tfplan already created.

Screenshot of running the terraform apply command and the resulting resource creation.

With the Apply complete! Resources: 1 added, 0 changed, 0 destroyed. message, the policy assignment is now created. Since we defined the outputs.tf file, the assignment_id is also returned.

Identify non-compliant resources

To view the resources that aren't compliant under this new assignment, use the assignment_id returned by terraform apply . With it, run the following command to get the resource IDs of the non-compliant resources that are output into a JSON file:

Your results resemble the following example:

The results are comparable to what you'd typically see listed under Non-compliant resources in the Azure portal view.

Clean up resources

To remove the assignment created, use Azure CLI or reverse the Terraform execution plan with terraform destroy .

In this quickstart, you assigned a policy definition to identify non-compliant resources in your Azure environment.

To learn more about assigning policies to validate that new resources are compliant, continue to the tutorial for:

Tutorial: Create and manage policies to enforce compliance

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

4sysops

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

Manage Azure Policy using Terraform

4sysops - The online community for SysAdmins and DevOps

Avatar

Prerequisites

Reviewing azure policy, configure the azurerm provider, create the policy definition, define metadata, define the parameters, define the policy rule, azurerm provider before 3.0, azurerm provider after 3.0, parameter values, terraform configuration deployment.

  • Recent Posts

Jeff Brown

  • Manage Azure Policy using Terraform - Tue, Aug 2 2022
  • Getting started with Terraform in Azure - Tue, Jul 12 2022
  • Azure Bicep: Getting started guide - Fri, Nov 19 2021

To follow along with this tutorial, you will need:

  • An Azure tenant and access to a subscription, like Owner or Contributor rights.
  • VS Code or other IDE. However, VS Code has a Terraform extension to improve the authoring process.
  • Terraform open-source command-line interface (install guide here ).
  • Azure CLI ( download ). This tutorial uses version 2.32.0.

Azure Policy enforces standards and assesses compliance in your cloud environment. You can perform actions such as limiting where you can deploy resources or enforcing tags. Azure Policy doesn't always have to prevent an activity; it can also perform audits. You can view resource compliance for things like storage accounts enabled for HTTPS traffic or whether SQL auditing is enabled.

Azure Policy's primary component is policy definitions. Policy definitions represent business rules that the environment should follow. You use a JSON-formatted language to describe the business rules and actions to take if the resource is noncompliant.

  • Enforce cloud governance with Azure Policy
  • Manage Azure Policy using PowerShell

Creating the Azure Policy

Like any other object in Terraform, you first define the resource—in this case, a policy definition. Before defining the policy definition, set up the foundations of a Terraform configuration by configuring the AzureRM provider . The AzureRM provider interacts with the Azure Resource Manager APIs to create and manage Azure resources. To see the completed tutorial code, reference the 4sysops_tf_azpolicy GitHub repository.

In a file named main.tf , create a Terraform configuration block with a required_providers section. This example sets the version to 3.13.0, but you can choose a newer or older version as needed. In the next section, you'll learn about some crucial differences HashiCorp made regarding Azure Policy between versions 2.0.0 and 3.0.0.

Next, create an azuremrm provider block with an empty features block. This example does not set any options, such as the subscription or storing authentication information. You will use the Azure CLI later in the tutorial to authenticate and select a subscription.

Next, create the policy definition using the azurerm_policy_definition resource type. This example policy enforces a naming convention for storage accounts. The policy definition has four required arguments:

  • name: Policy definition short name ("StorageAccountNamingConvention").
  • display_name: Policy definition display name ("Storage Accounts should follow naming convention").
  • mode: Policy mode to specify which resource types Azure evaluates the policy against ("Indexed").
  • policy_type: Policy type of "BuiltIn," "Custom," or "NotSpecified." This example uses "Custom."

While not required, you can define metadata for the policy definition. Metadata includes a version and a category. You use the Azure Policy JSON syntax inside the HashiCorp Terraform Language (HCL) when defining a policy. You place the JSON code inside a jsonencode() function. This function allows Terraform to interpret the JSON code and guarantee the correct syntax.

This example sets the policy version to "1.0.0" and the category to "Storage." Place this code in the same resource definition block as in the previous section.

Next, define any parameters used by the policy. In this example, there are two:

  • effectAction: The effect action is a string type that defines what action the policy takes. The two options are "Audit" or "Deny." Set the default value to "Audit."
  • namingPattern: This parameter is a string and sets the naming pattern the storage account should follow. Use a question mark (?) for letters and a pound symbol (#) for numbers. Set the default value to "4sysops???####", which translates to the prefix "4sysops" followed by three letters and four numbers.

Here is the parameters argument code block, which you place below the metadata argument code block. Continue to use the jsonencode() function so Terraform can validate the JSON syntax.

Next is the policy rule. The policy rule is the core of the definition, as it describes the resource conditions to match and the effect to take. Policy rules compare a resource property field or value to the required value.

In this example, the policy rule contains two conditions, both of which the resource must match for the policy to apply:

  • The resource type must be of type "Microsoft.Storage/storageAccounts".
  • The resource name does not match the value in the namingPattern parameter.

If both conditions are true, then the policy performs that action set in the effectAction parameter (remember, the default effect action is "Audit").

Here is the example code for the policy rule, which goes below the parameters argument code block. Again, use the jsonencode() function to wrap the JSON code.

Deploying the Azure Policy

Once your policy is defined, assigning it is next. You can set a policy for multiple scopes, such as a management group, subscription, resource group, or even an individual resource.

HashiCorp recently changed the method for creating assignments using the AzureRM provider. The sections below outline the two different ways, in case you run into code using an older version and need to understand it.

Before version 3.0, the AzureRM provider had a single resource for assigning policies, called azurerm_policy_assignment . You used this resource to assign policies to each scope. The resource had a single argument named scope that accepted a resource ID at the assignment level.

Here is some example code showing the syntax and how this worked. Do not add this to your main.tf file from the rest of this tutorial. This code is just to show how this assignment worked previously. To see a complete example, check out the HashiCorp documentation here .

With version 3.0, AzureRM has multiple resources for applying policy definitions to different scopes.

  • azurerm_management_group_policy_assignment for assigning to management groups
  • azurerm_subscription_policy_assignment for assigning to subscriptions
  • azurerm_resource_group_policy_assignment for assigning to resource groups
  • azurerm_resource_policy_assignment for assigning to a single resource

In this example, assign the policy to the subscription scope using azurerm subscription policy assignment. Give the policy assignment a name followed by the subscription ID (replace zeroes with your actual subscription ID).

Reference the policy defined earlier in the configuration using the resource type ( azurerm_policy_definition ), the symbolic name ( sa-naming-convention ), and the ID output from the resource. There are additional arguments you can use for policy assignment; review the documentation here .

Remember that this policy has two parameters: namingPattern and effectAction . Since you defined these parameters with a default vault, there is no need to pass a value when assigning the policy to a scope. However, if a parameter does not have a default value or you don't want to use the default, you set parameter values in this assignment resource declaration.

Use the parameters argument followed by the jsonencode() function, much like when you defined the metadata, parameters, and policy rule sections. This example sets the parameter effectAction to "Deny" instead of the default of "Audit."

Subscribe to 4sysops newsletter!

  • Use the az login command to log in to your Azure tenant.
  • If necessary, select the subscription where you want to deploy the resources using the az account set command. This example sets the context to a subscription named "Demo." az account set --subscription "Demo"
  • Use the terraform init command to initialize your Terraform working directory.
  • Use the terraform plan command to validate and see the planned resource deployment.
  • Once satisfied with the plan output, use the terraform apply command to deploy the configuration. When prompted, enter yes to authorize the deployment.

Searching in the Azure portal

Searching in the Azure portal

Searching the policy

Searching the policy

Viewing the policy definition

Viewing the policy definition

Testing the naming policy

Testing the naming policy

In this tutorial, you learned how to define an Azure Policy and assign the policy to a scope using Terraform. Terraform doesn't just have to be for virtual machines and storage accounts. Terraform can also control your governance strategy by codifying Azure Policy definitions and assignments. By defining the policies as code, you can quickly restore definitions and assignments if someone changes them outside Terraform.

avatar

IT Administration News

  • CrowdStrike sued by investors over massive global IT outage
  • Hands-on: Windows 11s new Recovery Tool that clean installs the OS using Windows Update
  • Microsoft veteran shares Windows NT, 3.1, 95 Blue Screen of Death (BSOD) origin story – Neowin
  • Introducing GitHub Models: A new generation of AI engineers building on GitHub – The GitHub Blog
  • Twilio kills off Authy for desktop, forcibly logs out all users

Read All IT Administration News

Join our IT community and read articles without ads!

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

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

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

Avatar

New in Docker Desktop 4.32: Compose File Viewer, integrated terminal, cloud backup, move data, and MSI installer

Avatar

Install Podman on Ubuntu, pull and run container images, and push to Docker Hub

Mercy Bassey

Install AWS CloudShell in a VPC

Avatar

Search and delete Copilot data in Microsoft 365

System resources widgets

What is Microsoft Dev Home?

Avatar

Docker Desktop 4.31: Air-Gapped Containers, Docker Build Cloud, GitHub Actions support, ARM support

Traefik with OpenTelemetry support

Traefik Proxy v3 review: WASM support, OpenTelemetry, and more

Avatar

Install Docker on Ubuntu 24.04

Starting Minikube with Kubernetes v1.30.0

Job management in Kubernetes 1.30: Understanding the new success/completion policies for indexed jobs

Signing in to AWS with Touch ID

Enable FIDO passkey authentication for IAM users in AWS

Avatar

OpenTofu 1.7: State encryption, provider-defined functions, loopable import blocks, and improved CLI experience

Avatar

Istio 1.22: Ambient mode, Gateway API, and Delta xDS for Kubernetes service mesh

Applying OpenTofu resources to AWS

Setting up EC2 instance access to an S3 bucket using IAM and OpenTofu

Calling the GPT 4o API via PowerShell

Use PowerShell to deploy and access GPT-4o in Azure OpenAI Service

Avatar

Microsoft Purview Audit Search Graph API: Retrieve audit logs from Microsoft 365 with PowerShell

View experimental features in Docker Desktop

Docker Desktop for Windows Subsystem for Linux 2 (WSL 2)

Flow of an external authentication with Entra ID. Courtesy: Microsoft

Configuring external authentication methods in Microsoft 365 with Microsoft Entra ID

Kyverno Logo

A Kubernetes policy engine: New features in Kyverno 1.12

Microsoft Graph and its interconnected components

Integrate Microsoft Graph activity logs for Microsoft 365 with Azure Monitor

Leave a reply click here to cancel the reply.

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

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

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

Receive new post notifications

Twitter

Subscribe to Newsletter

Follow 4sysops.

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

Log in with your credentials

or      Create an account

Forgot your details?

Create account.

Manage Azure Policy with Terraform

I am going to reverse the order I would normally explain a concept, in this blog we will look at the call to the module first and then dive into each of the components.

The Module Call

The initiative definition.

Let's step into the initiative definition next.

There are four top-level keys that we have to set:

  • name — unique name for the initiative.
  • display_name — the name displayed with the initiative.
  • description — a description of what the policy is for and does.
  • policies — objects containing the value definitions of BuiltIn and Custom policies.

With these properties we will be able to pass in all of the relevant values into our policies for a range of environments, further, we can also set a default if we don't have values specific to an environment. Let's take a look at the two types of policy definitions.

First, let's take a look at the policy properties:

  • type — the type of policy that we are referencing; Custom or BuiltIn .
  • file — if the policy is Custom we require the name of the file to import. This will be forced into the ${path.root}/policies/ directory by the Terraform code.
  • id — the GUID id of an existing Azure policy provided by Microsoft, this is required when type is set to BuiltIn .
  • default — the default parameter and effect values.
  • dev/uat/prd/... — the key is the environment and the keys must be the same as default , this provides an optional setting of policy parameters by the environment.

Inside the default or environment block we have the following few properties:

  • effect — the effect this policy will have, deny as an example. This property cannot be set on BuiltIn policies.

Custom Policy Definition

The key at the beginning AllowedLocations is how we will reference our policy and retrieve its components in the Terraform code. By allowing us to pass in the file to a json file it allows us to easily create custom policies alongside the fantastic baseline policies that Microsoft already give us. In the above example if we were running our Terraform code in the uat environment our code would use the properties we have defined in default as there are no environment-specific overrides. Allowing this makes our Terraform more powerful as perhaps when we start with Azure policy we don't necessarily understand what each environment requires, or they all explicitly require the same types of enforcement.

Built-in Policy Definition

The above is how we would set our parameters for a Built-in Azure policy. Remembering that we cannot set the effect of this policy as that is set by Microsoft, if you did need to alter that effect then it would be best to use a custom policy.

The Custom Policy Definition

We won't go into the mud on how to write an Azure Policy Definition if you're interested in that then check out the Azure Policy definition structure article by Microsoft.

The main point here is that you have a json definition of the Azure Policy either that you have written from scratch or perhaps you're pulling from the Azure portal so that you're now able to change the effect. As you can see on the high-lighted line below the value for the effect key is using string interpolation which will be set by templatefile in our Terraform code later. This is how we are going to be setting the effect on a per-environment basis.

Now we get into the fun stuff 🎉! Whilst going through the module I am going to split it up into some sub-sections to make it easier for us to talk through. Further, the module supports three scopes; Management Group ( mg ), Subscription ( sub ), and Resource Group ( rg ) I will just be referencing the resource group code below as it is almost identical to the other scopes.

The Module Interface .css-1a60e3e{transition-property:var(--chakra-transition-property-common);transition-duration:var(--chakra-transition-duration-fast);transition-timing-function:var(--chakra-transition-easing-ease-out);cursor:pointer;-webkit-text-decoration:none;text-decoration:none;outline:2px solid transparent;outline-offset:2px;color:inherit;font-weight:var(--chakra-fontWeights-normal);opacity:0;margin-left:var(--chakra-space-2);}.css-1a60e3e:hover,.css-1a60e3e[data-hover]{opacity:1;color:var(--chakra-colors-accent-500);-webkit-text-decoration:underline;text-decoration:underline;}.css-1a60e3e:focus,.css-1a60e3e[data-focus]{opacity:1;color:var(--chakra-colors-accent-500);-webkit-text-decoration:underline;text-decoration:underline;} #

If you've worked with me or read my articles before you would know that I treat the variables.tf as our documented API interface, think of it like an OpenAPI definition for a REST API. We will go through each variable one by one.

Our first variable is initiative_definition this is where we pass the full path to our definition yaml file like we discussed in The Initiative Definition .

Secondly, we need to pass in an environment , this must be in whatever format you've used in the initiative definition otherwise our Terraform code won't be able to retrieve the properties for an environment.

The most important input variable for us is the assignment variable, this is where we pass in a single or list of resource IDs we are going to be assigning the policy initiative. Allowing a list of assignments means that we can deal with assignments on a larger scale than a single resource. This is especially powerful when operating in an enterprise environment.

The name property of the assignments object we will use as part of our exemptions process, this ensures there is an easy and intentional lookup for us when we are trying to exempt a resource from a given initiative.

We also have some validation ensuring that the scope passed in is valid for our scenario.

When Azure Policy is concerned there is always going to be a requirement to be able to exempt some resources from having that policy applied/enforced on them. We manage that here through the use of the exemptions variable. This variable allows us to pass in a list of our exemptions object. We have the assignment_reference which as we mentioned above is a reference to name in the assignments object. This allows us to cleanly look up which assignment we are looking to exempt a given resource for.

In this variable, we need to validate that our exemption scope is valid, not only valid for Azure but for our given scenario. For instance, you can exempt a single resource from a policy but our module only supports down to the resource group is the most granular level. The second thing we are validating is that the category on the exemption is one of the two valid strings as expected by Microsoft.

Local Variables and Setup #

The first few pieces of setup that we are going to do is get some random_uuid 's setup that we can use for unique names of our policies, assignments and exemptions. Some properties in the azurerm the provider will auto-generate names for us, and others won't. In this instance, we are going to be dealing with the generation of the names.

Next, we need to decode our initiative_definition yaml into a Terraform object that we can use throughout our module. The policies local variable is a convenience variable for us so that we can quickly access the property. Also, if the way we access the policies object/key from our yaml file changes the code that consumes the policies doesn't need to know about that change.

Policy definitions #

We use an azurerm_policy_definition resource for a Custom policy and the azurerm_policy_definition data source for our BuiltIn policies. Doing so allows us to support both in our module.

When we are creating a Custom policy we have an object that is the filename of a policy json file before creating these policy instances we need to complete the templatefile on each policy. We will loop through our local.policies object and decodes each file to json once the templatefile action has been performed and we have applied the effect either via a default key from our initiative definition or an environment-specific one. This will only occur when the type property is Custom . Then we simply take the properties from our json and plug them into the resource. Some properties such as; metadata , policy_rule , and parameters require to have jsonencode on the object we are retrieving from the policy json as when we do our for_each those are converted into objects that Terraform can deal with.

For the data source, we simply need to loop through our local.policies object and filter to only use objects where the type property is BuiltIn . We do this by using a for expression within the for_each block. You can read more about that in my post Terraform For Expressions .

Policy Initiative #

Now that we have all of our policies in the state we require them its time to create our initiative and pass in the parameter values to each policy.

First off we will merge all our policies, both the resource and the data source. This will give us a single object to operate on. Using the new all_policies object we will get the parameter values, this will be environment specific if available otherwise it will return default . Having a pre-populated property for this allows for easy access within the azurerm_policy_set_definition resource.

Now we have two objects; all_policies and parameters these two combined are what allow us to set up all the policies within the initiative. Using a dynamic block -which you can read more about here - we will iterate over each policy in local.all_policies and assign the parameter_values from the local.parameters variable based on the key from our for_each . This is easily possible as when we created the local.parameters variable we did so by doing a for_each over the local.all_policies variable, this means that both the dynamic block and our parameters variable will use the same value as a key.

Policy Assignment #

The actual policy assignment portion of the module is most likely the simplest part. In this, we simply for through the var.assignment.assignments list and return a map where the key is the name property and the value is the id property of our assignments object.

We do however do a check on scope to ensure that we are operating on the right scope for the right resource type. In this instance the resource group. If we were doing this on azurerm_management_group_policy_assignment the resource then our check would be if var.assignment.scope == "mg" . You can see that in the full module code the terraform-azurerm-policy-initiative repository on my GitHub.

Policy Exemption #

The exemptions are where things get a little funkier, as we need to be able to match zero or more exemptions to the correct assignment.

Our first problem to solve is how we reference the correct Terraform resource block given each assignment type ( mg , sub , rg ) has its own Terraform resource. We do this by using the local variables' ability to reference a resource rather than a string. The try is important as Terraform will try to evaluate each of these even if they're not called which would be fine except that they will never all exist at the same time given assignment can only be done on a single scope.

With the above we can now access the right Terraform resource with the following:

To be honest, the ability to reference other resources with locals is INCREDIBLY powerful!!

Now that we can get the right policy assignment it's time to deal with the exemption side of things. For this, we are going to for through our assignments and our exemptions variables to create a new data structure containing all the relevant pieces of data. The assignment_id key will only ever return one value due to the use of the one function, this behavior is 💯 what we want if there was an instance where there were more than one assignment ID for a specific assignment_reference we would know someone has made a mistake. At this stage, we also validate that the assignment.scope is correct.

You can read more about the for expressions in my Terraform For Expressions post.

The name property is something that we construct out of the random_uuid for the exemptions as well as the last component of the resource ID. In the instance of a resource group that will be the name of the resource group. We also use this same logic to generate the id or key field on our for_each it is because of this that the resource we are referencing must exist before this code is run. If the resource does not exist then Terraform will error out saying that it is unable to determine the value of something that is part of the ID of a map. Whilst this behavior is not ideal I also don't think that it is that bad. The reason being is that should we ever try and exempt a policy on a resource that doesn't exist Terraform/Azure is going to wig out, therefore the behavior is more or less the same just at a different place in the run.

Closing Out #

Today we have gone through a module I've created to deal with creating Azure Policy initiatives. We went through the initiative definition, the custom policy definition and the module itself. By using this module we are now easily able to deploy and manage Azure Policies and exemptions on our cloud platform at scale. We also ensured that we can have the right level of flexibility when it comes to setting the parameter values and the effects on an Azure Policy.

For me, this was not what I would call an easy module to write, as it required me to think about how I could get the most amount of configuration information into the module without making it overly complex to consume. However, going back to My Development Workflow helped me through the process. This module had four iterations before it got to what we have here today.

You can find this module at BrendanThompson/terraform-azurerm-policy-initiative

I would love to hear from you on if you think this module is useful and what you have done to manage something as complex as Azure Policy in your cloud environment!

John Folberth

Resources and posts for those figuring out DevOps in Azure

  • Professional

Dynamically Adding Terraform Policy Assignments…Reusing Infrastructure as Code!

Azure Policy with Terraform

This a post related to my post on “ Creating Azure Policy via Terraform ” and throws in how to deal reusing an Azure Policy Definition for multiple assignments. In this case we may want to pass in a list of required tags and what the intended effect for each might be.

There are numerous ways to do this. For the purposes of this blog, we will focus on handling this information at the policy definition ASSIGNMENT level as opposed to encoded in the definition or within an initiative. (Full disclosure I wanted to do this in an initiative but ran into Terraform limitations, if you have overcome this feel free to reach out!)

Taking a step back doing this via the assignment level means we can define the Azure Policy as Terraform just once and pass in a variable list or object containing the details. This becomes useful as we can create one policy definition for all the required tags and at assignment pass in the necessary information.

For this example, we will define our variable as an object passing in the tag name(s) and our effect. This allows for greater granularity of control when applying policies. The Terraform might look like:

By constructing the Terraform variable file this way we will be required a tag of delete-by to create; however, the tage of department might be optional for now until we get up to compliance.

The associated policy rule may look like:

Then the magic of our assignment may look like:

Note that the display_name , description , and name will read each instance of the loop in. This is required since we can’t have two assignments of the same name.

That’s it! Now we can specify different required tags potentially in different variable files so that our tagging requirements in dev might be different then a production environment.

Leave a Reply 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.

  • 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 define and assign an Azure Policy on a Management Group Scope using Terraform?

I want to assign one of the built-in policies of Azure to a management group using Terraform. The problem I'm facing is, while assigning policies with Terraform can be fairly easily done by setting the scope properly to the subscription id or resource group or specific resource that the policy is to be applied upon, changing it to management group gives rise to an error. This, I believe, is due to the fact that the policy definition location needs to be the management group is well, so that we may make the scope for azurerm_policy_assignment equal to the desired management group. Could I please get some help regarding this, so as to how to define the policy, the definition location being that of the management group in Terraform ? For instance, I've tried setting scope = the management group id, in the resource azurerm_policy_definition block preceeding the policy assignment block, but I get "scope" to be an unexpected keyword there. Neither does setting the "location" work.

I'll also share my current workaround.

As a result of the problem I'm facing, what I'm currently doing is duplicating the definition of the policy from the portal, changing the "definition location" to be equal to the management group id there, and then passing the new policy definition id and scope to be the management group in my subsequent Terraform code, which now works now that the policy is defined in the concerned location of the management group.

But I want to do away with this manual intervention and intend to complete it using Terraform script solely. Being relatively new to the field, is there a way I could assign the policy to a particular management group in Terraform, having duly defined it first in the same scope so as to not lead to any error ?

Alternatively posed, my question could also be interpreted how to assign a Azure policy to a specific management group scope using Terraform script only ( one may assume, management groups to be created using Terraform too, although that part is taken care of ).

  • azure-policy
  • azure-management-groups

Swarnabja Bhaumik's user avatar

3 Answers 3

To assign a Built-In policy, I would suggest referencing the desired Policy Definition as a data source . This way, you do not need to declare/create a new Policy Definition in your Terraform code. (Although alternatively, you could just place the Definition ID for the Built-In Policy as the value for policy_definition_id in the azurerm_policy_assignment resource block).

Here is an example of referencing a Built-In Policy Definition as a Data source in Terraform.

Below is an example of what your Terraform would look like to take a Built-In Policy Definition from the Portal and assign to a management group.

noahb's user avatar

  • Thank you so much...@noahb, it works perfectly...I just had a question. However, referencing the policy definition as a data source does not allow me to write the policy rules and stuff inside the definition block...how would it be applicable without those ? Is there a way to incorporate it ? –  Swarnabja Bhaumik Commented Jan 25, 2021 at 11:12

To define that a policy should be located in a management group, you can use the management_group_id argument in the azurerm_policy_definition as follows:

Bertware's user avatar

Your Answer

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

Sign up or log in

Post as a guest.

Required, but never shown

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

Not the answer you're looking for? Browse other questions tagged azure scope terraform azure-policy azure-management-groups or ask your own question .

  • Featured on Meta
  • Announcing a change to the data-dump process
  • We've made changes to our Terms of Service & Privacy Policy - July 2024

Hot Network Questions

  • Compact rotatable connection that supports pull forces?
  • How does lycanthropy interact with the clone spell?
  • Why are the Founders in Star Trek: Deep Space Nine considered so powerful?
  • Can multi-threading improve performance of an IO-bound process?
  • Automata reaching the same state when reading the same word long enough
  • How does Wild Shape interact with the clone spell?
  • Jurisdiction: Can police officers open mail addressed to a stranger?
  • Does GDPR's "Legitimate Interest" allow spam?
  • How do Trinitarians distinguish whether the Hebrew bible is referring to the "being" or "person[s]" of God in the verses that declare oneness?
  • What might be causing ls to ignore LS_COLORS for setgid (sg, g+s) directories?
  • Five numbers with median and mean
  • Can an exponentially growing population perform eugenics and selective breeding at short time scales?
  • Washed my passport by mistake, can that cause a problem?
  • Why do repeating 8's show up more often in these decimals of square roots?
  • Thomson's lamp: a useless paradox?
  • Can I replace this resistor (in USB adapter that plugs to mains) with this other resistor?
  • Is it correct to say: "To solve an addiction"?
  • Possibly manipulated recommendation letter - inform alleged author?
  • Set of numbers with median and mean
  • How to use the すぎ suffix to mean "too much"?
  • How should I acknowledge a reviewer who left a negative review?
  • Foundations and contradictions of Scholze's work: the category of presentable infinity categories contains itself
  • Does spring stop applying force as soon as we cut it?
  • What is/was float option n? Unknown float option `n'

policy assignment terraform

Azure Policy Policy Assignment

This page shows how to write Terraform and Azure Resource Manager for Policy Policy Assignment and write them securely.

Review your .tf file for Azure best practices

Shisho Cloud, our free checker to make sure your Terraform configuration follows best practices, is available (beta).

azurerm_management_group_policy_assignment (Terraform)

The Policy Assignment in Policy can be configured in Terraform with the resource name azurerm_management_group_policy_assignment . The following sections describe 10 examples of how to use the resource and its parameters.

  • Example Usage from GitHub

Review your Terraform file for Azure best practices

The following arguments are supported:

management_group_id - (Required) The ID of the Management Group. Changing this forces a new Policy Assignment to be created.

name - (Required) The name which should be used for this Policy Assignment. Changing this forces a new Policy Assignment to be created.

policy_definition_id - (Required) The ID of the Policy Definition or Policy Definition Set. Changing this forces a new Policy Assignment to be created.

description - (Optional) A description which should be used for this Policy Assignment.

display_name - (Optional) The Display Name for this Policy Assignment.

enforce - (Optional) Specifies if this Policy should be enforced or not?

identity - (Optional) An identity block as defined below.

- > Note: The location field must also be specified when identity is specified.

location - (Optional) The Azure Region where the Policy Assignment should exist. Changing this forces a new Policy Assignment to be created.

metadata - (Optional) A JSON mapping of any Metadata for this Policy.

not_scopes - (Optional) Specifies a list of Resource Scopes (for example a Subscription, or a Resource Group) within this Management Group which are excluded from this Policy.

parameters - (Optional) A JSON mapping of any Parameters for this Policy. Changing this forces a new Management Group Policy Assignment to be created.

A identity block supports the following:

  • type - (Optional) The Type of Managed Identity which should be added to this Policy Definition. The only possible value is SystemAssigned .

In addition to the Arguments listed above - the following Attributes are exported:

  • id - The ID of the Management Group Policy Assignment.

The identity block exports the following:

principal_id - The Principal ID of the Policy Assignment for this Management Group.

tenant_id - The Tenant ID of the Policy Assignment for this Management Group.

>> from Terraform Registry

  • Explanation in Terraform Registry
Manages a Policy Assignment to a Management Group.

Microsoft.Management/managementGroups (Azure Resource Manager)

The managementGroups in Microsoft.Management can be configured in Azure Resource Manager with the resource name Microsoft.Management/managementGroups . The following sections describe how to use the resource and its parameters.

The Other Related Azure Policy Resources

Azure Policy Assignment

Azure Policy Configuration Policy Assignment

Azure Policy Definition

Azure Policy Remediation

Azure Policy Resource Group Policy Assignment

Azure Policy Set Definition

Azure Policy Subscription Policy Assignment

Azure Policy Virtual Machine Configuration Assignment

  • Frequently asked questions

What is Azure Policy Policy Assignment?

Azure Policy Policy Assignment is a resource for Policy of Microsoft Azure. Settings can be wrote in Terraform.

Where can I find the example code for the Azure Policy Policy Assignment?

For Terraform, the simonbrady/azure-nzism , petemessina/policy-as-code and timwebster9/azure-policy source code examples are useful. See the Terraform Example section for further details.

For Azure Resource Manager, the git-yrh-bloom/arm-bloom-es , geekyninja101/lz-poc-main and ZJQZ/cmp-core-public source code examples are useful. See the Azure Resource Manager Example section for further details.

Automate config file reviews on your commits

Fix issues in your infrastructure as code with auto-generated patches.

Table of Contents

policy assignment terraform

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

Support for specifying built-in policy definition version when creating azurerm_*_policy_assignment #26855

@eehret

eehret commented Jul 29, 2024 • edited Loading

to the original issue to help the community and maintainers prioritize this request to help.

Apologies if this exists already - I did look for it and came up empty.

Currently in preview there's support for indicating specific versions of built-in policies, both when viewing information about the policy definitions as well as when managing policy assignments at different scopes.

I am not currently seeing a way to do this in Terraform provider though; there doesn't seem to be a version attribute that can be specified in which I could pin the assignment to a specific version, or to opt in/out of the automatic minor version updates.

azurerm_*_policy_assignment, data.policy_definition_built_in

https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs/resources/management_group_policy_assignment And following the syntax shown here: resource "azurerm_management_group_policy_assignment" "example" { name = "example-policy" management_group_id = azurerm_management_group.example.id policy_definition_id = azurerm_policy_definition.example.id policy_definition_version = "2.*.*" # Optional }

Note that the field would only be valid for built-in policy and initiative definitions.

A similar change could be done for resource group, and resource scoped assignments and I suppose it might be considered for the data source as well.

@mybayern1974

No branches or pull requests

@eehret

IMAGES

  1. Azure Policy as Code with Terraform Part 1

    policy assignment terraform

  2. Announcing Policy Sets in Terraform Enterprise

    policy assignment terraform

  3. Announcing Policy Sets in Terraform Enterprise

    policy assignment terraform

  4. Enforce a Policy

    policy assignment terraform

  5. Open Policy Agent for AWS and Terraform

    policy assignment terraform

  6. Azure Policy as Code with Terraform Part 2

    policy assignment terraform

VIDEO

  1. Datbricks Unity Catalog Metastore Assignment to Spokes

  2. Automation

  3. Fact/Value/Policy Assignment- Rebuttal

  4. Fact/Value/Policy Assignment- Advocate’s Case

  5. Fact/Value/Policy Assignment- Opposition Cross Examination

  6. AIOU Assignment Decision

COMMENTS

  1. Quickstart: New policy assignment with Terraform

    The Terraform resources for Azure Policy use the Azure Provider. Create a new folder named policy-assignment and change directories into it. Create main.tf with the following code: Note. To create a Policy Assignment at a Management Group use the azurerm_management_group_policy_assignment resource, for a Resource Group use the azurerm_resource ...

  2. gettek/terraform-azurerm-policy-as-code

    Should be Defined as high up in the hierarchy as possible.; Should be Assigned as low down in the hierarchy as possible.; Multiple scopes can be exempt from policy inheritance by specifying assignment_not_scopes or using the exemption module.; Policy overrides RBAC so even resource owners and contributors fall under compliance enforcements assigned at a higher scope (unless the policy is ...

  3. Implementing Azure Policy using Terraform

    Second section of Terraform code would create a policy assignment using the terraform module. We have setup the identity section in assignment so as to setup managed identity through terraform. Location Parameter is needed for the managed identity. Third section would be creating a remediation task on the policy assignment scope.

  4. [Examples] Create Custom Policies Policy Sets and Assignments

    In your /lib directory create a policy_set_definitions subdirectory.. NOTE: Creating a policy_set_definitions subdirectory is a recommendation only. If you prefer not to create one or to call it something else, the custom policies will still work. In the policy_set_definitions subdirectory, create a policy_set_definition_enforce_mandatory_tags.json file. This file will contain the Policy Set ...

  5. Manage Azure Policy using Terraform

    Terraform is a popular Infrastructure as Code solution. Did you know that you can manage other Azure resources, such as policy definitions and assignments with Terraform? In this tutorial, you will learn how to use Terraform to manage Azure Policy by creating a policy definition for a storage account naming standard. You will then assign the policy to a subscription and test the policy's ...

  6. Manage Azure Policy with Terraform

    Brendan Thompson • 17 November 2022 • 17 min read. Terraform Azure Azure Policy. Today we are going to talk about managing Azure Policy using Terraform. Azure Policy has a few components to it; Policy Definition, Policy Definition Set (also known as an Initiative), policy assignment, policy exemption and policy remediation.

  7. Dynamically Adding Terraform Policy Assignments...Reusing

    Dynamically Adding Terraform Policy Assignments…Reusing Infrastructure as Code! May 13, 2021 by John Folberth. This a post related to my post on " Creating Azure Policy via Terraform " and throws in how to deal reusing an Azure Policy Definition for multiple assignments. In this case we may want to pass in a list of required tags and what ...

  8. Azure Policy Assignment

    What is Azure Policy Assignment? Azure Policy Assignment is a resource for Policy of Microsoft Azure. Settings can be wrote in Terraform. Where can I find the example code for the Azure Policy Assignment? For Terraform, the floriandorau/opa-aks source code example is useful. See the Terraform Example section for further details.

  9. Azure Policy Assignment

    Explanation in Terraform Registry. Configures the specified Policy Definition at the specified Scope. Also, Policy Set Definitions are supported. !> Note: The azurerm_policy_assignment resource has been deprecated in favour of the azurerm_management_group_policy_assignment, azurerm_resource_policy_assignment, azurerm_resource_group_policy_assignment and azurerm_subscription_policy_assignment ...

  10. How to define and assign an Azure Policy on a Management Group Scope

    This way, you do not need to declare/create a new Policy Definition in your Terraform code. (Although alternatively, you could just place the Definition ID for the Built-In Policy as the value for policy_definition_id in the azurerm_policy_assignment resource block).

  11. Azure Policy Subscription Policy Assignment

    Azure Policy Subscription Policy Assignment is a resource for Policy of Microsoft Azure. Settings can be wrote in Terraform. Where can I find the example code for the Azure Policy Subscription Policy Assignment? For Terraform, the globalbao/azure-policy-as-code, quintindk/azurebootcamp21 and acend/terraform-training-env source code examples are ...

  12. Azure Policy Policy Assignment

    The Policy Assignment in Policy can be configured in Terraform with the resource name azurerm_management_group_policy_assignment. The following sections describe 10 examples of how to use the resource and its parameters.

  13. Support for specifying built-in policy definition version when ...

    I am not currently seeing a way to do this in Terraform azurerm provider though; ... New or Affected Resource(s)/Data Source(s) azurerm_*_policy_assignment, data.policy_definition_built_in. Potential Terraform Configuration. Slightly modifying the example here: https: ...