This browser is no longer supported.

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

Azure Policy assignment structure

  • 9 contributors

Policy assignments are used by Azure Policy to define which resources are assigned which policies or initiatives. The policy assignment can determine the values of parameters for that group of resources at assignment time, making it possible to reuse policy definitions that address the same resource properties with different needs for compliance.

For more information on Azure Policy scope, see Understand scope in Azure Policy .

You use JavaScript Object Notation (JSON) to create a policy assignment. The policy assignment contains elements for:

  • display name
  • description
  • resource selectors
  • enforcement mode
  • excluded scopes
  • policy definition
  • non-compliance messages

For example, the following JSON shows a policy assignment in DoNotEnforce mode with dynamic parameters:

All Azure Policy samples are at Azure Policy samples .

Display name and description

You use displayName and description to identify the policy assignment and provide context for its use with the specific set of resources. displayName has a maximum length of 128 characters and description a maximum length of 512 characters.

The optional metadata property stores information about the policy assignment. Customers can define any properties and values useful to their organization in metadata . However, there are some common properties used by Azure Policy. Each metadata property has a limit of 1,024 characters.

Common metadata properties

assignedBy (string): The friendly name of the security principal that created the assignment.

createdBy (string): The GUID of the security principal that created the assignment.

createdOn (string): The Universal ISO 8601 DateTime format of the assignment creation time.

parameterScopes (object): A collection of key-value pairs where the key matches a strongType configured parameter name and the value defines the resource scope used in Portal to provide the list of available resources by matching strongType . Portal sets this value if the scope is different than the assignment scope. If set, an edit of the policy assignment in Portal automatically sets the scope for the parameter to this value. However, the scope isn't locked to the value and it can be changed to another scope.

The following example of parameterScopes is for a strongType parameter named backupPolicyId that sets a scope for resource selection when the assignment is edited in the Portal.

updatedBy (string): The friendly name of the security principal that updated the assignment, if any.

updatedOn (string): The Universal ISO 8601 DateTime format of the assignment update time, if any.

evidenceStorages (object): The recommended default storage account that should be used to hold evidence for attestations to policy assignments with a manual effect. The displayName property is the name of the storage account. The evidenceStorageAccountID property is the resource ID of the storage account. The evidenceBlobContainer property is the blob container name in which you plan to store the evidence.

Resource selectors

The optional resourceSelectors property facilitates safe deployment practices (SDP) by enabling you to gradually roll out policy assignments based on factors like resource location, resource type, or whether a resource has a location. When resource selectors are used, Azure Policy will only evaluate resources that are applicable to the specifications made in the resource selectors. Resource selectors can also be used to narrow down the scope of exemptions in the same way.

In the following example scenario, the new policy assignment is evaluated only if the resource's location is either East US or West US .

When you're ready to expand the evaluation scope for your policy, you just have to modify the assignment. The following example shows our policy assignment with two more Azure regions added to the SDPRegions selector. Note, in this example, SDP means to Safe Deployment Practice :

Resource selectors have the following properties:

name : The name of the resource selector.

selectors : (Optional) The property used to determine which subset of resources applicable to the policy assignment should be evaluated for compliance.

kind : The property of a selector that describes which characteristic narrows down the set of evaluated resources. Each kind can only be used once in a single resource selector. Allowed values are:

resourceLocation : This property is used to select resources based on their type. Can't be used in the same resource selector as resourceWithoutLocation .

resourceType : This property is used to select resources based on their type.

resourceWithoutLocation : This property is used to select resources at the subscription level that don't have a location. Currently only supports subscriptionLevelResources . Can't be used in the same resource selector as resourceLocation .

in : The list of allowed values for the specified kind . Can't be used with notIn . Can contain up to 50 values.

notIn : The list of not-allowed values for the specified kind . Can't be used with in . Can contain up to 50 values.

A resource selector can contain multiple selectors . To be applicable to a resource selector, a resource must meet requirements specified by all its selectors. Further, up to 10 resource selectors can be specified in a single assignment. In-scope resources are evaluated when they satisfy any one of these resource selectors.

The optional overrides property allows you to change the effect of a policy definition without modifying the underlying policy definition or using a parameterized effect in the policy definition.

The most common use case for overrides is policy initiatives with a large number of associated policy definitions. In this situation, managing multiple policy effects can consume significant administrative effort, especially when the effect needs to be updated from time to time. Overrides can be used to simultaneously update the effects of multiple policy definitions within an initiative.

Let's take a look at an example. Imagine you have a policy initiative named CostManagement that includes a custom policy definition with policyDefinitionReferenceId corpVMSizePolicy and a single effect of audit . Suppose you want to assign the CostManagement initiative, but don't yet want to see compliance reported for this policy. This policy's 'audit' effect can be replaced by 'disabled' through an override on the initiative assignment, as shown in the following sample:

Overrides have the following properties:

kind : The property the assignment will override. The supported kind is policyEffect .

value : The new value that overrides the existing value. The supported values are effects .

selectors : (Optional) The property used to determine what scope of the policy assignment should take on the override.

kind : The property of a selector that describes what characteristic will narrow down the scope of the override. Allowed value for kind: policyEffect is:

  • policyDefinitionReferenceId : This specifies which policy definitions within an initiative assignment should take on the effect override.

Note that one override can be used to replace the effect of many policies by specifying multiple values in the policyDefinitionReferenceId array. A single override can be used for up to 50 policyDefinitionReferenceIds, and a single policy assignment can contain up to 10 overrides, evaluated in the order in which they're specified. Before the assignment is created, the effect chosen in the override is validated against the policy rule and parameter allowed value list (in cases where the effect is parameterized ).

Enforcement mode

The enforcementMode property provides customers the ability to test the outcome of a policy on existing resources without initiating the policy effect or triggering entries in the Azure Activity log .

This scenario is commonly referred to as "What If" and aligns to safe deployment practices. enforcementMode is different from the Disabled effect, as that effect prevents resource evaluation from happening at all.

This property has the following values:

If enforcementMode isn't specified in a policy or initiative definition, the value Default is used. Remediation tasks can be started for deployIfNotExists policies, even when enforcementMode is set to DoNotEnforce .

Excluded scopes

The scope of the assignment includes all child resource containers and child resources. If a child resource container or child resource shouldn't have the definition applied, each can be excluded from evaluation by setting notScopes . This property is an array to enable excluding one or more resource containers or resources from evaluation. notScopes can be added or updated after creation of the initial assignment.

An excluded resource is different from an exempted resource. For more information, see Understand scope in Azure Policy .

Policy definition ID

This field must be the full path name of either a policy definition or an initiative definition. policyDefinitionId is a string and not an array. The latest content of the assigned policy definition or initiative is retrieved each time the policy assignment is evaluated. It's recommended that if multiple policies are often assigned together, to use an initiative instead.

Non-compliance messages

To set a custom message that describes why a resource is non-compliant with the policy or initiative definition, set nonComplianceMessages in the assignment definition. This node is an array of message entries. This custom message is in addition to the default error message for non-compliance and is optional.

Custom messages for non-compliance are only supported on definitions or initiatives with Resource Manager modes definitions.

If the assignment is for an initiative, different messages can be configured for each policy definition in the initiative. The messages use the policyDefinitionReferenceId value configured in the initiative definition. For details, see policy definitions properties .

This segment of the policy assignment provides the values for the parameters defined in the policy definition or initiative definition . This design makes it possible to reuse a policy or initiative definition with different resources, but check for different business values or outcomes.

In this example, the parameters previously defined in the policy definition are prefix and suffix . This particular policy assignment sets prefix to DeptA and suffix to -LC . The same policy definition is reusable with a different set of parameters for a different department, reducing the duplication and complexity of policy definitions while providing flexibility.

For policy assignments with effect set to deployIfNotExist or modify , it's required to have an identity property to do remediation on non-compliant resources. When using identity, the user must also specify a location for the assignment.

A single policy assignment can be associated with only one system- or user-assigned managed identity. However, that identity can be assigned more than one role if necessary.

  • Learn about the policy definition structure .
  • Understand how to programmatically create policies .
  • Learn how to get compliance data .
  • Learn how to remediate non-compliant resources .
  • Review what a management group is with Organize your resources with Azure management groups .

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

Azure Policy Explained with Example [Step-by-Step]

