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

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!

azure management group 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

azure management group policy assignment terraform

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

  • OpenSSH bug leaves RHEL 9 and the RHELatives vulnerable The Register
  • The new Outlook for Windows will be generally available August 1 for commercial users – Neowin
  • Microsoft and Apple ditch OpenAI board seats amid regulatory scrutiny – The Verge
  • Build enterprise-grade applications with natural language using AWS App Studio (preview) | AWS News Blog
  • Google: We’re still working to defeat Microsoft cloud policy The Register

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.

Finding the eDiscovery search ID using Microsoft Graph Explorer

Search and delete Copilot data in Microsoft 365

Avatar

What is Microsoft Dev Home?

Avatar

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

Avatar

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

Mercy Bassey

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

Avatar

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

View the Dockerfile generated by Docker Init

Containerize any app with Docker Init

Representation of a multitenant organization

The new Microsoft 365 multitenant organization feature

Running an OpenTofu init

Create an S3 bucket in AWS with OpenTofu

Creating a Role with Lens Desktop

Lens 2024: Redesigned GUI for Kubernetes

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.

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.

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

[Examples] Create Custom Policies Policy Sets and Assignments

This page describes how to deploy your Azure landing zone with custom policy definitions and policy set (Initiative) definitions.

In this example you will use three custom policies and a custom policy set definition. The custom policies will be named Enforce-RG-Tags , Enforce-Resource-Tags and Deny-NIC-NSG . You will then create a custom policy set definition (Initiative) named Enforce-Mandatory-Tags that will include the Enforce-RG-Tags and Enforce-Resource-Tags custom policies.

You will update the built-in configuration by following these steps:

  • Create the custom policy definition file for Enforce-RG-Tags
  • Create the custom policy definition file for Enforce-Resource-Tags
  • Create the custom policy definition file for Deny-NIC-NSG
  • Create the custom policy set definition file for Enforce-Mandatory-Tags
  • Make the custom policy definitions available for use in Azure by extending the built-in archetype for es_root
  • Create the policy assignment files for Enforce-RG-Tags , Enforce-Resource-Tags , Deny-NIC-NSG and Enforce-Mandatory-Tags
  • Assign the custom policy set definition for Enforce-Mandatory-Tags at the es_root Management Group by extending the built-in archetype for es_root
  • Assign the custom policy definition for Deny-NIC-NSG at the Landing Zones Management Group by extending the built-in archetype for es_landing_zones
IMPORTANT: To allow the declaration of custom or expanded templates, you must create a custom library folder within the root module and include the path to this folder using the library_path variable within the module configuration. In our example, the directory is /lib .

In order to create and assign custom policies, we need to create both a definition file and an assignment file for each custom policy or custom policy set definition. In this example we will do this by using the below files:

lib/policy_definitions/policy_definition_es_enforce_rg_tags.json

Lib/policy_definitions/policy_definition_es_enforce_resource_tags.json, lib/policy_definitions/policy_definition_es_deny_nic_nsg.json, lib/policy_set_definitions/policy_set_definition_enforce_mandatory_tagging.json, lib/policy_assignments/policy_assignment_es_enforce_rg_tags.json, lib/policy_assignments/policy_assignment_es_enforce_resource_tags.json, lib/policy_assignments/policy_assignment_es_deny_nic_nsg.json, lib/policy_assignments/policy_assignment_es_enforce_mandatory_tagging.json.

NOTE: This module provides the ability to define custom template variables used when reading in template files from the built-in and custom library_path. For more info click here .

Create Custom Policy Definition

In your /lib directory create a policy_definitions subdirectory if you don't already have one. You can learn more about archetypes and custom libraries in this article .

NOTE: Creating a policy_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_definitions subdirectory, create a policy_definition_es_policy_enforce_rg_tags.json file. This file will contain the policy definition for Enforce-RG-Tags . Copy the below code in to the file and save it.

