This browser is no longer supported.

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

Quickstart: Create a policy assignment to identify non-compliant resources by using a Bicep file

  • 7 contributors

In this quickstart, you use a Bicep file to create a policy assignment that validates resource's compliance with an Azure policy. The policy is assigned to a resource group and audits virtual machines that don't use managed disks. After you create the policy assignment, you identify non-compliant virtual machines.

Bicep is a domain-specific language (DSL) that uses declarative syntax to deploy Azure resources. It provides concise syntax, reliable type safety, and support for code reuse. Bicep offers the best authoring experience for your infrastructure-as-code solutions in Azure.

Prerequisites

  • If you don't have an Azure account, create a free account before you begin.
  • Azure PowerShell or Azure CLI .
  • Visual Studio Code and the Bicep extension for Visual Studio Code .
  • Microsoft.PolicyInsights must be registered in your Azure subscription. To register a resource provider, you must have permission to register resource providers. That permission is included in the Contributor and Owner roles.
  • A resource group with at least one virtual machine that doesn't use managed disks.

Review the Bicep file

The Bicep file creates a policy assignment for a resource group scope and assigns the built-in policy definition Audit VMs that do not use managed disks .

Create the following Bicep file as policy-assignment.bicep .

  • Open Visual Studio Code and select File > New Text File .
  • Copy and paste the Bicep file into Visual Studio Code.
  • Select File > Save and use the filename policy-assignment.bicep .

The resource type defined in the Bicep file is Microsoft.Authorization/policyAssignments .

The Bicep file uses three parameters to deploy the policy assignment:

  • policyAssignmentName creates the policy assignment named audit-vm-managed-disks .
  • policyDefinitionID uses the ID of the built-in policy definition. For reference, the commands to get the ID are in the section to deploy the template.
  • policyDisplayName creates a display name that's visible in Azure portal.

For more information about Bicep files:

  • To find more Bicep samples, go to Browse code samples .
  • To learn more about template reference's for deployments, go to Azure template reference .
  • To learn how to develop Bicep files, go to Bicep documentation .
  • To learn about subscription-level deployments, go to Subscription deployments with Bicep files .

Deploy the Bicep file

You can deploy the Bicep file with Azure PowerShell or Azure CLI.

From a Visual Studio Code terminal session, connect to Azure. If you have more than one subscription, run the commands to set context to your subscription. Replace <subscriptionID> with your Azure subscription ID.

You can verify if Microsoft.PolicyInsights is registered. If it isn't, you can run a command to register the resource provider.

For more information, go to Get-AzResourceProvider and Register-AzResourceProvider .

The Azure CLI commands use a backslash ( \ ) for line continuation to improve readability. For more information, go to az provider .

The following commands display the policyDefinitionID parameter's value:

The following commands deploy the policy definition to your resource group. Replace <resourceGroupName> with your resource group name:

The $rg variable stores properties for the resource group. The $deployparms variable uses splatting to create parameter values and improve readability. The New-AzResourceGroupDeployment command uses the parameter values defined in the $deployparms variable.

  • Name is the deployment name displayed in the output and in Azure for the resource group's deployments.
  • ResourceGroupName uses the $rg.ResourceGroupName property to get the name of your resource group where the policy is assigned.
  • TemplateFile specifies the Bicep file's name and location on your local computer.

The rgname variable uses an expression to get your resource group's name used in the deployment command.

  • name is the deployment name displayed in the output and in Azure for the resource group's deployments.
  • resource-group is the name of your resource group where the policy is assigned.
  • template-file specifies the Bicep file's name and location on your local computer.

You can verify the policy assignment's deployment with the following command:

The command uses the $rg.ResourceId property to get the resource group's ID.

For more information, go to Get-AzPolicyAssignment .

The rgid variable uses an expression to get the resource group's ID used to show the policy assignment.

The output is verbose but resembles the following example:

For more information, go to az policy assignment .

Identify non-compliant resources

After the policy assignment is deployed, virtual machines that are deployed to the resource group are audited for compliance with the managed disk policy.

The compliance state for a new policy assignment takes a few minutes to become active and provide results about the policy's state.

The $complianceparms variable creates parameter values used in the Get-AzPolicyState command.

  • ResourceGroupName gets the resource group name from the $rg.ResourceGroupName property.
  • PolicyAssignmentName specifies the name used when the policy assignment was created.
  • Filter uses an expression to find resources that aren't compliant with the policy assignment.

Your results resemble the following example and ComplianceState shows NonCompliant :

For more information, go to Get-AzPolicyState .

The policyid variable uses an expression to get the policy assignment's ID. The filter parameter limits the output to non-compliant resources.

The az policy state list output is verbose, but for this article the complianceState shows NonCompliant .

For more information, go to az policy state .

Clean up resources

To sign out of your Azure PowerShell session:

To sign out of your Azure CLI session:

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

To learn more about how to assign policies that validate resource compliance, continue to the tutorial.