Azure policy overview.

While organizations are transitioning towards deploying more and more resources in the cloud, it becomes imperative to ensure that the resources being deployed are in accordance with the organization’s standards. In this article, we will understand how we can ensure that our resources in the Azure cloud stay compliant via the use of Azure Policies.

Azure Policy is a service in Azure that you use to create, assign and manage policies. These polices are a mechanism through which we enforce compliance and enable auditing across our organization. Azure Policy does this by running evaluations of your resources and scanning for those not compliant with the policies you have created

Given below are the advantages of using Azure Polices:

  • Enforcement and compliance : Turn on built-in policies or build custom ones for all resource types. Real time policy evaluation and enforcement. Periodic and on-demand compliance evaluation.
  • Apply policies at scale : Apply policies to a Management Group with control across your entire organization. Apply multiple policies and aggregate policy states with policy initiative. Define an exclusion scope.
  • Remediation : Real time remediation, and remediation on existing resources.

Here are some use cases for Azure Polices:

  • Specify the resource types that your organization can deploy.
  • Prohibit the creation of resources for controlling costs.
  • Restrict access to a service when we don’t want it being deployed.
  • Specify a set of virtual machine SKUs that your organization can deploy.
  • Restrict the locations your organization can specify when deploying resources to enforce geographical compliance.
  • Enforce a required tag and its value.
  • Audit if Azure Backup service is enabled for all Virtual machines.

We can implement Azure Policies at various scopes within our organization. These are as follows:

  • Management groups
  • Subscriptions
  • Resource groups
  • Individual resources

Azure Policy components

Policy definition.

These are used to define what we will be monitoring for compliance and we also define the actions that will take place based on that evaluation. Azure offers several inbuilt policy definitions that we can use. Some of them are listed below.

  • Allowed Storage Account SKUs (Deny) : Determines if a storage account being deployed is within a set of SKU sizes. Its effect is to deny all storage accounts that don't adhere to the set of defined SKU sizes.
  • Allowed Resource Type (Deny) : Defines the resource types that you can deploy. Its effect is to deny all resources that aren't part of this defined list.
  • Allowed Locations (Deny) : Restricts the available locations for new resources. Its effect is used to enforce your geo-compliance requirements.
  • Allowed Virtual Machine SKUs (Deny) : Specifies a set of virtual machine SKUs that you can deploy.
  • Add a tag to resources (Modify) : Applies a required tag and its default value if it's not specified by the deploy request.
  • Not allowed resource types (Deny) : Prevents a list of resource types from being deployed.

To implement these policy definitions (both built-in and custom definitions), you'll need to assign them. You can assign any of these policies through the Azure portal, PowerShell, or Azure CLI.

Policy assignment

Once we define our policy, we need to assign it to a scope and that is where policy assignment comes into the picture. We can assign policies to management groups, subscriptions, resource groups or even individual resources within the Azure cloud.

Initiative definition

An initiative definition is a collection of policies that are tailored towards achieving a single high-end goal together. They simplify by grouping a set of policies as one single item. For example, ensuring that VMs are deployed as per standards.

Azure Policy example

An example of an Azure policy could be a scenario where we require resources to be tagged.

  • Policy definition : In this case, we can define that the virtual machines in our environment must have the tag “linux-cloud”. If this tag is missing then the creation of the virtual machine is denied.
  • Policy assignment : We would assign this policy at the scope of the resource group under which the VMs would be created.

With this policy in effect, when we try to deploy a VM without the required tag in the resource group with the policy applied, then the creation of that virtual machine will be denied.

Azure Policy Example

Now that we’ve understood the need of Azure policies, gone through the use cases and its different components, now it’s time to perform some hands on and see Azure policies in action. For the purpose of this demonstration, we’ll be using a built in Azure policy definition.

Step 1: Open the Azure policy service pane

Log in to the Azure portal and within the search bar, type policy and select the first result.

Azure Policy Explained with Examples

This will bring us to the overview section of our Azure Policy service. If you don’t have any existing policies applied, the page should look similar to the one shown below.

Azure Policy Explained with Examples

This page shows us the overall compliance status of our resources and also if any resources are in a non-compliant state so that we may take corrective actions.

Step 2: Create Azure policy definition

Towards the left side of the page, we have a section named authoring and within this section, there is a tab called definitions. Click on this tab to create a policy definition or use an existing one.

Azure Policy Explained with Examples

Clicking on the definitions tab takes us to the policy definitions page where we can view all of the pre-existing policies and initiative definitions.

Azure Policy Explained with Examples

We can use filters on this page to view only custom or only built-in policies under the type. We can filter polices based on different categories which are basically different Azure services. Also, we can search for a policy by typing the policy name in the search bar. We are going to search for location based policies so we’ll type in the keyword location in the search bar.

Azure Policy Explained with Examples

The policy that we are going to use is “ allowed locations ”. We will click on this policy so that we may examine it.

Azure Policy Explained with Examples

What we’ll see here is the JSON that defines the policy. Given below is the full JSON policy definition.

Description:

  • The definition contains information related to the policy like the display name, description and many other things. This policy is going to allow us to restrict the locations where we may deploy resources in the Azure cloud. This allows us to enforce geographical compliance in the environment.
  • The parameters section contains a parameter (of type array) named listOfAllowedLocations .
  • The listOfAllowedLocations parameter is being matched in the policy rule section such that any location that is not listed in this parameter will not be allowed. After this condition, we have an exemption section wherein if the field contains the location global or if the resource being created is an Azure Active Directory resource, then the policy is not enforced.
  • In the next section, we see the effect of non-compliance i.e., deny.

Step 3: Assign Azure Policy

Right above the policy definition JSON, we see an Assign button. Click on this button and we will now need to select the scope for this policy. We have selected our subscription and a resource group under that subscription.

Azure Policy Explained with Examples

We can also site exclusions from this policy if we wish to but we are not going to do this in this demonstration. From here click next . This brings us to the allowed locations parameters section where we need to select the locations, we would like to allow resources to be built in.

Azure Policy Explained with Examples

We will select Asia and Asia Pacific .

Azure Policy Explained with Examples

Now click review and create and then click on create on the next page.

Azure Policy Explained with Examples

This will now create the policy assignment which could take up to 30 minutes to take effect.

Step 4: Test the new azure policy

To test the policy, we’ll deliberately attempt to create a virtual machine that is not in one of the two allowed locations. So, we quickly navigate to the Virtual Machine service window in Azure, fill in the subscription, resource group, name and image.

In the region we’ve specified “ West US ” which is NOT Asia or Asia Pacific .

Azure Policy Explained with Examples

With these parameters entered, click on review and create . On the next page, we’ll encounter the following error.

Azure Policy Explained with Examples

Click on the arrow to view the error details.

Azure Policy Explained with Examples

The above error message clearly states that the VM deployment failed because we were trying to create a VM in a location is not one of the allowed locations thus verifying the successful enforcement of our Azure Policy .

In this article, we discussed the need and benefits of using Azure policy and we also practically demonstrated the enforcement of an Azure policy. We encourage you try out other pre-built Azure polices and examine the different levels and types of restrictions that could be enforced.

We’ve referred to the official Azure documentation along with the "Control and organize Azure resources with Azure Resource Manager" and "Build a cloud governance strategy on Azure" modules part of the managing resources in Azure learning path. Azure Policy Overview Control and organize Azure resources with Azure Resource Manager Build a cloud governance strategy on Azure

Sahil Hulage

He possesses over 5 years of experience as a Cloud Consultant, specializing in Azure DevOps and CloudLinux. With his expertise, he implements and optimizes cloud solutions, ensuring seamless operations and efficient resource management. You can connect with him on LinkedIn .

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to [email protected]

Thank You for your support!!

Leave a Comment Cancel reply

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

Notify me via e-mail if anyone answers my comment.

For Cloud Developers and IT Pros

Walkthrough using azure policy to audit and enforce compliance.

azpolicy

In this walkthrough, you will learn the implications of using a Policy in Azure. For this walkthrough, you will use Azure CLI to create a storage account that will not be compliant, but allowing its contents to be accessed using HTTP. Then you will add a Policy that requires HTTPS, and see how you can audit existing, non-compliant resource. You will audit the resource using the portal and using PowerShell script. Then you will create another non-compliant resource and see how Azure blocks the resource during creation.