Now create a policy_definition_es_policy_enforce_resource_tags.json file. This file will contain the policy definition for Enforce-Resource-Tags . Copy the below code in to the file and save it.

Next create a policy_definition_es_policy_deny_nsg_nic.json file. This file will contain the policy definition for our last custom policy - Deny-NSG-NIC . Copy the below code in to the file and save it.

Create Custom Policy Set Definition

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 Definition for Enforce-Mandatory-Tags . The policy set will contain the Enforce-RG-Tags and Enforce-Resource-Tags custom policies that you previously created. Copy the below code in to the file and save it.

Create Custom Policy Assignment Files

In order to assign your custom policies or policy sets, you need to create policy assignment files. The first step is to create a policy_assignments subdirectory within /lib .

NOTE: Creating a policy_assignments subdirectory within \lib is a recommendation only. If you prefer not to create one or to call it something else, the custom policies will still work.

You will then need to create a file named policy_assignment_es_enforce_rg_tags.json within the policy_assignments directory. Copy the below code in to the file and save it.

Now create a file named policy_assignment_es_enforce_resource_tags.json within the policy_assignments directory. Copy the below code in to the file and save it.

Next create a file named policy_assignment_es_deny_nic_nsg.json within the policy_assignments directory. Copy the below code in to the file and save it.

Finally, create a file named policy_assignment_es_enforce_mandatory_tagging.json . Copy the below code in to the file and save it.

Make the Custom Policy Definitions and Policy Set Definition available for use

You now need to save your custom policy and policy set definitions at the es_root Management Group to ensure they can be used at that scope or any scope beneath. To do that, we need to extend the built-in archetype for es_root .

NOTE: Extending built-in archetypes is explained further in this article .

If you don't already have an archetype_extension_es_root.tmpl.json file within your custom /lib directory, create one and copy the below code in to the file. This code saves the custom policy definition and policy set definitions but we still haven't assigned them anywhere yet.

Assign the Enforce-Mandatory-Tags Custom Policy Set at the es_root Management Group

You now need to assign the Enforce-Mandatory-Tags policy set and in this example, we will assign it at es_root . To do this, update your existing archetype_extension_es_root.tmpl.json file with the below code and save it.

You should now kick-off your Terraform workflow (init, plan, apply) to apply the new configuration. This can be done either locally or through a pipeline. When your workflow has finished, the Enforce-Mandatory-Tags policy set will be assigned at es_root .

Assign the Deny-NIC-NSG Custom Policy Definition at the Landing Zones Management Group

As you have already saved the Deny-NIC-NSG Custom Policy Set at es_root , this gives us the ability to assign it at the es_root scope or at any scope beneath it. In this example, we will assign it at the Landing Zones Management Group. To do this, either update your existing archetype_extension_es_landing_zones.tmpl.json file or create one and copy the below code in to it and save.

You should now kick-off your Terraform workflow (init, plan, apply) again to apply the updated configuration. This can be done either locally or through a pipeline. When your workflow has finished, the Deny-NIC-NSG Policy Definition will be assigned at the Landing Zones Management Group.

You have now successfully created and assigned both a Custom Policy Definition and a Custom Policy Set Definition within your Azure environment. You can re-use the steps in this article for any Custom Policies of your own that you may wish to use.

This wiki is being actively developed

If you discover any documentation bugs or would like to request new content, please raise them as an issue or feel free to contribute to the wiki via a pull request . The wiki docs are located in the repository in the docs/wiki/ folder.

