AZ-305Chapter 103 of 103Objective 1.2

Policy as Code and Compliance Automation

This chapter covers Policy as Code and Compliance Automation in Azure, focusing on Azure Policy and Azure Blueprints. These services enable you to enforce organizational standards and assess compliance at scale. For the AZ-305 exam, approximately 15-20% of questions in the Identity Governance domain touch on policy enforcement, compliance automation, and related concepts like management groups, initiatives, and remediation. Mastering this topic is critical for designing governance strategies that meet security and compliance requirements.

25 min read
Intermediate
Updated May 31, 2026

Building Code Enforcement for Cloud Infrastructure

Imagine a city with thousands of buildings, each constructed by different contractors. The city enforces a building code that specifies everything from foundation depth to window egress sizes. Instead of sending inspectors to every building site, the city creates a digital rulebook that every contractor must run their blueprints through before pouring concrete. This rulebook is written in a machine-readable language that automatically checks each blueprint against the code. If a blueprint violates a rule—say, a fire escape that's too narrow—the system rejects it and provides a detailed report of the violation. The contractor cannot proceed until the blueprint is compliant. Now, imagine that the city updates the code every year; contractors must re-submit their blueprints for validation, and the system automatically flags any non-compliant existing buildings. This is exactly how Azure Policy works: Azure Resource Manager acts as the blueprint submission portal, Azure Policy defines the rulebook, and policy assignments enforce compliance at resource creation and during periodic audits. Just as the city can exempt historic buildings from certain rules, Azure Policy allows exemptions for specific resources. The key difference is that Azure Policy can also automatically remediate non-compliant resources by applying corrections, like a city that sends a crew to fix a fire escape without waiting for the contractor.

How It Actually Works

What is Policy as Code?

Policy as Code is the practice of defining and managing policies using machine-readable code files, typically JSON or YAML, that are stored in version control systems like Git. In Azure, this is primarily implemented through Azure Policy, which allows you to create, assign, and manage policies that enforce rules and effects on your Azure resources. The key idea is that policies are not just documents; they are executable rules that automatically evaluate resources and take actions such as deny, audit, or modify.

Why Policy as Code Exists

Traditional IT governance relies on manual checks and documentation, which is error-prone and does not scale. In cloud environments with hundreds or thousands of resources, manual compliance checks are infeasible. Policy as Code automates compliance enforcement, ensures consistency, and enables continuous compliance monitoring. It also integrates with DevOps pipelines, allowing policies to be tested and deployed alongside application code.

How Azure Policy Works Internally

Azure Policy is a service that evaluates resources against policy definitions. When a resource is created, updated, or deleted, Azure Resource Manager (ARM) triggers an evaluation. The policy engine checks the resource properties against the defined rules. If a rule is violated, the policy effect is applied. Effects include: - Deny: Prevents the resource creation or update. - Audit: Creates a warning in the activity log but does not block the operation. - Append: Adds additional fields to the resource during creation or update. - AuditIfNotExists: Audits resources that do not have specified components. - DeployIfNotExists: Deploys a template to remediate non-compliant resources. - Disabled: Effectively turns off the policy. - Modify: Adds, updates, or removes properties on a resource. - EnforceOPAConstraint: Used with Open Policy Agent for Kubernetes. - Mutate: Used for mutating admission webhooks in Kubernetes.

Policy definitions are written in JSON and consist of: - Mode: Determines which resource properties are evaluated. Modes include All, Indexed, Microsoft.ContainerService.Data, Microsoft.Kubernetes.Data, and Microsoft.KeyVault.Data. - Parameters: Allow customization of policies at assignment time. - Display Name and Description: Metadata. - Policy Rule: The core logic, including if (condition) and then (effect) blocks.

Key Components

Policy Definition: A single rule, e.g., "Allowed locations" or "Not allowed resource types."

Initiative Definition (Policy Set): A group of policy definitions that are assigned together. For example, the "ISO 27001" initiative includes multiple policies for security controls.

Assignment: The process of applying a policy or initiative to a scope. Scopes include management groups, subscriptions, resource groups, or individual resources.

Exemption: A way to exclude a resource from evaluation for a specific period. Exemptions can be waiver (allows non-compliance) or mitigated (acknowledges risk).

Remediation: A task that automatically corrects non-compliant resources. Remediation is available for DeployIfNotExists and Modify effects.

Compliance State: Resources are evaluated as Compliant, Non-compliant, Conflicting, Error, Exempted, or Not started.