Tutorial: Create and manage policies to enforce compliance

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

How to deploy Azure Policy with Bicep

It has been a while since I wrote about Azure Policy last time, plus recently there was a lot of hype around Bicep , so I decided to give it a try and shed some light on creating and deploying custom Azure policies with that new language.

Prerequisites

I assume that you are already familiar with what Azure Policy is and how it works. If you are new to that really helpful and often underrated technology, I suggest checking out my Azure Policy Starter Guide .

Also, I recommend that you read through official Bicep documentation to get some notion about this new domain-specific language, which Microsoft promotes as an abstraction over ARM templates and Azure Resource Manager.

Bicep basics for Azure Policy

Like JSON-based ARM templates, Bicep is a declarative language that allows you to define desired Azure resource configuration and let Azure Resource Manager do its job of provisioning it. Initially, you had to compile a Bicep file into a regular ARM template to deploy your configuration. However, it is not the case anymore as both Azure CLI and Azure PowerShell now support deploying Bicep definitions . Note that input parameters for Bicep definitions are still come in the same format as for old-school ARM templates .

Apart from that, as we work with the same Azure service, you should expect that all Azure Policy specifics are applicable regardless of the language you use to define your configurations. So, all the tips and tricks you learned about creating, deploying and evaluating Azure Policy are still relevant.

Speaking of Bicep, you can define a single policy as well as a policy initiative, aka policy set, along with their assignment to a specific scope using the Bicep resource primitive . For example, to create a custom Azure Policy, you can define the following resource in your Bicep file:

As you might notice from that sample, in order for some policy-specific syntax to be valid, you should use backslash as an escape character for single quotation marks. Also, you shouldn’t use an additional forward square bracket in the expressions as it will be automatically added to the JSON during the Bicep build.

In the same manner, you can define your custom policy initiative:

As policy initiatives don’t define any rules, they use the ‘ policyDefinitions’ keyword to reference existing policy definitions.

Policy and policy initiative assignments are also pretty straightforward and defined as yet another resource:

For complete definitions, look into bicep samples in my Azure Policy repository on GitHub . Besides, the Bicep product team and the community regularly update and create new sample Bicep definitions for various Azure services, including Azure Policy, so I suggest checking them for additional cases.

Advanced technics

Now, when the basics are clear, let’s look into more advanced topics.

First of all, remember that you can deploy your custom Azure policy definitions at the subscription and management group levels only . At the same time, Azure Policy assignments can be created at the management group, subscription, and resource group levels. Also, keep in mind that the deployment scope of a policy, in turn, effectively limits its assignment scope .

The Bicep VS Code extension will warn you about the resources that cannot be deployed to the target scope, and the Bicep compiler will produce the compilation error.

In terms of Bicep definitions, you can scope your deployments by using the ‘ targetScope ’ keyword. Depending on that scope, a bicep file will be compiled into an ARM template using the corresponding deployment schema.

Using different deployment scopes will also impact the way you reference other resources in your configuration. If it is a new resource defined in the same Bicep file, then using standard syntax like ‘ resourceSymbolicName.Id ’ should be enough. However, when you need to reference an existing resource , e.g., a policy definition in policy initiative, first you should correctly define that resource in your Bicep file, and second, you should use the correct reference function:

  • for Azure Policy definitions deployed at the subscription level use the ‘ subscriptionResourceId ’ function;
  • for Azure Policy definitions deployed at the management group level use the ‘ extensionResourceId ’ function as custom policy definitions are implemented as resource extensions .
If you want to assign your policy at the tenant level, you should use the Tenant Root Group for that.

For example, to reference your existing policy definition deployed at the subscription level in a policy initiative, you can define it as the following:

Same referencing but at the management group level can be accomplished with the following syntax:

I don’t cover the Azure Policy exemptions feature here as it’s currently in preview and might change in the future.

Current drawbacks

Unfortunately, authoring Azure Policies with Bicep is still far from ideal. So, here are a few things that are not specifically related to Azure Policy, but rather Bicep language-generic features or their absence that annoyed me.

As I already mentioned, referencing policies from policy initiatives is a bit complicated and non-intuitive as you must be explicit about your reference scopes and always keep that nuance in mind. On a larger scale, when you have dozens of definitions that are defined in separate files and need to be deployed and assigned at different scopes, the new authoring experience is quite painful.

The next thing, which adds up to the negative authoring and debugging experience, is the lack of IntelliSense support for Azure Policy internal logic defined in Bicep files . What is more, the syntax highlighting for Bicep-defined Azure Policy rules in VS Code is also very limited. Apart from that, I was also unpleasantly surprised that, in contrast to the ARM template authoring experience, Bicep will not warn you about unused parameters or variables you have in your files.

Lastly, the way you currently define human-readable names and descriptions for policy parameters using the Bicep parameter decorators looks a bit awkward for me:

Why not provide the same simplified syntax for the ‘name’ metadata tag for the ‘description’ ?

