Policy as Code (PoC): Deploying and Managing Azure Policy in Bicep

What is Azure Policy ? As Per Official Microsoft Article

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.


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.

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

Remediate non-compliant resources

While these effects primarily affect a resource when the resource is created or updated, Azure Policy also supports dealing with existing non-compliant resources without needing to alter that resource.

Azure Policy vs 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 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.

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.


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.

Going through the Bicep code

The Bicep project is configured to work on the following principle

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

Understanding Policy code

The main.bicep file starts with a targetScope variable which defines the deployment scope of the code.

targetScope = 'subscription'
param policyInitiativeArray array
module policyM 'modules/policy.bicep' = [for (pol, i) in policyInitiativeArray: {
name: 'Policy-${i}'
params: {
policyData: pol
module allowedRegionsModule './policies/allowed_regions.bicep' = {
name: '${policyData.client}-${policyData.allowed_regions_policy.name}'
params: {
client: policyData.client
policyInputData: policyData.allowed_regions_policy
targetScope = 'subscription'param policyInputData object
param client string
output policyId string = allowed_regions_policy.id
resource allowed_regions_policy 'Microsoft.Authorization/policyDefinitions@2021-06-01' = {
name: '${client}-${policyInputData.name}'
properties: {
displayName: '${client}-${policyInputData.displayName}'
policyType: 'Custom'
mode: 'All'
description: policyInputData.description
metadata: {
category: 'General'
policyRule: {
if: {
allOf: [
field: 'location'
notIn: '[parameters(\'regAllowedRegions\')]'
field: 'location'
notEquals: 'global'
field: 'type'
notEquals: 'Microsoft.AzureActiveDirectory/b2cDirectories'
then: {
effect: policyInputData.effect
resource policyDefSet 'Microsoft.Authorization/policySetDefinitions@2021-06-01' = {
name: '${policyData.client}-${policyData.name}'
dependsOn: [
properties: {
policyType: policyData.policyType
displayName: policyData.policySetDefinitionDisplayName
parameters: {}
policyDefinitions: [
policyDefinitionId: allowedRegionsModule.outputs.policyId
parameters: {}
resource policyAssign 'Microsoft.Authorization/policyAssignments@2021-06-01' = {
name: '${policyData.client}-${policyData.name}-Assignment'
properties: {
displayName: '${policyData.client}-${policyData.policyInitiativeDisplayName}'
enforcementMode: 'Default'
policyDefinitionId: policyDefSet.id
parameters: {}
"allowed_regions_policy": {
"name": "Allowed-Azure-Regions",
"displayName": "Allowed Azure Regions",
"description": "This policy allows resources to be created in the allowed locations.",
"listOfAllowedLocations": ["canadaeast", "canadacentral"],
"effect": "Audit"

Policies that are created

  1. Allowed Regions
  2. Allowed Resource Types
  3. Allowed SQL Version
  4. Allowed Storage Account SKU
  5. Allowed VM Extensions
  6. Allowed Subnets for Public IP
  7. Allowed VM OS and version
  8. Allowed VM SKU
  9. DDOS Protection
  10. Diagnostics Settings
  11. Diagnostic settings logs to be send to Log Analytics WOrkspace
  12. Firewall Internet Traffic
  13. Key Vault Purge Protection
  14. Key Vault soft delete
  15. VM NIC IP Forwarding
  16. Enable Network Watchers
  17. NSG for every Subnet
  18. NSG Inbound rules
  19. SQL Database Private endpoint
  20. SQL Database TLS version
  21. SQL server public network access
  22. Storage Account Secure Transfer Settings
  23. Storage Account Key Expiry
  24. Storage Account Network Access
  25. Mandatory Tags
  26. Optional Tags
  27. Internet facing VM NSG
  28. VM managed disk
  29. VM management port
  30. VM encryption

Run the code

Authenticate Azure CLI

Hit the command az login from Comamnd Prompt or Terminal depending upon your OS. More details can be found here

Trigger Manually

Fire the below command to create the resources using Bicep script



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store