Defaults and Timers

Evaluation Frequency: Policies are evaluated on resource creation, update, and delete. Additionally, a full compliance scan runs every 24 hours.

Remediation Task: Remediation tasks can be triggered manually or on a schedule. The default maximum number of remediation tasks per policy assignment is 1000.

Policy Definition Limits: Up to 500 policy definitions per initiative, up to 200 initiatives per subscription, and up to 10,000 assignments per subscription.

Exemption Expiration: Exemptions can be set to expire on a specific date, after which the resource is re-evaluated.

Configuration and Verification

Policies can be created via Azure portal, Azure CLI, PowerShell, or ARM templates. Example CLI commands:

# Create a policy definition
ez policy definition create --name "allowed-locations" --display-name "Allowed locations" --description "This policy enables you to restrict the locations your organization can specify when deploying resources." --rules '{"if":{"not":{"field":"location","in":["eastus","westus"]}},"then":{"effect":"deny"}}' --mode All

# Assign a policy to a subscription
ez policy assignment create --name "allowed-locations-assignment" --policy "allowed-locations" --scope /subscriptions/00000000-0000-0000-0000-000000000000

# Get compliance state
ez policy state list --resource "/subscriptions/.../resourceGroups/.../providers/Microsoft.Compute/virtualMachines/vm1"

Interaction with Related Technologies

Azure Blueprints: Blueprints package policies, role assignments, and ARM templates into a repeatable environment. Assigning a blueprint creates policy assignments automatically.

Management Groups: Policies assigned at a management group scope are inherited by all child subscriptions. This allows hierarchical governance.

Azure RBAC: Policies enforce what resources can be created, while RBAC controls who can create them. They work together: a user with Contributor role can create resources, but a policy can deny creation in certain regions.

Azure Resource Graph: Used to query compliance data across subscriptions. For example, where type =~ 'microsoft.policyinsights/policystates' returns policy states.

Azure DevOps: Policies can be integrated into CI/CD pipelines using Azure Policy as a gate. For instance, a pipeline can check if a resource is compliant before deployment.

Compliance Automation

Compliance automation extends beyond Azure Policy. It includes: - Azure Security Center (now Microsoft Defender for Cloud): Provides continuous security assessments and recommendations. It integrates with Azure Policy to enforce security controls. - Azure Compliance Manager: Helps track compliance against regulatory standards like GDPR, HIPAA, and ISO 27001. It maps Azure Policy initiatives to specific controls. - Azure Automation: Can be used to run remediation scripts on a schedule to fix non-compliant resources. - Azure Logic Apps: Can trigger workflows based on policy evaluation results, e.g., sending an email when a resource becomes non-compliant.

Step-by-Step: How Azure Policy Evaluates a Resource

1.

A user submits a create request for a resource via Azure portal, CLI, or API.

2.

ARM receives the request and starts the resource creation process.

3.

Before creating the resource, ARM triggers Azure Policy evaluation.

4.

The policy engine checks all applicable policy assignments at the resource's scope.

5.

For each policy, the engine evaluates the if condition using the resource properties.

6.

If a condition is met, the policy's then effect is applied.

7.

For Deny effect, the request fails with an error message.

8.

For Audit, the resource is created but a compliance event is logged.

9.

For Append, the specified fields are added to the resource before creation.

10.

After creation, the resource is tagged with compliance state.

11.

Periodic scans (every 24 hours) re-evaluate all resources and update compliance states.

Advanced Concepts

Policy as Code with Git: Store policy definitions in a Git repository. Use Azure DevOps or GitHub Actions to deploy policies via CI/CD. This ensures version control and peer review.

Custom Policy Definitions: You can write custom policies for specific requirements, such as enforcing naming conventions or requiring specific tags.

Policy Effects Order: When multiple policies apply, the most restrictive effect wins. For example, if one policy denies a location and another audits it, the deny takes precedence.

Exemption Scopes: Exemptions can be applied at the same scope as the assignment or at a child scope. They are inherited.

Remediation on Scale: Remediation tasks can be configured to run automatically when new non-compliant resources are discovered. They use managed identity to apply corrections.

Exam-Relevant Numbers

Maximum number of policy definitions per initiative: 500

Maximum initiatives per subscription: 200

Maximum policy assignments per subscription: 10,000

Maximum scope depth for inheritance: Management groups can have up to 6 levels.

Default compliance scan frequency: 24 hours.

Remediation task maximum per assignment: 1000.