Prerequisites

  • It is helpful that you understand resource groups and about storage accounts. Although the sample provides code, you will want to know how to upload a small file into Azure blob storage. You can use the portal or AzCopy .
  • The sample shows how to use specific role, but you should understand about role based access control roles.
  • You will need owner or contributor access in your subscription.

Definitions

First let’s start with some definitions:

Business rule is a standard that the business wants to audit or wants to insure is compliance. Often, but not always, business rules follow compliance standards, such as ISO 27001 or NIST.

Resource Provider is service that supplies Azure resources. For example, a common resource provider is Microsoft.Storage, which supplies the storage resource. The name of a resource type is in the format:  {resource-provider}/{resource-type} .

Resource is a manageable item that is available through Azure. Virtual machines, storage accounts, web apps, databases, and virtual networks are examples of resources. when the resource is created, it has an id. The id has a field that has a format like /subscriptions//resourceGroups//providers/Microsoft.Compute/disks/ .

Resources have properties that you set when you create the resource. For example, when you create a storage account, you set its location.

Azure Policy examines properties on resources that are represented in Resource Manager and properties of some Resource Providers. For example the location of a resource is a property that a policy can audit.

Policy definition is the JSON implementation of a business rule.

Several business rules can be grouped together into a Policy initiative .

The policy definition or initiative is assigned to any scope that can be a management groups, subscriptions, resource groups, or individual resources.

A policy assignment applies the policy to all resources within the scope. For example, if the policy

For more information, see:

  • What is Azure Resource Manager?
  • Azure resource providers and types
  • What is Azure Policy?

Identify the business requirements

Let’s begin by defining the compliance requirements.

The requirements should clearly identify both the “to be” and the “not to be” resource states.

For example in this case:

First, let’s figure out the resource property that we want to build our policy on.

Explore resource properties that might want to check

Each resource in Azure is built on a set of APIs that are defined at the top level as Azure resource providers . A resource provider is [uhm] a service that provides resources, such as storage.

For the list of the providers, see Resource providers for Azure services . To get a list of providers and the status of whether they are installed in your subscription, use the following command:

Let’s start by reviewing the Microsoft.Storage resource provider. Resource Manager template reference for the storage account resource gives you a (nearly all) the property. In this case, the supportsHttpsTrafficOnly will be the one we use.

supportshttps

In the StorageAccountPropertiesCreateParameters object is the supportsHttpsTrafficOnly .

httpstraffic

Another way to explore resources

Once you have created a resource, you can inspect their properties. Use the Azure Resource Explorer to inspect the context of your subscription. You can browse by providers, subscriptions, resource groups, and resources.

Find the property alias

We need to map the property we found to it’s alias . When you create a policy, it uses aliases to restrict what values or conditions are allowed. Each alias maps to paths in different API versions for a given resource type. During policy evaluation, the policy engine gets the property path for that API version.

Use the following cli to get the alias used by the Azure Policy.

As shown in the following illustration, the results show that supportsHttpsTrafficOnly is supported.

supporthttps

This means we can write a policy based on supportsHttpsTrafficOnly .

Another way to query the aliases is to use Azure Graph. The following code installs Azure Graph into the CLI and queries the aliases. The results are provided in a heirarchy that may be easier to view.

Before we go install a custom policy, let’s create a sample resource that will not be compliant.

Create a non-compliant storage account

Let’s begin by creating a storage account resource that allows applications to access the storage, create a container, and upload a file. Log into Azure using az login , then use the following code to create a resource group, storage account, and storage container; grant yourself contributor access to the storage account, create a file and upload it.

Note: For the demo to work, you will explicitly need to assign the  Storage Blob Data Contributor role to yourself. Even though you are the account owner, you need explicit permissions to perform data operations against the storage account.

The storage account is intentionally created with --https-only false .

Next, before we create our custom policy, let’s test to see if there is a voilation of Azure policy from our existing policies.

Test against current policies

Does the new storage resource already violate one of our policies? Log into the Azure Portal, search in the search bar for Policy . And there is an intiative that was installed by Azure Security Center that flags the storage resource as not being compliant, as shown in the following illustration.

notcompliant

Click through the links initiative and you can see resource that we just created and the rule that was violated, as shown in the following illustration.

resourcecompliance

Our business requirement is to now allow the creation of storage accounts, not to just audit. In the next step, create a custom policy to stop anyone from creating a storage account that is non-compliant.

Create custom policy to deny the non-compliant storage creation

It is possible to go into the portal and just change the policy. You could go into the initiative, edit the assignment of the policy, and change the parameter from Audit to Deny . But in our world where you want to track the changes and to automate your new initiatives, you will want to create a custom policy that denies creation of the non-compliant resource.

The following JSON (from the Microsoft documentation Tutorial: Create a custom policy definition ) shows the policy.

Several itesm to note from the code:

  • The displayName and description elements show the intent of the policy.
  • The effectType element on lines 7 to 18 defaults to Deny , but allows you to set the effect to Disabled , which allows you to turn off the rule.
  • The storage account type is Microsoft.Storage/storageAccounts and
  • The storage account supportsHttpsTrafficOnly property is not true

Next, let’s split up our policy so we can create the policy definition.

Create the policy definition

The policy definition consists of rules and parameters for those rules. Both are declared in JSON. The following script uses Bash to create two files, one for the rules and one to define the parameters.

Use az policy definition create to create the policy definition. See Create a policy definition with Azure CLI . The following code creates a policy definition and saves the policy definition to a subscription. It does not assign the policy to the subscription.

Once you have defined the policy, you can find it in the portal. Open the portal, search Policy, click Definitions to all the the policies. Search on https. The following illustration shows the definition of the matchint policies.

denystorage

Click Deny storage accounts not using only HTTPS to see your policy definition.

You may want to consider the following best practices:

You could have saved the policy to a management group, which is then available as a the policy definition to all of the subscriptions associated with the management group. The rule and param URLs can point to your rules in GitHub or Azure DevOps.

Now that we have a definition available in our subsription, you need to apply it.

Apply the policy to a scope

Now that your policy has been defined and available in your subscription, you need to assign the policy. This step sets the policy to a particular scope .

Valid scopes are management group, subscription, resource group, and resource as shown in this table:

You can assign the policy in the portal. See

To automate it, use an Azure CLI script command az policy assignment create to assign the policy definition to the scope. The following sample assigns the policy to the subscription scope.

As it assigns the policy, it also provides the parameters for this particular assignment.

Now that you have the policy assigned, what happened to the non-compliant resource?

Check compliance

Once you have assigned the policy to your subscription, you will want to check compliance. The resource created in an earlier step still fails based on the Security Center rule. But it also fails based on the new custom rules you added in the previous step.

To view, open Policy blade in the Azure portal. Click Compliance .

policycompliance

It takes a few minutes to scan your resources.

Assigning a policy with a “deny” effect may take up to 30 mins (average case) and 1 hour (worst case) to start denying the creation of non-compliant resources.

You can query for non-compliant resources in PowerShell. The following cmdlet returns the details for all non-compliant storage accounts.

Creation of a non-compliant resource now fails

To test that the policy denies creation of an non-compliant resource, run the script in the previous section to create a non-compliant storage account. The following code tries to create a new storage account in the same resource group.

Once completed, you will see an error message.

policyerror

When you go into the portal, click Compliance in the Policy page to see results. Click Require https for storage in subscription to see the summary of non-compliance. Notice that the existing resource is audited as not compliant. And the denial for the creating of the non-compliant storage account is shown.

policycompliance2

View compliance in Log Analytics

Because you installed a Log Analytics workspace as described in the post Setting up Log Analytics workspace for production in enterprise , you can view AzureActivity from the Activity Log Analytics solution tied to your subscription.

policyactivitylog

Apply policy using a ARM template

The documentation Quickstart: Create a policy assignment to identify non-compliant resources by using a Resource Manager template shows how you can deploy a policy to a resource group.

You will need the policyDefinitionID . Use the following command to get the properties of the policy you want to apply.

Use the properties when you deploy the ARM template.