Fortunately, the Bicep product team makes good progress in implementing new Bicep features and providing the community with simpler and better options for defining Azure infrastructure as code, and I’m impatiently looking forward to new Bicep releases .

If you were writing lots of ARM templates and haven’t tried Bicep yet, I certainly recommend you check it out and post your impressions in the comments below!

Written by:

Andrew Matveychuk

Andrew Matveychuk

Member discussion:.

DEV Community

DEV Community

Olivier Miossec

Posted on Oct 11, 2022

Bicep and Azure Policy: Create and manage custom Azure Policies

This is the second post about Azure Policy. It will focus on policy definition and how to manage your custom policies with Azure Bicep and PowerShell.

Azure provides several policy definitions that cover a wide range of situations and governance strategies. But sometimes you need policies that cover particular needs and requirements. You will need to write your own custom Azure Policy.

An Azure Policy is a JSON file with several properties.

  • A name (limited to 64 characters)
  • A display Name (limited to 128 characters)
  • A description
  • The mode of the policy, all (for all resources) or indexed (only resources that support tags and location)
  • Metadata (version, category, …)
  • A Parameters bloc
  • Policy Rule bloc including the evaluation to filter target resources and the effect
  • A type, as we are creating a custom policy, it will be custom

In Bicep we can retrieve these policy elements plus the name of the policy (that will form the policy ID with de deployment scope)

Like Policy Initiatives, Policy definitions are deployed at a given scope, management group, or subscription.

Now imagine that your task is to deploy several policy definitions and update some existing ones. How can you automate this task using PowerShell and Bicep? You may not have to manage only one policy but several.

A Policy definition is a JSON file, it can easily be read by a PowerShell script. If you put all the policy definition JSON files into a single folder, PowerShell can parse them and extract all the information needed to deploy the policy definition.

A bicep file is needed to deploy policy definitions.

As with Policy initiative the target scope is a management group but it could be change to subscription. The definitionName and defintionDisplayName parameters have limited length, so control is needed to avoid deployment errors. Policy mode can only have two values indexed (for resources supporting tags) or all (all resource types). The policyMode parameter restricts the choice of these two values.

For metadata, parameters, and policyRule, bicep only accepts JSON objects while PowerShell can only provide a string representation of a JSON object. The bicep function json() is here to translate a string to a corresponding JSON object.

The PowerShell script needs to parse any JSON file in a given folder and extract displayName, Description, and mode as string and parameters, metadata, and policyRule as JSON objects. Then it can run the bicep deployment. The name of the policy definition is extracted from the name of the JSON file

Next post we will talk about assignment.

You can find the related PwSh/Bicep code here

Top comments (0)

pic

Templates let you quickly answer FAQs or store snippets for re-use.

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink .

Hide child comments as well

For further actions, you may consider blocking this person and/or reporting abuse

mdarifulhaque profile image

752. Open the Lock

MD ARIFUL HAQUE - Apr 22

vietdt89 profile image

Delegation is the last thing managers should do

vietdt89 - Apr 23

jenwikehuger profile image

COO of open source tool chats about his POV

Jen Wike Huger - Apr 22

musaaj profile image

Basic Concepts in Programming

Musa Ibrahim - Apr 22

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

This browser is no longer supported.

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

Quickstart: Create a policy assignment to identify non-compliant resources by using a Bicep file

  • 7 contributors

In this quickstart, you use a Bicep file to create a policy assignment that validates resource's compliance with an Azure policy. The policy is assigned to a resource group and audits virtual machines that don't use managed disks. After you create the policy assignment, you identify non-compliant virtual machines.

Bicep is a domain-specific language (DSL) that uses declarative syntax to deploy Azure resources. It provides concise syntax, reliable type safety, and support for code reuse. Bicep offers the best authoring experience for your infrastructure-as-code solutions in Azure.

Prerequisites

  • If you don't have an Azure account, create a free account before you begin.
  • Azure PowerShell or Azure CLI .
  • Visual Studio Code and the Bicep extension for Visual Studio Code .
  • Microsoft.PolicyInsights must be registered in your Azure subscription. To register a resource provider, you must have permission to register resource providers. That permission is included in the Contributor and Owner roles.
  • A resource group with at least one virtual machine that doesn't use managed disks.

Review the Bicep file

The Bicep file creates a policy assignment for a resource group scope and assigns the built-in policy definition Audit VMs that do not use managed disks .

Create the following Bicep file as policy-assignment.bicep .

  • Open Visual Studio Code and select File > New Text File .
  • Copy and paste the Bicep file into Visual Studio Code.
  • Select File > Save and use the filename policy-assignment.bicep .

The resource type defined in the Bicep file is Microsoft.Authorization/policyAssignments .

The Bicep file uses three parameters to deploy the policy assignment:

  • policyAssignmentName creates the policy assignment named audit-vm-managed-disks .
  • policyDefinitionID uses the ID of the built-in policy definition. For reference, the commands to get the ID are in the section to deploy the template.
  • policyDisplayName creates a display name that's visible in Azure portal.