Policy definition modes: All, Indexed, Microsoft.ContainerService.Data, Microsoft.Kubernetes.Data, Microsoft.KeyVault.Data.

Trap Patterns

Trap: Confusing Azure Policy with Azure RBAC. Azure Policy controls what resources can be created, while RBAC controls who can create them. A common wrong answer is using RBAC to enforce location restrictions. The correct answer is Azure Policy.

Trap: Thinking policy assignments are exclusive. Policies can overlap; the most restrictive effect wins. Candidates may think only one policy applies at a time.

Trap: Assuming remediation is automatic for all effects. Remediation only works for DeployIfNotExists and Modify effects. For Deny, there is no remediation because the resource was not created.

Trap: Exemptions are permanent. Exemptions have an expiration date; after that, the resource is re-evaluated. Candidates may think exemptions are indefinite.

Edge Cases

Policy on deleted resources: Policies do not evaluate deleted resources. Compliance states are removed.

Policy on resources created by Azure Backup or other services: Some Azure services create resources on your behalf. These are also evaluated by policies, which can cause failures if policies are too restrictive.

Policy evaluation for existing resources: When a new policy assignment is created, it triggers a compliance scan for existing resources. This can take time for large environments.

Initiative with multiple policies: If an initiative includes a policy that denies and another that audits, the deny effect overrides. But if the deny policy is disabled, the audit effect applies.

Summary

Azure Policy is the core service for policy as code in Azure. It allows you to define rules that are automatically enforced during resource creation and periodically thereafter. Compliance automation extends to remediation, integration with security tools, and reporting. For the AZ-305 exam, focus on understanding policy effects, scope inheritance, and how to design governance strategies using management groups and initiatives. Remember the key differences between policy, RBAC, and blueprints.

Walk-Through

1

Define Policy Definition

Start by creating a policy definition in JSON format. The definition includes a condition (if) and an effect (then). For example, a policy that denies creation of resources outside of East US would have a condition checking the location field and a deny effect. You can define it via Azure portal, CLI, or ARM template. The mode must be set to 'All' for general resources or specific data modes for container or Key Vault data. Parameters can be added to make the policy reusable, such as a list of allowed locations. The definition is stored at the management group or subscription level.

2

Create Initiative Definition

Group multiple policy definitions into an initiative for easier assignment. For example, a 'Security Baseline' initiative might include policies for allowed locations, required tags, and allowed SKUs. Initiatives are also defined in JSON and can include parameters that are passed to the member policies. Initiatives help manage complex compliance requirements by bundling related rules. They are assigned as a single unit, simplifying governance.

3

Assign Policy to Scope

Assign the policy or initiative to a scope: management group, subscription, resource group, or individual resource. The assignment includes parameter values and an optional exclusion list. For example, assign the 'Allowed locations' policy to a subscription with a parameter specifying allowed regions. The assignment triggers an immediate compliance scan for existing resources. You can also set assignment priority; if multiple assignments conflict, the most restrictive effect wins.

4

Evaluate Resource Compliance

When a resource is created or updated, Azure Resource Manager triggers policy evaluation. The policy engine checks the resource properties against all applicable policies. If a condition is met, the effect is applied. For deny, the request fails. For audit, the resource is created but logged as non-compliant. For append, fields are added automatically. The compliance state is stored and visible in the Azure portal. A full scan runs every 24 hours to catch any drift.

5

Remediate Non-Compliant Resources

For policies with DeployIfNotExists or Modify effects, you can create remediation tasks. Remediation uses a managed identity to deploy a template or modify the resource to make it compliant. For example, if a policy requires a specific tag on all resources, a remediation task can add that tag to existing non-compliant resources. Remediation can be triggered manually or on a schedule. It is important to ensure the managed identity has appropriate permissions.

What This Looks Like on the Job

Scenario 1: Enforcing Regional Compliance

A global financial institution must ensure that all customer data remains within the United States. They create an Azure Policy that denies resource creation in any region outside the US. The policy is assigned at the root management group, affecting all subscriptions. They also create an initiative that includes policies for encryption at rest and in transit. When a developer tries to deploy a VM in Europe, the request is denied with a clear error message. The compliance dashboard shows all resources and their compliance status. Remediation tasks automatically enable encryption on existing storage accounts that were provisioned before the policy was assigned. This setup prevents data residency violations and simplifies audits.

Scenario 2: Tagging Governance for Cost Allocation