This was a deep-dive walkthrough into how to define and implement your own policies, which build-in governance best practices for your users. You learned the workflow of a custom policy and how to deploy the policy into either a subscription or management group. And you learned how to check your compliance with all your initiatives.

  • Define your own specific bsuiness requirements for your own compliance initiatives. Review the Azure Policy security baseline for Azure Security Benchmark .
  • Define tags so you can idenity who ownership of resources. Define business rules, policy definition, and assign policies so you will know who to contact and when to review resources as policies change.
  • Review the built-in policy definitions and initiatives to help you in quickly building your own compliance initiatives. Note how the policies have versions
  • Follow and update policies that are on GitHub
  • Understand Azure Policy effects
  • Learn about Blueprints that can group together your policies, resource groups, and role assignments for automation
  • Design Policy as Code workflows
  • Define alerts to watch for non-compliance in Azure Monitor logs.
  • Quickstart: Create, download, and list blobs with Azure CLI
  • Authorize with Azure AD credentials
  • Quickstart: Create a policy assignment to identify non-compliant resources with Azure CLI

Share this:

Leave a reply cancel reply, discover more from azuredays.

Subscribe now to keep reading and get access to the full archive.

Type your email…

Continue reading

Assignment Naming Element

Assigning policy sets or policies, assignment scopes and excluded scopes, defining parameters with json, defining overrides with json, defining noncompliancemessages with json.

  • Defining parameters, overrides and nonComplianceMessages with a CSV file

Defining resourceSelectors

Defining metadata, defining enforcementmode.

  • Policy Exemptions

Policy Assignments

This chapter describes how Policy Assignments are handled by EPAC. To learn about how custom Policy and Policy Set definitions are managed, see the Policies and Policy Set Definitions .

Assignment JSON structure

Assignment JSON is hierarchical for efficient definitions, avoiding duplication (copy/paste) of JSON. Each branch of the tree is cumulative. Each tree node must include a nodeName - an arbitrary string exclusively used by EPAC to display an error location. EPAC concatenates a leading / and the nodeName entries encountered in the tree to create a "breadcrumbs" trail; therefore, we recommend that you use / to help separate the concatenated nodeName . The following (partial and invalid) assignment tree would create this error message.

JSON Schema

The GitHub repo contains a JSON schema which can be used in tools such as VS Code to provide code completion.

To utilize the schema add a $schema tag to the JSON file.

This schema is new in v7.4.x and may not be complete. Please let us know if we missed anything.

  • Every tree branch must accumulate a definitionEntry (or definitionEntryList ), Assignment naming ( name and displayName ) and scope element.
  • The elements parameters , overrides , resourceSelectors , notScope , enforcementMode , metadata , userAssignedIdentity , managedIdentityLocations , additionalRoleAssignments and nonComplianceMessages are optional.
  • For Policy Sets with large numbers of included Policies you should use a spreadsheet (CSV file) to manage effects (parameterized or effect overrides ), parameters and optional nonComplianceMessages . We recommend the CSV approach for Policy Sets with more than 10 included Policies.
  • EPAC continues to support deprecated elements initiativeId , initiativeName and ignoreBranch , Consider using their replacements policySetId , policySetName and enforcementMode instead.

The tree is not required to be balanced. The number of levels is not restricted; however, anything beyond 3 levels is unnecessary in real scenarios and would be difficult to read and manage as the depth increases.

Tree Structure

Assignment File Overview Diagram

Each Assignment is required to have a name which is used in it's resource id. EPAC also requires a displayName . The description is optional. For the allowed location assignment you specify the component with:

Multiple assignment naming components in a tree branch are string concatenated for each of the three fields.

Azure has a limit of 24 characters for the concatenated name string. EPAC displays an error if this limit is exceeded.

Each assignment assigns either a Policy or Policy Set. In EPAC this is done with a definitionEntry or a definitionEntryList . Exactly one occurrence must exist in any collated tree branch. For each entry, you need to specify one of the following:

  • policyName - custom Policy managed by EPAC. Specifying just the name allows EPAC to inject the correct definition scope.
  • policySetName - custom Policy Set managed by EPAC.
  • policyId - resource id for builtin Policy.
  • policySetId - resource id for builtin Policy Set.

displayName is an optional field to document the entry if the Policy name is a GUID. Builtin Policies and Policy Sets use a GUID.

Using definitionEntryList allows you to save on copy/paste tree branches. Without it, the number of branches would need to be duplicated as many times as the list has entries.

Each entry in the list creates an Assignment at each leaf of the tree. Since assignments must have unique names at a specific scope, the Assignment naming component must be amended for each list entry. In this sub-component you can decide if you want to concatenate the string by appending or prepending them by specifying append boolean value.

In the above example one of the children (leaf node) has the following Assignment name.

This example generates two assignments at the "prod" leaf per scope:

  • /providers/Microsoft.Management/managementGroups/ Contoso-Prod /providers/Microsoft.Authorization/policyAssignments/ pr-asb
  • displayName = "Prod Azure Security Benchmark"
  • description = "Prod Environment controls enforcement with Azure Security Benchmark Initiative."
  • /providers/Microsoft.Management/managementGroups/ Contoso-Prod /providers/Microsoft.Authorization/policyAssignments/ pr-nist-800-53-r5
  • displayName = "Prod NIST SP 800-53 Rev. 5"
  • description = "Prod Environment controls enforcement with NIST SP 800-53 Rev. 5 Initiative."

scope is required exactly once in each tree branch. Excluded scopes ( notScope ) are cumulative from global-settings.json and the entire tree branch; however, once a scope is defined notScope may not be defined at any child node.

Both scope and notScope are specific to an EPAC Environment using the pacSelector name , e.g., epac-dev and tenant .

notScope works the same. In addition "*" means all EPAC Environments which is most often used for resourceGroupPatterns .

Managed Identities and role assignments

Policies with a DeployIfNotExists or Modify effect need a Managed Identity (MI) and role assignments to execute remediation task. EPAC calculates the necessary role assignments based on the roleDefinitionIds in the Policy definition. By default EPAC uses a system-assigned Manged Identity. The team maintaining EPAC recommend system-assigned identities; however, your organization may have role assignment reasons to use user-assigned Managed Identities.

Defining managedIdentityLocations

Policy assignments requiring a Managed Identity (system-assigned or user-assigned) require a location managedIdentityLocations . You must specify the location based on EPAC Environment or use "*" to use the same location for all of the EPAC Environments. You can specify them in global-settings.jsonc or at any node in the tree. The last (closest to the leaf node) is the one chosen if multiple managedIdentityLocations entries are encountered in a tree branch.

Defining optional additionalRoleAssignments

In some scenarios you will need additionalRoleAssignments ; e.g., for diagnostics settings to Event Hubs, the target resource might be in a different Management Group and therefore the Managed Identity requires additional role assignments. You must specify the additionalRoleAssignments based on EPAC Environment or use "*" to use the same additionalRoleAssignments for all of the EPAC Environments.

User-assigned Managed Identities

Azure Policy can use a user-defined Managed Identity and EPAC allows you to use this functionality (new in version 7.0). You must specify the user-defined Managed Identity based on EPAC Environment or use "*" to use the same identity for all of the EPAC Environments (only possible in single tenant scenarios). Within each EPAC Environment entry, you can specify just the URI string indicating to use the same identity even if we are using a definitionEntryList , or in the case of a definitionEntryList can assign a different identity based on the definitionEntryList by specifying a matching policyName , policyId , policySetName or policySetId .

The rest (below) of the node components are optional.

parameters have a simple JSON structure. You do not need the additional value indirection Azure requests (EPAC will inject that indirection).

Too enable definitionEntryList , parameters not present in the Policy or Policy Set definition are quietly ignored.

overrides are in the same format as documented by Azure . They are cumulative in each tree branch. The selectors element is only used for Assignments of Policy Sets. They are not valid for Assignments of a single Policy.

If using definitionEntryList , you must add the policyName , policyId , policySetName or policySetId as used in the definitionEntryList item.

Assign a non-compliance message to the assignment, or individual non-compliance messages if the assignment is for an Policy Set. This value is an array of objects - each containing a message, and in the case of an initiative a policyDefinitionReferenceId. See this link for details.

If you use single definitionEntry , place them normally. If you use a definitionEntryList place them in the respective list entry.

Defining parameters , overrides and nonComplianceMessages with a CSV file