For more information about Bicep files:

  • To find more Bicep samples, go to Browse code samples .
  • To learn more about template reference's for deployments, go to Azure template reference .
  • To learn how to develop Bicep files, go to Bicep documentation .
  • To learn about subscription-level deployments, go to Subscription deployments with Bicep files .

Deploy the Bicep file

You can deploy the Bicep file with Azure PowerShell or Azure CLI.

From a Visual Studio Code terminal session, connect to Azure. If you have more than one subscription, run the commands to set context to your subscription. Replace <subscriptionID> with your Azure subscription ID.

You can verify if Microsoft.PolicyInsights is registered. If it isn't, you can run a command to register the resource provider.

For more information, go to Get-AzResourceProvider and Register-AzResourceProvider .

The Azure CLI commands use a backslash ( \ ) for line continuation to improve readability. For more information, go to az provider .

The following commands display the policyDefinitionID parameter's value:

The following commands deploy the policy definition to your resource group. Replace <resourceGroupName> with your resource group name:

The $rg variable stores properties for the resource group. The $deployparms variable uses splatting to create parameter values and improve readability. The New-AzResourceGroupDeployment command uses the parameter values defined in the $deployparms variable.

  • Name is the deployment name displayed in the output and in Azure for the resource group's deployments.
  • ResourceGroupName uses the $rg.ResourceGroupName property to get the name of your resource group where the policy is assigned.
  • TemplateFile specifies the Bicep file's name and location on your local computer.

The rgname variable uses an expression to get your resource group's name used in the deployment command.

  • name is the deployment name displayed in the output and in Azure for the resource group's deployments.
  • resource-group is the name of your resource group where the policy is assigned.
  • template-file specifies the Bicep file's name and location on your local computer.

You can verify the policy assignment's deployment with the following command:

The command uses the $rg.ResourceId property to get the resource group's ID.

For more information, go to Get-AzPolicyAssignment .

The rgid variable uses an expression to get the resource group's ID used to show the policy assignment.

The output is verbose but resembles the following example:

For more information, go to az policy assignment .

Identify non-compliant resources

After the policy assignment is deployed, virtual machines that are deployed to the resource group are audited for compliance with the managed disk policy.

The compliance state for a new policy assignment takes a few minutes to become active and provide results about the policy's state.

The $complianceparms variable creates parameter values used in the Get-AzPolicyState command.

  • ResourceGroupName gets the resource group name from the $rg.ResourceGroupName property.
  • PolicyAssignmentName specifies the name used when the policy assignment was created.
  • Filter uses an expression to find resources that aren't compliant with the policy assignment.

Your results resemble the following example and ComplianceState shows NonCompliant :

For more information, go to Get-AzPolicyState .

The policyid variable uses an expression to get the policy assignment's ID. The filter parameter limits the output to non-compliant resources.

The az policy state list output is verbose, but for this article the complianceState shows NonCompliant .

For more information, go to az policy state .

Clean up resources

To sign out of your Azure PowerShell session:

To sign out of your Azure CLI session:

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

To learn more about how to assign policies that validate resource compliance, continue to the tutorial.

Tutorial: Create and manage policies to enforce compliance

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

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 …

Maik van der Gaag

Maik van der Gaag

I am Microsoft Azure MVP , Speaker and Father .

  • Schiedam, The Netherlands
  • Custom Social Profile Link

Building your Azure Policies - Part 1

11 minute read

Azure Policy is a way of enforcing standards and guardrails and assessing resource compliance. In Azure, the compliance dashboard offers an aggregated view to validate the state of the platform with additional options to see the resources that are not compliant.

Azure Policy overview

An Azure Policy itself evaluates resources within Azure based on the rules you specify. The rules are defined in a JSON format and called policy definitions, and policies can also be grouped into so-called policy initiatives. The policies themself can be deployed on several scopes that, of course, keep the standard Azure inheritance in place. The scopes it can be deployed to are:

  • Management groups
  • Subscriptions
  • Resource Groups

If there are resources at a scope that can not comply with the guardrails/standards, these resources can be excluded by defining an exclusion on the policy assignment.

The Azure Portal offers a lot of policies OOTB, but in many situations, you want to create your own. This is when the policy rules come in.

Policy Rule Effects

As mentioned above, Azure Policies have rules that have specific effects. At the time of writing this article, the following effects are supported:

  • Append: Append additonal information / fields on the resource. Like appending additional rows to an firewall array.
  • Audit: Log specific information as warning in the activity log.
  • AuditIfNotExists: Audit resource when specific configuration is missing and have gone through the if condition of the rule.
  • Deny: Deny creation when some configuration is missing or the configuration is not allowed by the standards.
  • DeployIfNotExists: Deploy resources when not configured. This will trigger an template deployment.
  • Disabled: Disabled effect means that the policy itself is disabled.
  • Modify: Modify an existing deployment to fit the rules specified. This is mainly used to do CRUD operations on properties and tags for subscriptions, resource groups and resources.