A large enterprise uses a chargeback model where each department pays for its cloud usage. They require that every resource be tagged with 'CostCenter' and 'Environment'. An Azure Policy with Append effect automatically adds missing tags with default values during resource creation. For existing resources, a remediation task adds the tags. The policy is assigned at the subscription level with parameters for default values. The IT team uses Azure Policy's compliance view to identify untagged resources and runs weekly remediation. This ensures accurate cost reporting and prevents budget overruns.

Scenario 3: Kubernetes Admission Control

A SaaS provider runs AKS clusters and needs to enforce security policies on pods, such as preventing privileged containers. They use Azure Policy for AKS, which leverages Open Policy Agent (OPA) as an admission controller. They define custom policies using the 'Microsoft.Kubernetes.Data' mode. When a developer tries to deploy a pod with privileged mode, the policy denies the request. The policy is assigned at the resource group level containing the AKS cluster. This provides fine-grained control over what runs in the cluster without requiring developers to modify their deployment scripts. Misconfiguration can occur if the policy is too restrictive, breaking legitimate deployments, so careful testing is required.

How AZ-305 Actually Tests This

What AZ-305 Tests

AZ-305 exam domain 1.2 (Identity Governance) tests your ability to design governance strategies using Azure Policy, Azure Blueprints, and management groups. Specific objectives include:

Design a policy-driven governance strategy (1.2.1)

Design an Azure Blueprint-based governance strategy (1.2.2)

Design a management group hierarchy (1.2.3)

Design a compliance automation strategy (1.2.4)

Common Wrong Answers

1.

Using RBAC to restrict locations: Candidates often choose Azure RBAC because they think of 'permissions' as controlling actions. However, RBAC does not have conditions based on resource location. The correct answer is Azure Policy.

2.

Assuming all policies are enforced immediately: Some candidates think policy evaluation is only on creation. In reality, policies are also evaluated on updates and during periodic scans.

3.

Confusing initiatives with policy sets: Initiatives are policy sets, but the term 'policy set' is used in the portal. The exam uses 'initiative' as the official term.

4.

Thinking exemptions are permanent: Exemptions have an expiration date. Candidates may select 'exempt' as a permanent solution, but the correct approach is to design a policy that allows the specific scenario.

Specific Numbers and Terms

Maximum 500 policy definitions per initiative.

Maximum 200 initiatives per subscription.

Maximum 10,000 policy assignments per subscription.

Maximum 6 levels of management group hierarchy.

Default compliance scan interval: 24 hours.

Effects: Deny, Audit, Append, AuditIfNotExists, DeployIfNotExists, Disabled, Modify.

Modes: All, Indexed, Microsoft.ContainerService.Data, etc.

Edge Cases and Exceptions

Policy on Azure Backup-created resources: If a policy denies resources in a region, Azure Backup may fail to create restore points. You must exempt the Backup service.

Policy on Azure Policy itself: You cannot create a policy that affects the Azure Policy service itself.

Initiative with conflicting policies: If two policies in an initiative conflict, the most restrictive effect wins. For example, one policy denies and another audits, deny wins.

Policy evaluation for existing resources when a new assignment is created: The scan can take time; compliance results are not immediate for all resources.

How to Eliminate Wrong Answers

If the question is about restricting resource locations, the answer is always Azure Policy, not RBAC.

If the question involves automatic remediation, look for DeployIfNotExists or Modify effects.

If the question mentions version control and CI/CD for policies, think of Policy as Code with Git.

If the question is about grouping policies for assignment, think of initiatives (policy sets).

Key Takeaways

Azure Policy enforces rules on resource properties; Azure RBAC controls user permissions.

Policy effects include Deny, Audit, Append, AuditIfNotExists, DeployIfNotExists, Modify, and Disabled.

Initiative (policy set) groups multiple policy definitions for assignment as a unit.

Policies are evaluated on resource creation, update, and every 24 hours.

Remediation is only available for DeployIfNotExists and Modify effects.

Exemptions have an expiration date and are not permanent.

Maximum 500 policy definitions per initiative, 200 initiatives per subscription, 10,000 assignments per subscription.

Management groups support up to 6 levels of hierarchy.

Azure Blueprints package policies, roles, and templates for repeatable deployments.

Policy as Code involves storing policy definitions in Git and deploying via CI/CD.

Easy to Mix Up

These come up on the exam all the time. Here's how to tell them apart.

Azure Policy

Enforces rules on resources (e.g., deny, audit, append).

Assignable to management groups, subscriptions, resource groups, or resources.