Assigning single or multiple security and compliance focused Policy Sets (Initiatives), such as Azure Security Benchmark, NIST 800-53 r5, PCI, NIST 800-171, etc, with just JSON parameters becomes very complex fast. Add to this the complexity of overriding the effect if it is not surfaced as a parameter in the Policy Set using overrides . Finally, adding the optional nonComplianceMessages further increases the complexity.

To address the problem of reading and maintaining hundreds or thousands of JSON lines, EPAC can use the content of a spreadsheet (CSV) to create parameters , overrides and optionally nonComplianceMessages for a single Policy assignment definitionEntry or multiple Policy definitions ( definitionEntryList ).

This approach is best for very large Policy Sets such as Azure Security Benchmark, NIST 800-53, etc. Smaller Policy Sets should still be handled with JSON parameters , overrides and nonComplianceMessages .

Start by generating documentation for one or more of those Policy Sets , then modify the effect and parameter columns for each type of environment types you will use. In the example header below the infrastructure environments prod, test, dev, and sandbox are used as prefixes to the columns for Effect and Parameters respectively. Optionally you can add a column for nonComplianceMessages . If you want to switch from JSON to CSV, you can generate this CSV file frm your already deployed Assignment(s) .

The CSV file generated contains the following headers/columns:

name,referencePath,policyType,category,displayName,description,groupNames,policySets,allowedEffects,allowedOverrides,prodEffect,testEffect,devEffect,sandboxEffect,prodParameters,testParameters,devParameters,sandboxParameters,nonComplianceMessages

Column explanations:

  • name is the name of the policyDefinition referenced by the Policy Sets being assigned.
  • referencePath is only used if the Policy is used more than once in at least one of the Policy Sets to disambiguate them. The format is <policySetName>//<policyDefinitionReferenceId> .
  • policyType , category , displayName , description , groupNames , policySets , allowedEffects are optional and not used for deployment planning. They assist you in filling out the <env>Effect columns.
  • <env>Effect columns must contain one of the allowedValues or allowedOverrides values. You define which scopes define each type of environment and what short name you give the environment type to use as a column prefix.
  • <env>Parameters can contain additional parameters. You can also specify such parameters in JSON. EPAC will use the union of all parameters.
  • nonComplianceMessages column is optional. The documentation script does not generate this columns.

EPAC will find the effect parameter name for each Policy in each Policy Set and use them. If no effect parameter is defined by the Policy Set, EPAC will use overrides to set the effect. EPAC will generate the policyDefinitionReferenceId for nonComplianceMessages .

After building the spreadsheet, you must reference the CSV file and the column prefix in each tree branch. parameterFile can be overridden in a child node; however, it is often used once per tree branch and defined adjacent to the 'definitionEntry or definitionEntryList .

In the child nodes specifying the scope(s) specify which column prefix to use for selecting the CSV columns with parameterSelector . The actual prefix names have no meaning; they only need to match between the JSON below and the CSV file.

The element nonComplianceMessageColumn may appear anywhere in the tree. Definitions at a child override the previous setting. If no nonComplianceMessageColumn is specified, the spreadsheet is not used for the (optional) nonComplianceMessages .

resourceSelectors may appear anywhere in the tree and are cumulative in any branch. They follow the standard Azure Format .

metadata is sometimes used to track tickets for changes. Do NOT specify EPAC-reserved elements roles and pacOwnerId . For the final metadata EPAC creates the union of instances in the entire tree branch.

enforcementMode is similar to the deprecated ignoreBranch ; it deploys the assignment and sets the assignment to Default or DoNotEnforce . DoNotEnforce allows a what-if analysis. enforcementMode may appear anywhere in the tree. Definitions at a child override the previous setting.

Example assignment files

Simple policy assignment (allowed locations).

In the simple case an assignment is a single assignment or with no difference in assignment , parameters , and definitionEntry across multiple scopes. In many scenarios "Allowed Locations" is such a simple Assignment. Such Assignments do not have child nodes, just the root node.

  • nodeName is required for error messages; it's value is immaterial. EPAC concatenates them in the current tree branch.
  • definitionEntry specifies that the custom Policy Set general-allowed-locations-policy-set from our starter kit. displayName has no meaning - it is for readability and in this instance is superfluous.
  • assignment fields name , displayName and description are used when creating the assignment.
  • This assignment has no metadata . You don't need an empty collection. EPAC will add pacOwnerId and roles metadata . Do not add them manually.
  • enforcementMode is set to default - it is superfluous.
  • parameters are obvious. Note: you don't add the value layer Azure inserts - EPAC takes care of that.
  • During Policy resource development (called epac-dev ) the Assignment is deployed to an EPAC development Management Group Epac-Mg-1 .
  • During Policy prod deployments ( tenant -wide), it is deployed to the tenant Management Group Epac-Mg-1 .
  • No notScope entries are specified.

If we remove the empty and superfluous entries, we arrive at:

Security-Focused Policy Assignment with JSON parameters

  • In the following example we named our root node ( nodeName ) /security/ . Since it is only used in case of error messages produced by EPAC during planning it's actual value doesn't matter as long as it's unique.
  • We use a definitionEntryList to create two assignments at every leaf (six assignments total).
  • For assignment string concatenation we append the strings in the definitionEntryList to the strings in the child nodes. You can see this best when you look at the description string in the child nodes. It will form a sentence when concatenated by append ing the definitionEntryList assignment field description .
  • The parameters specified in the children are specific to the IaC environment types and their scope . Note: a real assignment would define many more parameters. The set here is abbreviated since the actual set could easily exceed a hundred entries for each of the IaC environments. We'll see in the next example how to simplify large Policy Set parameters with a CSV file.

Security-Focused Policy Assignment with CSV file parameters

This example is the same as the previous, except we replaced inline JSON parameters with a CSV file and use the column prefixes in the CSV file to select which parameter values we use by:

  • Setting the file name at the root node with

json "parameterFile": "security-baseline-parameters.csv",

  • Setting the column prefix with parameterSelector to prod , nonprod and sandbox . For example:

The CSV file is explained above . The entire file is:

Inverted Policy Assignment (Tag Inheritance and Required Tags)

As mentioned above sometimes it is advantageous (to reduce the number of repetitions) to turn a definition on its head:

  • Common parameters , scope , definitionEntryList (with two Policies) at the root ( nodeName is /Tags/ ).
  • Start of the assignment strings ( append is defaulted to false ). Again look at description which will be a concatenated sentence.
  • The children define the tagName parameter and the second part of the strings for assignment . The set of parameters is the union of the root node and the child node.
  • This creates six Assignments (number of Policies assigned times number of children).

Non-Compliance Messages in a Policy Definition Assignment

An example of a policy assignment for a single policy definition with a default non-compliance message.

Non-Compliance Messages in a Policy Set Definition Assignment

An example of a policy assignment for a policy set definition with a default non-compliance message and a policy specific non-compliance message.

Non-Compliance Messages in a Policy Set Definition Assignment with a definitionEntryList

An example of how to use a non-compliance message when using a definitionEntryList list in the assignment.

azure policy definition and assignment

Alif consulting logo

ISO Certified

  • Oct 31, 2022

What is Azure Policy?

Updated: Dec 27, 2023

Azure Policy helps to enforce organizational standards and to assess compliance at-scale. Through its compliance dashboard, it provides an aggregated view to evaluate the overall state of the environment, with the ability to drill down to the per-resource, per-policy granularity. It also helps to bring your resources to compliance through bulk remediation for existing resources and automatic remediation for new resources.

Common use cases for Azure Policy include implementing governance for resource consistency, regulatory compliance, security, cost, and management. Policy definitions for these common use cases are already available in your Azure environment as built-ins to help you get started.

All Azure Policy data and objects are encrypted at rest .

Azure policy

Azure Policy evaluates resources in Azure by comparing the properties of those resources to business rules. These business rules, described in JSON format , are known as policy definitions . To simplify management, several business rules can be grouped together to form a policy initiative (sometimes called a policySet ). Once your business rules have been formed, the policy definition or initiative is assigned to any scope of resources that Azure supports, such as management groups , subscriptions, resource groups , or individual resources. The assignment applies to all resources within the Resource Manager scope of that assignment. Subscopes can be excluded, if necessary.