When working with policies and custom policies, it is good to know the order of the evaluation process. The below-ordered list shows this:

  • Append and Modify
  • AuditIfNotExists and DeployIfNotExists.

When are policies evaluated

Policies are evaluated on multiple occasions and, depending on the way used, will show results in around 30 minutes:

  • Manual / On-demand
  • At policy assignment
  • When changing a policy assignment
  • When exemptions are created or updated.
  • Default evaluation cycle (once every 24 hours)
  • Resource creation or update

For more information about policies, read the Azure Policy documentation .

Creating your own Policy

Creating your policy is done using Bicep or writing the definition in JSON. With the use of Bicep, you can use the standard way of deploying the policies.

We will work on a policy that solves the following problem for this series of posts.

As a administrator I want to make sure that resources that are tagged as production resources are not able to be changed. Unless specific actions are taken.

The above problem can be solved by combining Azure Policies with Azure Resource Locks, especially the read-only lock deployed with the "DeployIfNotExists" effect.

The first part of the policy in Bicep contains the default information, and the policy itself is specified in the properties property. Let's discuss that in parts.

Policy Metadata

The first section is the metadata. The policy metadata contains all the information about the policy that defines the name, description, category, and everything else. With the help of the 'securityCenter' part, you can specify additional feedback for Azure Security Center.

For our use case, these properties are filled with information to identify the policy correctly.

Policy Parameters

The second part we will discuss is the parameters. Within the policy parameter section, parameters for the policy itself can be defined. Using this adds the ability to supply information when assigning the policies.

For this use case, we will define two parameters. The tag name so that we can specify against what tag we want to check within the rule and tag value used to check for the rule to be successful.

Policy Rule

The last part is the most important. This section contains the rule, which is the real heart of the policy. This section defines where to check against and what action (effect) is handled.

In the above rule, we do the following: If the field type is of the type resource group and field tags contains a tag with the specified tag name (the parameter) with the value (the parameter) that is configured, then deploy the specified deployment template, which includes the read-only lock.

The deployment part of the rule contains an ARM template for the deployment.

Remediation

In Azure, you can also remediate existing resources. In our example, remediating a resource group means that the remediation is done when instructing Azure Policy to remediate the resource.

Azure Policy in Bicep

The complete policy in Bicep looks like the snapshot below.

Deploy the Azure Policy

When the policy is defined in Bicep, it can quickly be deployed with the standard deployment commands on the scope you want. The below snippet shows how to deploy the file on the management group scope.

The definition can also be defined in JSON. When expressed in JSON, the structure is the same. The snipped below shows it defined in JSON.

With the help of the below PowerShell function, the policy definition can be deployed to the Azure Platform.

To be continued

You may also enjoy, getting started with deployment stacks.

7 minute read

Since June this year, a new functionality in public preview called deployment stacks. Deployment stacks are Azure resources that enable you to manage a group...

Verified commits in GitHub

5 minute read

Git commits can be signed by using a GPG key. With this GPG key, you can prove that a specific commit comes from you. Doing this will also add a ‘Verified’ b...

Creating a Logic App API Connection that uses the Managed Identity using Bicep

2 minute read

Logic Apps in Azure provides a platform for building workflows that integrate with various services and APIs. When creating Logic Apps, you must often connec...

“Exposing Azure App Registrations as Secure APIs: A Guide to Authentication with ‘User Assignments Required’ Turned On”

3 minute read

Azure App Registrations are a powerful tool for managing resource access and integrating applications with Microsoft's cloud services. While these registrati...

NielsKok.Tech

A blog about End User Computing (EUC)

policy assignment bicep

Deploy Azure Policy to ManagementGroup with Bicep

I have tinkered with this for a bit. So, I thought let’s share it with the world. This blog is about how to deploy azure policy to a managementgroup using the Bicep language. A management group helps you to assign policy’s to multiple azure subscriptions. Furthermore, new subscriptions can easily be added to the existing management groups. As a result, policy’s are assigned automatically to new subscriptions. Let’s start!

Prerequisites

Optional : Install Visual Studio Code with GIT – Guide for Installation

Azure Powershell Modules – Download link Powershell 7 (recommended) – Download link Bicep compiler/modules – Download link

Management Group creation

Firstly, we need to create a management group. We use powershell to do so. Log on to Azure Powershell with the following code:

After that, run this piece of code to create the management group

As as result, this managementgroup is available:

Deploy Azure Policy to ManagementGroup with Bicep - Management group creation

By default, there are no subscriptions assigned to a management group. We assign the subscriptions later in the process.

Policy assigment via Bicep

We use the bicep language to assign an Azure Policy to the management group. The policy which we use is: ‘audit-vm-manageddisks’ This policy checks whether virtual machines uses managed disks. Managed disks are covered by the 99,95% SLA coverage by Microsoft. So, we need to make sure that our virtual machines use these disks. The syntax of the bicep file looks like this:

Save this file as ‘AzurePolicy.bicep’.

We use the Azure CLI application to deploy this bicep template to Azure. It is fairly simple. Firstly, use this command to logon with the Azure CLI:

After that, use this command to select the right subscription:

Lastly, deploy the bicep template with this code:

This is the result of the template deployment:

Deploy Azure Policy to ManagementGroup with Bicep - Management group assignment

And that is how you deploy Azure Policy to a ManagementGroup with Bicep!

Bicep Template for Policy assignment Other Posts: Azure Logon Subscription Menu Snapshot Managed disk to storage account

Leave a Comment Cancel reply

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

Eldar Borge

All things cloud

Azure Bicep – Tagging Policies

With the recent v0.3 release of Azure Bicep, the language is maturing and becoming a powerful language for declaratively deploying resources to Azure. As of v0.3, it’s fully supported by Microsoft, and they’re rapidly releasing new features and improvements. The 0.4 version of Bicep is estimated to arrive at Microsoft Build, with many exciting new capabilities — including referencing external modules, indexed loops and more.

I’ve created a couple of Azure Policies in Bicep to discover and learn the capabilities of this language, all of which are available in this repository .

The modules consist of three main components; the definition itself, the assignments, and the role assignments for the SystemAssigned identity (if the policy requires permissions to resources).

A Bicep module is a .bicep-file which can be referenced to by another .bicep-file within the same repository . A module starts with defining the parameters which is expected from the consumer of the module (optionally with a default value), and then continues describing the resources.

A policy definition in Bicep is fairly similar to a policy definition in an ARM template, slightly prettified. The example below has the policyRule omitted; the repository has the entire code.

One of the neat features in the latest version of Bicep, is the ability to loop, which is a lot easier to implement in Bicep than with ARM Templates. The above policy definition requires an assignment for every tag, which would be exhausting to implement manually in the portal or by describing each individual assignment with code. Loops in Bicep function like for-each loops, enabling you to loop through an array referencing the respective individual element each iteration.

The role assignments required for each policy assignment can also be created using loops, since Bicep supports referencing an individual object created by a loop with an index. If I wanted to reference the first object created by the loop above, I’d reference inheritTagsFromRG_policyAssignments[0]. To achieve this using loops, create a loop iterating as many times as there are elements in the array, which is calculated by the range between 0 and the length of the array.

To learn more about Bicep, I really recommend their repository . In particular, the docs and the language spec .

Leave a Reply Cancel reply

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

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

Privacy Overview

Global Azure: Policy as Code with Bicep for Enterprise Scale

2 minute read

GlobalAzure2021

Global Azure is a community event about the Microsoft Azure platform. On April 15-17 the Global Azure community goes online to share, learn, and have community Azure fun together.

This year I was fortunate to have a session accepted for Global Azure 2021 titled: Policy as Code with Bicep for Enterprise Scale

Recently I’ve been diving into Microsoft’s new DSL Bicep and as I’m passionate about Azure Policy I thought why not combine both aspects into a session?

Admittedly, I left my sessionize submission very late and probably just scraped in. Even so it was a wonderful surprise to see my session accepted followed by a frantic scramble to prepare my presentation (YT links below) and code which can be found here https://github.com/globalbao/azure-policy-as-code .

Presentation Structure

I structured my presentation into 3x levels so that beginners could start with a small proof of concept deployment and then scale up in complexity and advanced logic as their comfort levels increased with Bicep and Azure Policy.

More experienced users can jump straight to Level 3 and learn/adopt a Policy as Code workflow with Bicep.

Links to skip to specific content levels in the recorded session are included below!

  • Uses built-in policies
  • Uses an initiative and assignment
  • 1x main.bicep
  • Manual CLI deployment

YouTube Video Timestamp 16m 10s

  • Uses built-in policies and custom policies
  • Uses multiple initiatives and assignments
  • Targeting multiple Azure environments
  • Uses parameter files for environment-specfic values passed during deployment

YouTube Video Timestamp 50m 3s

  • Custom policyDefinitionReferenceId for initiatives
  • Custom non-compliance msgs for assignments targeted to the policyDefinitionReferenceId
  • Advanced modules organised per resource type
  • CI/CD workflow automation with GitHub Actions YAML
  • Targeting multiple Azure environments with authentication via GitHub secrets

YouTube Video Timestamp 1h 11m 45s

Finally, I’d like to thank Rahul Nath for reaching out to me prior to the session and helping me out with YouTube streaming/gearing tips. Much appreciated Rahul!

This year’s Global Azure event was the biggest yet with over 560 speakers and 530 sessions from across the world! So a big kudos to the organisers and session reviewers who contributed their time to make this happen!

Looking forward to next year’s Global Azure!

GlobalAzure2021Sessions

Leave a comment

You may also enjoy.

policy assignment bicep

Flexing your Security Governance with Azure Policy as Code

3 minute read

I recently had the pleasure of presenting a livestream session via Microsoft Reactor Sydney on a subject close to my heart.