Azure landing zones Terraform module

  • Getting started
  • Module outputs
  • Module permissions
  • Module variables
  • Module releases
  • Module upgrade guidance
  • Provider configuration
  • Archetype definitions
  • Core resources
  • Management resources
  • Connectivity resources
  • Identity resources
  • Video guides
  • Deploy default configuration
  • Deploy demo landing zone archetypes
  • Deploy custom Landing Zone Archetypes
  • Deploy connectivity resources (Hub and Spoke)
  • Deploy connectivity resources (Virtual WAN)
  • Deploy identity resources
  • Deploy management resources
  • Assign a built-in policy
  • Create and assign custom RBAC roles
  • Set parameter values for Policy Assignments
  • Deploy connectivity resources with custom settings (Hub and Spoke)
  • Deploy connectivity resources with custom settings (Virtual WAN)
  • Deploy with Zero Trust network principles (Hub and Spoke)
  • Deploy identity resources with custom settings
  • Deploy management resources with custom settings
  • Expand built-in archetype definitions
  • Create custom policies, initiatives and assignments
  • Override module role assignments
  • Control policy enforcement mode
  • Policy assignments with user assigned managed identities
  • Deploy using module nesting
  • Deploy using multiple module declarations with orchestration
  • Deploy using multiple module declarations with remote state
  • Frequently Asked Questions
  • Troubleshooting
  • Raising an issue
  • Feature requests
  • Contributing to code
  • Contributing to documentation

Clone this wiki locally

  • 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 do you add a managed policy to a group in terraform?

I've got this so far:

But I'm not sure how to attach this to a group.

  • amazon-web-services

ydaetskcoR's user avatar

2 Answers 2

You can use either the aws_iam_group_policy_attachment resource or the aws_iam_policy_attachment resource to attach a policy to a group.

As mentioned in the aws_iam_policy_attachment resource docs this resource creates an exclusive attachment of that policy to specified users, groups and roles and isn't normally what you want so I'd recommend the aws_iam_group_policy_attachment resource.

This might look something like this:

Note that you don't actually need the aws_iam_policy data source here as you are already building the ARN to pass into the data source and that's all that's needed by the aws_iam_group_policy_attachment resource.

  • Welcome to StackOverflow. To show that an answer solved your problem we don't normally comment on the answer to say thank you but instead accept the answer instead by ticking the green checkmark to the side of the answer. This shows other people who have the same problem as you that it was a helpful answer. If at any point another answer comes along that solves your original question in a better way then you can always move the acceptance to that new answer. –  ydaetskcoR Commented Jan 25, 2019 at 10:16

You add it later down in the file.

so something like

Mostafa Hussein's user avatar

  • 1 This isn't a valid use of the aws_iam_policy resource. This resource creates the IAM policy and doesn't handle attaching to a group. It's also not what you want when trying to use a service linked role. Also the resource doesn't support the arn or group parameters. –  ydaetskcoR Commented Jan 25, 2019 at 9:03

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 amazon-web-services terraform amazon-iam or ask your own question .

  • Featured on Meta
  • Upcoming initiatives on Stack Overflow and across the Stack Exchange network...
  • Announcing a change to the data-dump process
  • What makes a homepage useful for logged-in users

Hot Network Questions

  • Which distribution should I choose when my interest is the the interaction term (the poisson or negative binomial)?
  • Had there ever been a plane crash caused by flying too high and exploding?
  • Is it customary to hold off recognition of a state that seceded from another country through a referendum?
  • What's the easiest way to prove the Riemann Zeta function has any zeros at all on the critical line?
  • How do satellite trackers work when showing a "satellite"?
  • What is this font called and how to study it
  • Need help deciphering word written in Fraktur
  • Why call for Biden to step down now?
  • ミラさん が すんで いた うち を かいました。Who bought the house? Me or Mira-san?
  • Olive tree suckers but no top growth at all
  • A redesign of a bulky 12 kV source
  • Weighing out Cinestill dry C-41 materials
  • Can I disable the alpha channel in the UV editor?
  • "commit" a crime
  • Do liquid items stay separate in a Bag of Holding?
  • What does "Nor our strong sorrow, upon the foot of motion" mean?
  • How do I maintain Bezier circle resolution when selecting fill mode "none" for processing with Geometry Nodes?
  • Very old horror short story about a dead man waking up
  • Are hot air balloons regulated by ATC or can they fly without reporting to ATC?
  • GUI Interface for a command line program in C# Windows Forms
  • Can a bad paper title hurt you? Can a good one help you?
  • Why do the Fourier components of a piano note shift away from the harmonic series?
  • Can Curve25519 shared secret be safely truncated to half its size?
  • Does surviving an assassination attempt increase your chance of getting elected?