Azure Policy uses a JSON format to form the logic the evaluation uses to determine whether a resource is compliant or not. Definitions include metadata and the policy rule. The defined rule can use functions, parameters, logical operators, conditions, and property aliases to match exactly the scenario you want. The policy rule determines which resources in the scope of the assignment get evaluated.

azure policy definition and assignment

Understand evaluation outcomes

Resources are evaluated at specific times during the resource lifecycle, the policy assignment lifecycle, and for regular ongoing compliance evaluation. The following are the times or events that cause a resource to be evaluated:

A resource is created or updated in a scope with a policy assignment.

A policy or initiative is newly assigned to a scope.

A policy or initiative already assigned to a scope is updated.

During the standard compliance evaluation cycle, which occurs once every 24 hours.

Control the response to an evaluation

Business rules for handling non-compliant resources vary widely between organizations. Examples of how an organization wants the platform to respond to a non-compliant resource include:

Deny the resource change

Log the change to the resource

Alter the resource before the change

Alter the resource after the change

Deploy related compliant resources

Azure Policy makes each of these business responses possible through the application of effects . Effects are set in the policy rule portion of the policy definition .

Azure Policy and Azure RBAC

There are a few key differences between Azure Policy and Azure role-based access control (Azure RBAC). Azure Policy evaluates state by examining properties on resources that are represented in Resource Manager and properties of some Resource Providers. Azure Policy doesn't restrict actions (also called operations ). Azure Policy ensures that resource state is compliant to your business rules without concern for who made the change or who has permission to make a change. Some Azure Policy resources, such as policy definitions , initiative definitions , and assignments , are visible to all users. This design enables transparency to all users and services for what policy rules are set in their environment.

Azure RBAC focuses on managing user actions at different scopes. If control of an action is required, then Azure RBAC is the correct tool to use. Even if an individual has access to perform an action, if the result is a non-compliant resource, Azure Policy still blocks the create or update.

The combination of Azure RBAC and Azure Policy provides full scope control in Azure.

azure policy definition and assignment

Resources covered by Azure Policy

Azure Policy evaluates all Azure resources at or below subscription-level, including Arc enabled resources. For certain resource providers such as guest configuration , Azure Kubernetes Service , and Azure Key Vault , there's a deeper integration for managing settings and objects.

Recommendations for managing policies

Here are a few pointers and tips to keep in mind:

Start with an audit effect instead of a deny effect to track impact of your policy definition on the resources in your environment. If you have scripts already in place to autoscale your applications, setting a deny effect may hinder such automation tasks already in place.

Consider organizational hierarchies when creating definitions and assignments. We recommend creating definitions at higher levels such as the management group or subscription level. Then, create the assignment at the next child level. If you create a definition at a management group, the assignment can be scoped down to a subscription or resource group within that management group.

We recommend creating and assigning initiative definitions even for a single policy definition. For example, you have policy definition policyDefA and create it under initiative definition initiativeDefC . If you create another policy definition later for policyDefB with goals similar to policyDefA , you can add it under initiativeDefC and track them together.

o Once you've created an initiative assignment, policy definitions added to the initiative also become part of that initiative's assignments.

o When an initiative assignment is evaluated, all policies within the initiative are also evaluated. If you need to evaluate a policy individually, it's better to not include it in an initiative.

Manage Azure Policy resources as code with manual reviews on changes to policy definitions, initiatives, and assignments.

Azure Policy objects

Policy definition.

The journey of creating and implementing a policy in Azure Policy begins with creating a policy definition. Every policy definition has conditions under which it's enforced. And, it has a defined effect that takes place if the conditions are met.

In Azure Policy, we offer several built-in policies that are available by default. For example:

Allowed Storage Account SKUs (Deny)

Determines if a storage account being deployed is within a set of SKU sizes. Its effect is to deny all storage accounts that don't adhere to the set of defined SKU sizes.

Allowed Resource Type (Deny)

Defines the resource types that you can deploy. Its effect is to deny all resources that aren't part of this defined list.

Allowed Locations (Deny)

Restricts the available locations for new resources. Its effect is used to enforce your geo-compliance requirements.

Allowed Virtual Machine SKUs (Deny)

Specifies a set of virtual machine SKUs that you can deploy.

Add a tag to resources (Modify)

Applies a required tag and its default value if it's not specified by the deploy request.

Not allowed resource types (Deny)

Prevents a list of resource types from being deployed.

To implement these policy definitions (both built-in and custom definitions)

You'll need to assign them. You can assign any of these policies through the Azure portal, PowerShell, or Azure CLI.

Initiative definition

An initiative definition is a collection of policy definitions that are tailored toward achieving a singular overarching goal. Initiative definitions simplify managing and assigning policy definitions. They simplify by grouping a set of policies as one single item. For example, you could create an initiative titled Enable Monitoring in Microsoft Defender for Cloud, with a goal to monitor all the available security recommendations in your Microsoft Defender for Cloud instance

Under this initiative, you would have policy definitions such as:

Monitor unencrypted SQL Database in Microsoft Defender for Cloud - For monitoring unencrypted SQL databases and servers.

Monitor OS vulnerabilities in Microsoft Defender for Cloud - For monitoring servers that don't satisfy the configured baseline.

Monitor missing Endpoint Protection in Microsoft Defender for Cloud - For monitoring servers without an installed endpoint protection agent.

Like policy parameters, initiative parameters help simplify initiative management by reducing redundancy. Initiative parameters are parameters being used by the policy definitions within the initiative.

Assignments

An assignment is a policy definition or initiative that has been assigned to a specific scope. This scope could range from a management group to an individual resource. The term scope refers to all the resources, resource groups, subscriptions, or management groups that the definition is assigned to. Assignments are inherited by all child resources. This design means that a definition applied to a resource group is also applied to resources in that resource group. However, you can exclude a subscope from the assignment.

  • Microsoft Azure

Recent Posts

Azure Service Fabric

Azure SQL Database - Case Study

Onboard Microsoft Sentinel

Comentarios

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!

How to deploy Azure Policies with ARM templates

This post describes an outdated experience of authoring Azure Policy with ARM templates. For a new approach, check out my post on “ How to deploy Azure Policy with Bicep .”

When creating custom Azure Policy definitions and assignments for them, basically, there are a few options for doing this programmatically:

  • using the REST API ;
  • running the PowerShell cmdlets ;
  • executing the Azure CLI commands ;
  • defining them in ARM templates.

Let’s make a brief overview of them.

If I were you, I would consider using Azure REST API as a fallback option when there are no other ways to interact with an Azure resource. I’m not a big fan of it because I see it as a low-level interface that requires more effort to use and maintain in automation solutions.

Regarding Azure PowerShell and Azure CLI for working Azure Policies, I feel somewhat confused about the implementation of their cmdlets and commands. For example, ‘ New-AzPolicyDefinition ’ cmdlet requires you to provide policy rules and policy parameters as separate files and also to specify policy name, display name, description and metadata as cmdlet input parameters. So, instead of keeping all information defining an Azure Policy in one place, you have to synchronize it among multiple files .

Azure CLI commands resemble the same usage pattern that introduces duplication in the contribution process . This, in turn, makes automated deployments for Azure Policies a mixture of data and logic when using the out-of-the-box tools.

To make your deployment pipeline more organized, you might look for creating a custom deployment scripts to parse all required information from a single ‘azurepolicy.json’ file or describe your Azure Policy definitions and assignments in an ARM template, which is my choice for consistent deployment approach in Azure.

Note: At the time of writing, it is not possible to use ARM templates to deploy resources on a Management Group level. Use Azure PowerShell or Azure CLI options for that.

How to define policy definitions in ARM templates

Unfortunately, the documentation about defining Azure Policy resources in ARM templates is not very descriptive about the technical aspects of this approach: just a short example of defining a policy definition in a template , which, for an unknown reason, is located in a completely different section of the documentation. So, what to pay attention to?

Firstly, when creating ARM templates with Azure Policy definitions, use the schema for subscription-level deployment :

https://schema.management.azure.com/schemas/2018-05-01/subscriptionDeploymentTemplate.json#

Also, to deploy the subscription-level templates, if using Azure PowerShell, use ‘New-AzDeployment’ cmdlet instead of ‘New-AzResourceGroupDeployment.’