policy assignment bicep

Talking Azure Policy as Code on CtrlAltAzure podcast

4 minute read

Appearing as a guest on the Ctrl+Alt+Azure podcast to talk Azure Policy as Code with hosts Tobias Zimmergren and Jussi Roine

policy assignment bicep

How to Win vs Azure Policy Non-Compliance

5 minute read

Fixing a design flaw with the existenceCondition for builtin policies

policy assignment bicep

HashiTalks ANZ: DRY Coding with Terraform, CSVs, ForEach

How combining Terraform with CSVs and ForEach we can deploy at scale from large datasets

Tao Yang

I am a Microsoft Azure MVP based in Melbourne, Australia.

  • Custom Social Profile Link

GripMatix

Azure Bicep Modules for Azure Policy Resources

4 minute read

Although I’m a big fan of Microsoft CARML Bicep module repo, and have used many of their modules in my projects, Sometimes I still prefer using the modules I have created myself. I created 3 Bicep modules a while back for Azure Policy Definitions, Initiatives and Assignments. They are all created for management-group scoped deployments because I have not had requirements for subscription scoped deployments to date. I have used these modules in several projects now. I thought I’d share with the community, gives you an alternative to the CARML modules.

You can find the modules coupled with sample templates in my Azure Policy Github repository

Policy Definition Module

Azure policy definitions are written in JSON format. With the Policy Definition module takes a JSON payload as an input and parses it to get all attributes that Bicep requires. When deploying multiple policy definitions in bulk, you can also use the @batchsize decorator to control the concurrent deployments. I was able to use this module to deploy 100+ policy definitions in a single deployment in a timely manner.

For example:

NOTE : This sample template above is located here

Policy Initiative (Policy Set) Module

Similar to the Policy Definition module, the Policy Initiative module can be used together with the loadTextContent() bicep function so you can easily deploy existing Policy initiative definition JSON files.

In this example, I’m deploying a policy initiative defined in the polset-tags.json file. The loadTextContent() function is used to read the JSON file.

In the Policy Initiative definition JSON file, I have defined the member policy location as below:

"policyDefinitionId": "{policyLocationResourceId}/providers/Microsoft.Authorization/policyDefinitions/pol-inherit-tags-from-sub",

The Bicep template uses the replace() function to replace the {policyLocationResourceId} placeholder with the management group Id (in this example, assuming the member policies are located at the same management group as the policy initiative).

NOTE : The sample template above is located here

Policy Assignment Module

The policy assignment module is used to assign policy definitions or policy initiatives to a management group scope. It can also create role assignments for Policy Assignments Managed Identity, which is required for policies with DeployIfNotExists and Modify effects.

This sample bicep template requires parameter inputs, which can be defined in a parameter file. It adds the assignedBy metadata to existing assignment metadata, and similar to the Policy Initiative sample, it replaces the {policyLocationResourceId} token with the definitionSourceManagementGroupId parameter.

I was able to use these modules in Azure DevOps pipelines to deploy policy resources in scale. Since Policy definitions will need to be in place before creating Policy Initiatives and assignments, the order of deployments would be:

  • Deploy Policy Definitions
  • Deploy Policy Initiatives
  • Deploy Policy Assignments
  • Optionally create policy remediation tasks to remediate non-compliant existing resources

Leave a comment

You may also enjoy, powershell module azpolicytest v2.0 released.

6 minute read

Introduction I created the PowerShell module AzPolicyTest (GitHub, PowerShellGallery) back in 2019. This module provides a list of Pester tests can be used t...

Enhanced Azure Bicep Modules for Azure Policy Resources

Introduction

Azure Bicep Module for Network Security Groups

3 minute read

Managing Azure Private Endpoints using Azure Policy

2 minute read

Using Azure policies to manage the configuration of resources has become a very common practice and there are already many articles covering this topic. When...

Navigation Menu

Search code, repositories, users, issues, pull requests..., provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

  • Notifications

Policy assignment in bicep which require managed identities #5825

@bk-edge

bk-edge Feb 1, 2022

Beta Was this translation helpful? Give feedback.

You will need to assign a managed identity to the policy assignment.

See the Bicep spec for this resource here: https://docs.microsoft.com/en-us/azure/templates/microsoft.authorization/policyassignments?tabs=bicep

If you want to create a system assigned you need to use the identity property:

Note that you will need to create corresponding role assignme…

Replies: 1 comment · 1 reply

{{editor}}'s edit, matsest feb 1, 2022.

@bk-edge

bk-edge Feb 1, 2022 Author

@bk-edge

  • Numbered list
  • Unordered list
  • Attach files

Select a reply