azure management group policy assignment terraform

IMAGES

  1. GitHub

    azure management group policy assignment terraform

  2. Creating Azure Management Groups using Terraform

    azure management group policy assignment terraform

  3. How to assign Azure Policies using Terraform

    azure management group policy assignment terraform

  4. Azure Policy as Code with Terraform Part 2

    azure management group policy assignment terraform

  5. Creating Azure Resource Groups Using Terraform And Azure Key Vault

    azure management group policy assignment terraform

  6. Implementing Azure Policy using Terraform

    azure management group policy assignment terraform

VIDEO

  1. You really can manage ALL Microsoft Azure services and features with Terraform

  2. Manage Azure Subscription and Governance using Azure Policy

  3. Start to customize the Azure landing zones Terraform module

  4. Azure Governance: Understanding Azure Management Group

  5. Q 073 AZ 400 DevOps Real Exam Question and answer, Dumps CertStudyPro

  6. Q 064 AZ 400 DevOps Real Exam Question and answer, Dumps CertStudyPro

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. How to define and assign an Azure Policy on a Management Group Scope

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

  3. andrewCluey/terraform-azurerm-management-group-policy-assignment

    terraform-azurerm-management-group-policy-assignment Module to assign Azure policies to Management groups based on a predefined Management group 'Type'. This module is intended to be used for assigning Azure Policies to Management Groups only.

  4. Manage Azure Policy with Terraform

    Manage Azure Policy using Terraform with the terraform-azurerm-policy-initiative module. Using this module allows you excellent flexibility and scalability in your Azure Policy deployments. ... If we were doing this on azurerm_management_group_policy_assignment the resource then our check would be if var.assignment.scope == "mg".

  5. Azure Policy as Code with Terraform

    There's a maximum count for each object type for Azure Policy. For definitions, an entry of Scope means the management group or subscription. For assignments and exemptions, an entry of Scope means the management group, subscription, resource group, or individual resource:

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

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

  8. Using Terraform to configure Azure Policy Parameters

    There are three TF resources for assignment based on scope; azurerm_management_group_policy_assignment, azurerm_resource_group_policy_assignment and azurerm_subscription_policy_assignment. Each ...

  9. Manage Azure Policy using 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 effectiveness. ... azurerm_management_group_policy_assignment for assigning to management groups;

  10. Azure Policy + Terraform = Policy-As-Code

    Policy definition comes in a fixed structure, that define the rules, whereas Policy assignment is a policy definition that has been assigned within a specific scope, for instance, Azure Management ...

  11. [Examples] Set parameter values for Policy Assignments · Azure

    Please refer to the Microsoft documentation for setting a value for parameters within a Policy Assignment template.. This approach can be used when adding new custom Policy Assignments to a custom lib folder, as specified by the library_path input variable.. NOTE: Whilst possible, we don't recommend using this approach if you want to set different values for custom Policy Assignments provided ...

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

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

    In order to assign your custom policies or policy sets, you need to create policy assignment files. The first step is to create a policy_assignments subdirectory within /lib. NOTE: Creating a policy_assignments subdirectory within \lib is a recommendation only. If you prefer not to create one or to call it something else, the custom policies ...

  14. Azure Policy Management via Terraform

    azurerm_policy_assignment: This resource assigns the policy definition to a specific scope — here it's assigned to a resource group denoted by azurerm_resource_group.example.id, which should ...

  15. How do you add a managed policy to a group in terraform?

    6. You can use either the aws_iam_group_policy_attachment resource or the aws_iam_policy_attachment resource to attach a policy to a group. As mentioned in the aws_iam_policy_attachment resource docs this resource creates an exclusive attachment of that policy to specified users, groups and roles and isn't normally what you want so I'd ...