Secondly, if your custom policy definition requires input parameters or uses policy functions , such as ‘concat,’ for instance, use escape characters for them in policy definition body , so they are not invoked during the template deployment and just passed through as parts of the policy definition:

Thirdly, remember that you can use strongTypes to validate the input parameters of your policy.

And lastly, don’t forget to specify an ‘apiVersion’ for ‘Microsoft.Authorization/policyDefinitions’ resource provider in your template. This property is not required in the bare ‘azurepolicy.json’ format, but it is needed for Azure Resource Manager to ‘talk’ to a specific API version.

A sample Azure Policy definition in an ARM template:

How to define policy assignments in ARM templates

If you were able to define your Azure Policy definition in an ARM template and successfully deploy it, then creating a policy assignment will be a piece of cake. There is no need to use escape characters as for policy definitions – policy assignments can be treated as regular ARM resources. However, to pass the policy parameters, you should define them as an object input both in the template and parameter file (see ‘ Use an object as a parameter in an Azure Resource Manager template ’ for details):

Also, there is one important aspect to be aware of. When creating Azure Policy assignments on the portal, you can limit the assignment scope to a specific resource group, which might be especially handy for testing policy effects before deploying it to production. To achieve the same effect in an ARM template, you can you specify ‘scope’ property in the following format:

/subscriptions/<subscription_id>/resourceGroups/<resourcegroup_name>

and stumble at the following non-descriptive error:

“The policy assignment <policy_definition_name> create request is invalid. Policy assignment scope ‘/subscriptions/<subscription_id>/resourceGroups/<resourcegroup_name>’ must match the scope specified on the Uri ‘/subscriptions/<subscription_id>’.”

If you expand the scope back to the subscription level, the deployment completes without errors.

So, the trick here is to:

  • use a regular deployment schema like ‘ https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#’ ,
  • deploy the ARM template with policy assignment with ‘New-AzResourceGroupDeployment’ cmdlet when scoping for a specific resource group and ‘New-AzDeployment’ when targeting a subscription.

In terms of automation, you can create a single unified deployment template that takes policy definition and its required parameters as inputs and separate parameter files for each policy assignment:

Deployment scripts for Azure Policy definitions and assignments

Now, when you have your ARM templates for policy definitions and assignments ready, it is time to deploy them.

Even though it is possible to define Azure Policy definitions and assignments in the same template file , I prefer to make the deployment a two-step process: deploy policy definitions first, then create assignments for them. The reason for that is flexibility. I create a policy definition on the subscription level but want to create an assignment for it limited to a resource group.

If you structure your repository for policy definitions according to the official recommendations , you might use the following Azure PowerShell script to automate their deployment:

Regarding the deploying templates with policy assignment, you might consider a more dynamic approach:

Depending on the environment you are creating Azure Policy assignments in, you can construct input parameters for the sample ARM template mentioned in the previous section on the fly. The Azure PowerShell deployment cmdlets can take hash tables as template parameter inputs, so you can specify your environment-specific parameters as Azure DevOps pipeline variables and add them during the deployment. Doing so can help you to reduce the number of duplicate parameter files for different environments in your repository.

Have you tried to create a deployment pipeline for Azure Policies? Share your experience in the comments!

Written by:

Andrew Matveychuk

Andrew Matveychuk

Member discussion:.

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 policy definition and assignment

How to deploy Azure Policy with Bicep?

Table of contents:.

Azure Policy is the way to enforce company’s standards and settle compliance properly at-scale. While it’s possible to do portal clickOps in small environments with little requirements, I found it’s error prone and cumbersome to deal with in anything that is bigger than just a personal Azure tenant and a demo subscription in it. :) In this article I want to walk through different aspects of policies, provide simple examples of deploying policies as code (Azure Bicep) and outline several resources that I used along the way in my journey. I highly recommend the following video (taken from here ) to get started with policies:

To settle everything properly at-scale the best way to move forward (IMHO) is to put it in code and use git as a single source of truth, have the ability to trace back to any particul change (that might cause an issue or for audit purposes) and of course for collaboration purposes between members of the team. There are multiple options for SCM, but if you ask my preference I’d mention GitLab and Azure DevOps ( Repo ).

Let’s take a look what elements make policy work in Azure.

Policy definition #

Policy definition , as the name suggests, is the one that makes up a policy. There are builtin (or this repo ) and custom policy definitions (the ones we craft ourselves). An example of a custom policy definition would be:

Each policy goes to separate json file and stored in git. This is a policy with audit effect, and it evaluates existence of a tag (if resource’s tag is missing this policy is not compliant). The policy added to the portal ends up in the list of definitions (custom):

Azure Policy - Definition

To create such policy using Bicep (actually I can put multiple in that array) and loop :

For the builtin policy definition we just need it’s ID which is formed like this: /providers/Microsoft.Authorization/policyDefinitions/<GUID> . This is needed when a policy definition needs to be added to policy initiative or assigned directly.

Azure Policy - builtin

Policy assignment #

Definition does not have any influence on our resources. What makes a difference is a policy assignment .

NB! policyAssignment’s name has to be >64 length and uniq. And policyDefinitionId has to be formed like: /providers/Microsoft.Authorization/policyDefinitions/<GUID> (by the way builtin policyDefinitionId can be specified as well for assignment). Parameters are being passed in exactly the same form as they are required by the policy:

Policy initiative #

We can assign individual definitions or group multiple definitions to make policy initiative (also known as policy set) and assign initiatives to required scope. Resource format is outlined here .

Role assignment #

Some policies (with deployIfNotExists and modify effect) require managed identity in order to make a change. This is done with a role assignment of that managed identity to a particular scope. Let’s assume we have the following policy to enable Microsoft Cloud Defender on all subscriptions:

… nah, just a long one. It includes a roleDefinitionIds array with a single item pointing to resource definition with GUID: fb1c8493-542b-48eb-b624-b4c8fea62acd . This is Security Admin builtin role required for enabling MCD on subscription (check description from the doc: This permission allows to view and update permissions for Microsoft Defender for Cloud. Same permissions as the Security Reader role and can also update the security policy and dismiss alerts and recommendations ). This role has to be given to the service principal that is being generated during policy assignment.

Last but not least there is a policy exemption resource (which is an extension resource, means that we can apply this to another resource) to exclude a defined scope from an effect of the policy (an example use case would be: with the policy definition above we can require a given tag from every resource within our tenant, but we want to exclude a certain resource group or subscription from this list, so this is where we use policy exemption).

Okay the list of all Microsoft.Authorization provider resources required for policies:

  • policyDefinitions
  • policySetDefinitions
  • policyAssignments
  • roleAssignments
  • policyExemptions

Now the next step is to put this together. Review the following folder structure:

Policy as code #

Let’s take a look at the following main.bicep :