Can be used for continuous compliance monitoring and remediation.

Supports custom policy definitions and initiatives.

Integrates with Azure DevOps for policy as code.

Azure Blueprints

Packages policies, role assignments, and ARM templates into a repeatable environment.

Assigned to subscriptions only (not resource groups or resources).

Used for deploying a consistent governance foundation (e.g., a landing zone).

Includes versioning and can be updated to match new requirements.

Automatically creates policy assignments when the blueprint is assigned.

Watch Out for These

Mistake

Azure Policy and Azure RBAC are the same thing.

Correct

Azure Policy enforces rules on resource properties (e.g., allowed locations, required tags), while Azure RBAC controls user permissions (who can create or manage resources). They are complementary but distinct.

Mistake

Azure Policy only evaluates resources at creation time.

Correct

Azure Policy evaluates resources on creation, update, and during periodic compliance scans every 24 hours. Existing resources are also evaluated when a new policy assignment is created.

Mistake

A policy with effect 'Deny' can be remediated automatically.

Correct

Deny prevents resource creation or update; there is no resource to remediate. Remediation is only for DeployIfNotExists and Modify effects.

Mistake

Exemptions are permanent and never expire.

Correct

Exemptions have an expiration date. After expiration, the resource is re-evaluated and may become non-compliant. Exemptions are meant for temporary exceptions.

Mistake

Policy assignments at a management group are not inherited by child subscriptions.

Correct

Policy assignments at a management group scope are inherited by all child scopes, including subscriptions and resource groups. Inheritance can only be blocked by a policy assignment at a lower scope with a different effect.

Do You Actually Know This?

Reveal each answer, then mark whether you got it right. Score 60%+ to unlock the next chapter.

Frequently Asked Questions

What is the difference between Azure Policy and Azure RBAC?

Azure Policy enforces rules on resource properties (e.g., allowed locations, required tags) and can deny or audit non-compliant resources. Azure RBAC controls who can perform actions on resources (e.g., who can create VMs). They work together: RBAC grants permissions, but Policy can override by denying the action. For example, a user with Contributor role can create resources, but a Policy can deny creation in certain regions.

Can Azure Policy automatically fix non-compliant resources?

Yes, but only for policies with DeployIfNotExists or Modify effects. These effects can trigger remediation tasks that deploy a template or modify the resource to make it compliant. For example, a policy that requires a specific tag can use the Append effect to add the tag during creation, and a remediation task can add the tag to existing resources. Deny and Audit effects do not have automatic remediation.

How do I create a custom Azure Policy definition?

Custom policy definitions are written in JSON. You define the condition (if) and effect (then). For example, to deny resources without a specific tag, you would check if the tag exists. You can create the definition via Azure portal, CLI, or ARM template. Use the command 'az policy definition create' with the --rules parameter. Custom policies can be added to initiatives for assignment.

What is an Azure Blueprint and how does it relate to Policy?

An Azure Blueprint is a package that contains one or more Azure Policy assignments, role assignments, and ARM templates. It is used to deploy a consistent environment, such as a landing zone. When you assign a blueprint, it automatically creates the policy assignments defined in it. Blueprints support versioning and can be updated. Policy assignments created by blueprints are independent and can be modified separately.

How do I handle policy conflicts when multiple policies apply?

When multiple policies apply to the same resource, the most restrictive effect wins. For example, if one policy denies a location and another audits it, the deny effect overrides. If multiple policies have the same effect, the order of evaluation is not guaranteed. To avoid conflicts, design policies carefully and test in a non-production environment. Use initiatives to group related policies and manage conflicts.

What are management groups and how do they affect policy inheritance?

Management groups are containers that help manage access, policy, and compliance across multiple subscriptions. Policies assigned at a management group are inherited by all child subscriptions and resource groups. You can have up to 6 levels of management groups. Inheritance can be overridden by a policy assignment at a lower scope with a different effect. Management groups are free and can be used to organize your Azure environment.

How often does Azure Policy scan for compliance?

Azure Policy evaluates resources on every create or update operation. Additionally, a full compliance scan runs automatically every 24 hours. When a new policy assignment is created, it triggers a scan for existing resources. You can also trigger an on-demand scan using Azure CLI or PowerShell. The compliance state is updated after each evaluation.

Terms Worth Knowing

Ready to put this to the test?

You've just covered Policy as Code and Compliance Automation — now see how well it sticks with free AZ-305 practice questions. Full explanations included, no account needed.

Done with this chapter?