COMMENTS

  1. Quickstart: Create policy assignment using Bicep file

    The Bicep file creates a policy assignment for a resource group scope and assigns the built-in policy definition Audit VMs that do not use managed disks. Create the following Bicep file as policy-assignment.bicep. Open Visual Studio Code and select File > New Text File. Copy and paste the Bicep file into Visual Studio Code.

  2. How to deploy Azure Policy with Bicep

    As policy initiatives don't define any rules, they use the 'policyDefinitions' keyword to reference existing policy definitions. Policy and policy initiative assignments are also pretty straightforward and defined as yet another resource: For complete definitions, look into bicep samples in my Azure Policy repository on GitHub.

  3. Bicep and Azure Policy: Manage Policy and Initiative Assignment

    This time, the post will focus on policy assignments with Azure Bicep and PowerShell. Policy assignment enforces a policy and a policy set at a given scope, management group, or subscription. This is where policies are applied to target resources. A policy Assignment object has several properties: A non-compliance object.

  4. Bicep

    Create the Bicep file. Create the Bicep file. The first step in implementing a Bicep template is to create the Bicep file that defines its resources. Create a new file named assignment.bicep. This file will contain the code necessary to assign a list of initiatives. targetScope = 'subscription' @description('Array of policy initiatives.

  5. Bicep and Azure Policy: Create an Azure Policy Set (or Policy

    A policy Set (or Initiative) is a collection of Azure policies. It simplifies the life cycle of these policies (adding or removing policies) and assignments where you apply the Initiative to a scope (subscriptions or management group). A Policy Set is a JSON definition that contains several properties. A display name (limited to 128 characters ...

  6. Bicep and Azure Policy: Create and manage custom Azure Policies

    This is the second post about Azure Policy. It will focus on policy definition and how to manage your custom policies with Azure Bicep and PowerShell. Azure provides several policy definitions that cover a wide range of situations and governance strategies. But sometimes you need policies that cover particular needs and requirements.

  7. Quickstart: New policy assignment with Bicep file

    In this quickstart, you use a Bicep file to create a policy assignment to identify non-compliant resources. Skip to main content. This browser is no longer supported. Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support. ...

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

  9. Building your Azure Policies

    At policy assignment; When changing a policy assignment; When exemptions are created or updated. Default evaluation cycle (once every 24 hours) Resource creation or update; For more information about policies, read the Azure Policy documentation. Creating your own Policy. Creating your policy is done using Bicep or writing the definition in JSON.

  10. Deploy Azure Policy to ManagementGroup with Bicep

    Policy assigment via Bicep. We use the bicep language to assign an Azure Policy to the management group. The policy which we use is: 'audit-vm-manageddisks' This policy checks whether virtual machines uses managed disks. Managed disks are covered by the 99,95% SLA coverage by Microsoft.

  11. AssigningPolicies · Azure/ALZ-Bicep Wiki · GitHub

    If specific ALZ default policies does not fit your organization you can exclude policies from the ALZ Default Policy Assignments module by following the process below: Navigate to the Policy Assignments lib directory: infra-as-code\bicep\modules\policy\assignments\lib\policy_assignments. Open the .json file for the policy that you want to ...

  12. Bicep: azure policy assignment scope

    Definition of the scope of the policy assignment. Definition of the parameter of the assignment; I couldn't find much example on the internet. The documentation of the Policy Assignment for Bicep is here. Do you have any idea how can I correct these errors?

  13. Azure Bicep

    The modules consist of three main components; the definition itself, the assignments, and the role assignments for the SystemAssigned identity (if the policy requires permissions to resources). A Bicep module is a .bicep-file which can be referenced to by another .bicep-file within the same repository. A module starts with defining the ...

  14. Policy as Code : Using Azure Bicep to deploy Azure Policies

    In a Bicep file, you define the infrastructure you want to deploy to Azure, and then use that file throughout the development lifecycle to repeatedly deploy your infrastructure. Your resources are ...

  15. Global Azure: Policy as Code with Bicep for Enterprise Scale

    More experienced users can jump straight to Level 3 and learn/adopt a Policy as Code workflow with Bicep. Links to skip to specific content levels in the recorded session are included below! Level 1. Uses built-in policies; Uses an initiative and assignment; 1x main.bicep; Manual CLI deployment; YouTube Video Timestamp 16m 10s. Level 2

  16. ArlanNugara/bicep-azure-policy: Azure Policy with Bicep

    The main.bicep calls the policy.bicep file. The policy.bicep in returns calls the modules in modules/policies directory and creates the policies. The main.parameters.json file is passed to the command which contains all the key value pair of the variables. You need to exchange "" with your values.

  17. Azure Bicep Modules for Azure Policy Resources

    Although I'm a big fan of Microsoft CARML Bicep module repo, and have used many of their modules in my projects, Sometimes I still prefer using the modules I have created myself. I created 3 Bicep modules a while back for Azure Policy Definitions, Initiatives and Assignments. They are all created for management-group scoped deployments ...

  18. Policy assignment in bicep which require managed identities #5825

    Policy assignment in bicep which require managed identities #5825. Answered by matsest. bk-edge asked this question in General. Policy assignment in bicep which require managed identities #5825. bk-edge. Feb 1, 2022 · 1 comments · 1 reply ...