Each definition is in a json file and is loaded with Bicep’s loadTextContent function into an array as an object. Since each element of the array is being loaded as an json object we can work with it accordingly by calling every single attribute like this (for example we need to access description attribute of a policy we do it the following way: policy.policyDefinition.properties.description . Along with policy definition we define some other things that can be helpful for us during creation and assignment of the policy. I chose the following:

  • name - name of the policy (typically I use it for deployment name and, sometimes, uniqueString or guid functions with given value of name combining with some “salt” like environment name to make it really uniq for definition or assignment name). NB! Policy definition name requires GUID format!
  • parameters - they are either defaultValues from the definition or values for parameters
  • scopes - to change the scope of definition creation or assignment (this can be useful if we deploy everything at once and create deployment under the scope of, for example, tenant/root management group)

Policy deployment

While the loop through the policies for the policyDefinition is clear I might need to explain the reason for calling the module for policyAssignment . Since we want scopes (plural) for the policy assignment I need a nested loop. I’ve been looking into this for a while and based on this ended up using modules (sometimes submodules) if need another nested loop.

and then from the wrapper.bicep we call the actual role and policy assignment:

How to deploy #

I prefer to use the same code base, but separate environments via parameters. Parameters can be defined via parameters file or via environment variables (i.e. from CICD tool). Some of my policies accept parameters (default values will be overwritten in this case). Example of parameters file:

Now it’s easy to deploy using azure CLI like this:

There is one important caveat. Using deployment with anything above group scope deployment does not allow the use --mode=Complete . This means I can’t destroy this and have to come up with some creative ideas … good news, I am not alone.

I wonder if it's only me desperately need --mode=Complete flag for everything above resource group deployment (az deployment sub/mg etc..) ? #Azure #BicepLang — Evgeny Rudinsky 🐧 (@evgenyrudinsky) September 15, 2022

I have not worked with deploymentStack yet, but this seems to be exactly what I am missing (may be you as well :). You can watch this video to learn more about deployment stacks:

Now that we have policies and managed identity assigned it’s time to review …

Azure Policy - compliance

If you liked this article, go ahead fork this repo and enjoy crafting policies in Azure! 🧶

Resources #

  • What is Azure Policy?
  • Azure Landing Zones with Bicep
  • Policy as code repo
  • AzAdvertizer

Related Posts

How to build and deploy to azure with gitlab.

In this short post you’ll find how to prepare your GitLab to deploy to Azure.

Service principal #

Generate Service Principal (aka App Registration) using azure CLI (either builtin shell or local …

Azure resource governance with project Bicep and template specs

Last week I was setting up a static web site using Azure DevOps and Bicep consuming templates from git. This approach might not be the best option for a large environment with multiple teams as …

Static web site on Azure with Azure DevOps and Bicep

In this sprint I’ll be setting up landing page (aka comming soon page or pre-launch page … static web site using Azure to be precise). The purpose of the exercise is to learn …

Authenticate With Azure Container Registry From Azure Kubernetes Service

As an engineer I want to pull container images that are part of my pods’ deployments to Azure Kubernetes Service (further - AKS) from private container registry Azure Container Registry (further …

Build and release Docker Compose using Azure DevOps

I’ve been fighting a bit with some of the Azure DevOps pipeline tasks trying to configure end-to-end solution for one of my side project. It is based on a good old Docker Compose and I am pretty …

US judiciary says courts have discretion to adopt 'judge shopping' policy

A Lady Justice statue is seen at the Delaware Supreme Court in Dover, Delaware

  • United States of America Follow

Jumpstart your morning with the latest legal news delivered straight to your inbox from The Daily Docket newsletter. Sign up here.

Reporting by Nate Raymond in Boston, Editing by Alexia Garamfalvi and Rosalba O'Brien

Our Standards: The Thomson Reuters Trust Principles. , opens new tab

azure policy definition and assignment

Thomson Reuters

Nate Raymond reports on the federal judiciary and litigation. He can be reached at [email protected].

Read Next / Editor's Picks

Car manufacturers display their wares on the show floor of the North American International Auto Show in Detroit

A federal judge on Friday temporarily blocked a land swap needed before developers can build a major clean-energy transmission line through a Mississippi River wildlife refuge, according to attorneys involved in the case.

LSEG Workspace

Industry Insight

azure policy definition and assignment

Mike Scarcella, David Thomas

azure policy definition and assignment

Karen Sloan

azure policy definition and assignment

Henry Engler

azure policy definition and assignment

Diana Novak Jones

IMAGES

  1. Azure Policy 101

    azure policy definition and assignment

  2. Azure policy

    azure policy definition and assignment

  3. Azure Policy

    azure policy definition and assignment

  4. Quickstart: New policy assignment with portal

    azure policy definition and assignment

  5. Keep control of your Azure environment with Azure Policy

    azure policy definition and assignment

  6. Keep control of your Azure environment with Azure Policy

    azure policy definition and assignment

VIDEO

  1. Azure Policy

  2. Azure Policy

  3. In-Depth Azure Subscriptions,Tenant,ResourceGroup,ResourceManager,Azure Policy,Cost,Budget (Part-2)

  4. In-Depth Azure Subscriptions,Tenant,ResourceGroup,ResourceManager,Azure Policy,Cost,Budget (Part-1)

  5. Azure Policy

  6. Manage Azure Subscription and Governance using Azure Policy

COMMENTS

  1. Details of the policy assignment structure

    In this article. Policy assignments are used by Azure Policy to define which resources are assigned which policies or initiatives. The policy assignment can determine the values of parameters for that group of resources at assignment time, making it possible to reuse policy definitions that address the same resource properties with different needs for compliance.

  2. Regain Control of Azure Resources with Azure Policy

    Within the Azure Portal, search for Policy. Click on Remediation on the left-hand side. Click on a policy that is of the type of deployIfNotExists an d has non-compliant resources. Filter the resources to be re-mediated on the New remediation task page to limit what the task applies to. Click on Remediate to start the task itself.

  3. Azure Policy Recommended Practices

    Custom Policy/Initiative Definitions and Policy Assignments need to be deployed at a scope. Custom definitions should always be deployed at the top Management Group (MG) in each tenant. ... Policy Assignments are deployed to prevent rogue subscriptions from bypassing your security controls enforcement with Azure Policy. Policy Assignments.

  4. Azure Policy: Starter Guide

    A common use case is to duplicate a built-in policy logic in your custom definition completely. The reason for that is the way how Azure Policy engine handles updates to the existing definitions. When you update a definition, all existing policy assignment of it will automatically be using the new definition.

  5. Azure Policy Explained with Example [Step-by-Step]

    Policy assignment: We would assign this policy at the scope of the resource group under which the VMs would be created. ... Step 2: Create Azure policy definition. Towards the left side of the page, we have a section named authoring and within this section, there is a tab called definitions. Click on this tab to create a policy definition or ...

  6. Walkthrough using Azure Policy to audit and enforce compliance

    A policy assignment applies the policy to all resources within the scope. For example, if the policy. For more information, see: ... See Create a policy definition with Azure CLI. The following code creates a policy definition and saves the policy definition to a subscription. It does not assign the policy to the subscription.

  7. Policy Assignments

    Policies with a DeployIfNotExists or Modify effect need a Managed Identity (MI) and role assignments to execute remediation task. EPAC calculates the necessary role assignments based on the roleDefinitionIds in the Policy definition. By default EPAC uses a system-assigned Manged Identity.

  8. Azure Policy Initiatives vs Azure Policies: When should I use one over

    To summarize, Azure policy is basically 3 components; policy definition , assignment and parameters. Policy definition is the conditions which you want controlled. There are built in definitions such as controlling what type of resources can be deployed to enforcing the use of tags on all resources. Policy assignment is the scope of what the ...

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

  10. Azure policy

    An assignment is a policy definition or initiative that has been assigned to a specific scope. This scope could range from a management group to an individual resource. The term scope refers to all the resources, resource groups, subscriptions, or management groups that the definition is assigned to. Assignments are inherited by all child resources.

  11. Azure Policy Definition Assignment Exemptions

    Watch this tutorial for every step for Azure policy management. Create custom policy, create assignments, set exemptions and sample custom policy. Policy co...

  12. Manage Azure Policy with Terraform

    Brendan Thompson • 17 November 2022 • 17 min read. 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.

  13. Manage Azure Policy using PowerShell

    Policy assignments are used to declare where the policy definitions are applied. You can create a policy assignment by linking an existing policy definition and specifying the target scope. In this way, the same policy definition object can be reused with another policy assignment.

  14. How to deploy Azure Policies with ARM templates

    Even though it is possible to define Azure Policy definitions and assignments in the same template file, I prefer to make the deployment a two-step process: deploy policy definitions first, then create assignments for them. The reason for that is flexibility. I create a policy definition on the subscription level but want to create an ...

  15. Deploy and Assign Azure Policy via Azure DevOps Pipelines

    Assign Resource Policy Contributor. By default, Azure DevOps grants 'Contributor' permissions for the service principals to authenticate pipelines to Azure, which are just fine for the majority of regular deployments.However, the 'Contributor' built-in role doesn't have permission to create and manage Azure Policy definitions.In this case, you need to assign the 'Resource Policy ...

  16. Azure Policy Policy Assignment

    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.

  17. How to deploy Azure Policy with Bicep?

    Policy initiative #. We can assign individual definitions or group multiple definitions to make policy initiative (also known as policy set) and assign initiatives to required scope. Resource format is outlined here.. Role assignment #. Some policies (with deployIfNotExists and modify effect) require managed identity in order to make a change. This is done with a role assignment of that ...

  18. US judiciary says courts have discretion to adopt 'judge shopping' policy

    The U.S. federal judiciary on Friday made clear that trial courts had discretion to decide how to implement a policy it adopted earlier in the week to curtail the practice of "judge shopping ...