Home DevOps Microsoft Azure — Azure Policy & Compliance
Beginner 6 min · July 12, 2026

Microsoft Azure — Azure Policy & Compliance

Azure Policy definitions, initiatives, assignments, compliance dashboard, and built-in regulatory compliance..

N
Naren Founder & Principal Engineer

20+ years shipping production infrastructure and CI/CD at scale. Lessons pulled from things that broke in production.

Follow
Verified
production tested
July 12, 2026
last updated
1,983
articles · all by Naren
Before you start⏱ 20 min
  • Azure subscription (free tier), Azure CLI (version 2.40+), PowerShell (7.0+ with Az module), basic understanding of Azure resource hierarchy (management groups, subscriptions, resource groups), familiarity with JSON syntax.
✦ Definition~90s read
What is Azure Policy & Compliance?

Microsoft Azure — Azure Policy & Compliance is a core Azure service that handles policy compliance in the Microsoft cloud ecosystem.

Azure Policy & Compliance is like having a specialized tool that handles policy compliance in the Microsoft cloud — you manage the configuration, Azure handles the infrastructure.
Plain-English First

Azure Policy & Compliance is like having a specialized tool that handles policy compliance in the Microsoft cloud — you manage the configuration, Azure handles the infrastructure.

Azure is Microsoft's cloud computing platform offering over 200 services. This article covers azure policy & compliance with production-ready configurations, best practices, and hands-on examples.

Why Azure Policy Matters in Production

Azure Policy is a service in Azure that you use to create, assign, and manage policies. These policies enforce different rules and effects over your resources, so those resources stay compliant with your corporate standards and service level agreements. In production, ungoverned resources lead to security breaches, cost overruns, and compliance failures. Azure Policy helps you avoid these by applying guardrails at scale. For example, you can prevent deployment of VMs in unsupported regions, enforce tagging for cost tracking, or require HTTPS on storage accounts. Without policies, your environment drifts into chaos. This article walks through the core concepts, writing custom policies, assignment strategies, and remediation — all from a production perspective.

🔥Policy vs RBAC
Azure Policy evaluates resource properties during create, update, and existing state. RBAC controls who can do what. They work together: RBAC for permissions, Policy for compliance.
📊 Production Insight
In production, a missing policy on allowed locations can lead to data residency violations. Always start with a baseline set of policies from Azure Policy built-in definitions.
🎯 Key Takeaway
Azure Policy enforces organizational standards and assesses compliance at scale.
azure-policy-compliance THECODEFORGE.IO Azure Policy Lifecycle from Definition to Remediation Step-by-step workflow for policy creation and enforcement Define Policy Create custom or built-in policy definition Assign Policy Assign to management group or subscription Evaluate Compliance Azure Policy scans resources for compliance Identify Non-Compliant Resources flagged in compliance dashboard Remediate Apply remediation tasks or deployIfNotExists Report & Monitor View compliance state and export reports ⚠ Skipping remediation leads to persistent non-compliance Always pair deny policies with remediation tasks THECODEFORGE.IO
thecodeforge.io
Azure Policy Compliance

Core Concepts: Policy Definition, Initiative, Assignment

A policy definition expresses a rule using JSON. It includes a condition (e.g., resource type equals 'Microsoft.Compute/virtualMachines') and an effect (e.g., deny, audit, append). An initiative is a group of policy definitions, often used to group related policies (like 'ISO 27001'). An assignment applies a policy or initiative to a specific scope: management group, subscription, or resource group. Effects determine what happens when a resource is non-compliant: Deny blocks creation, Audit logs a warning, Append adds tags, DeployIfNotExists triggers remediation. Understanding these is critical because misconfigured effects can break deployments. For instance, a Deny effect on a tag that is missing will block all new resources until the tag is added. Always test with Audit first in production.

policy-definition.jsonJSON
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
{
  "properties": {
    "displayName": "Require tag: CostCenter",
    "policyType": "Custom",
    "mode": "Indexed",
    "description": "Deny deployment if CostCenter tag is missing",
    "metadata": {
      "category": "Tags"
    },
    "parameters": {
      "tagName": {
        "type": "String",
        "defaultValue": "CostCenter"
      }
    },
    "policyRule": {
      "if": {
        "field": "tags[parameters('tagName')]",
        "exists": "false"
      },
      "then": {
        "effect": "deny"
      }
    }
  }
}
⚠ Effect Order Matters
If you assign a policy with Deny effect to a scope that already has non-compliant resources, existing resources are not affected. Only new creates or updates are blocked. Use Audit first to assess current compliance.
📊 Production Insight
We once assigned a Deny policy on a subscription without auditing first. It blocked all new VM deployments because the default image didn't have the required tag. Always audit before deny.
🎯 Key Takeaway
Policy definitions are JSON rules; initiatives group them; assignments apply them to scopes.

Writing Your First Custom Policy

Custom policies let you enforce rules specific to your organization. Start by defining the policy rule in JSON. The rule has an 'if' condition and a 'then' effect. Conditions can check resource properties (field), tags, locations, SKUs, etc. Use the Azure Policy extension for VS Code or the portal editor. A common pattern is to enforce mandatory tags. The example below denies any resource that doesn't have a 'CostCenter' tag. After writing the definition, create it with New-AzPolicyDefinition (PowerShell) or az policy definition create (CLI). Then assign it to a scope. Test in a non-production subscription first. Remember: custom policies are powerful but can cause friction if too restrictive. Involve your engineering teams in the design.

create-policy.ps1POWERSHELL
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# Create custom policy definition
$definition = New-AzPolicyDefinition -Name 'require-costcenter-tag' `
  -DisplayName 'Require CostCenter tag' `
  -Description 'Deny if CostCenter tag is missing' `
  -Policy '.\.\policy-definition.json' `
  -Mode Indexed

# Assign to a subscription
$subscriptionId = '00000000-0000-0000-0000-000000000000'
$assignment = New-AzPolicyAssignment -Name 'require-costcenter-tag-assignment' `
  -DisplayName 'Require CostCenter tag assignment' `
  -Scope "/subscriptions/$subscriptionId" `
  -PolicyDefinition $definition

Write-Output "Policy assigned to subscription $subscriptionId"
Output
Policy assigned to subscription 00000000-0000-0000-0000-000000000000
💡Use Built-in Policies First
Azure provides over 500 built-in policy definitions. Before writing custom, check if a built-in exists. It saves time and follows best practices.
📊 Production Insight
We wrote a custom policy to enforce specific VM sizes. It broke a deployment because the policy didn't account for availability sets. Always include exceptions via parameters.
🎯 Key Takeaway
Custom policies enforce organization-specific rules; test with Audit before Deny.
azure-policy-compliance THECODEFORGE.IO Azure Policy Enforcement Stack Hierarchical layers from management groups to resources Management Group Root MG | Child MG Subscription Subscription A | Subscription B Policy Assignment Built-in Policy | Custom Policy | Initiative Resource Group RG-Prod | RG-Dev Resource VM | Storage | SQL DB THECODEFORGE.IO
thecodeforge.io
Azure Policy Compliance

Assigning Policies at Scale with Management Groups

Management groups let you organize subscriptions hierarchically. Assign policies at the management group level to apply to all child subscriptions. This is essential for large enterprises. For example, assign a policy that requires encryption at rest at the root management group. All subscriptions inherit it. Inheritance is additive: a policy assigned at a higher scope applies to lower scopes unless overridden by an exclusion. Exclusions are done by assigning a policy with 'Exclude' parameter on specific child scopes. Be careful: too many exclusions defeat the purpose. Use initiatives to bundle related policies. Also, use policy parameters to make assignments flexible (e.g., allowed locations list).

assign-mg.shAZURECLI
1
2
3
4
5
6
7
8
9
10
11
#!/bin/bash
# Assign policy at management group scope
MG_ID="my-root-group"
POLICY_DEF="/providers/Microsoft.Authorization/policyDefinitions/require-costcenter-tag"

az policy assignment create \
  --name 'require-costcenter-mg' \
  --display-name 'Require CostCenter at MG' \
  --scope "/providers/Microsoft.Management/managementGroups/$MG_ID" \
  --policy "$POLICY_DEF" \
  --params '{"tagName":{"value":"CostCenter"}}'
🔥Inheritance and Exclusions
Policies are inherited by all child scopes. To exclude a specific subscription, assign the policy with 'Exclude' parameter or use a separate assignment with 'NotScopes'.
📊 Production Insight
We assigned a policy at root management group that required all storage accounts to use blob encryption. It broke a legacy app that used unencrypted file shares. We had to create an exclusion for that subscription.
🎯 Key Takeaway
Assign policies at management group level for enterprise-wide compliance.

Remediation: Fixing Non-Compliant Resources

Policies with 'DeployIfNotExists' or 'Modify' effects can automatically remediate non-compliant resources. For example, a policy that deploys a network watcher if missing. Remediation tasks run on existing resources. To set up, create a managed identity for the policy assignment, grant it permissions (e.g., Contributor on the scope), and define the deployment template in the policy definition. The remediation task can be triggered manually or on a schedule. Be cautious: remediation can modify many resources at once. Test on a small scope first. Also, monitor remediation logs to catch failures. Common issues: missing permissions, template errors, or resource conflicts.

remediation-policy.jsonJSON
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
{
  "properties": {
    "displayName": "Deploy Network Watcher if missing",
    "policyType": "Custom",
    "mode": "Indexed",
    "description": "Deploy Network Watcher in each region where VMs exist",
    "metadata": {
      "category": "Network"
    },
    "parameters": {},
    "policyRule": {
      "if": {
        "field": "type",
        "equals": "Microsoft.Network/virtualNetworks"
      },
      "then": {
        "effect": "deployIfNotExists",
        "details": {
          "type": "Microsoft.Network/networkWatchers",
          "resourceGroupName": "NetworkWatcherRG",
          "existenceCondition": {
            "field": "location",
            "equals": "[resourceGroup().location]"
          },
          "deployment": {
            "properties": {
              "mode": "incremental",
              "template": {
                "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
                "contentVersion": "1.0.0.0",
                "parameters": {},
                "resources": [
                  {
                    "type": "Microsoft.Network/networkWatchers",
                    "name": "[concat('NetworkWatcher_', resourceGroup().location)]",
                    "location": "[resourceGroup().location]",
                    "apiVersion": "2020-05-01",
                    "properties": {}
                  }
                ]
              },
              "parameters": {}
            }
          }
        }
      }
    }
  }
}
⚠ Remediation Permissions
The managed identity used for remediation must have write permissions on the target resources. Without proper RBAC, remediation tasks fail silently.
📊 Production Insight
We set up a remediation policy to deploy diagnostic settings on all VMs. It failed because the managed identity didn't have 'Log Analytics Contributor' on the workspace. Always test permissions.
🎯 Key Takeaway
Remediation automatically fixes non-compliant resources using DeployIfNotExists or Modify effects.

Compliance Dashboard and Reporting

Azure Policy provides a compliance dashboard in the portal. It shows overall compliance percentage, non-compliant resources, and policy details. You can export compliance data to Log Analytics or Event Hubs for custom reporting. Use Azure Resource Graph to query compliance state across subscriptions. For example, find all non-compliant VMs. Set up alerts for compliance changes using Azure Monitor. In production, regularly review compliance reports to catch drift. A common pitfall: compliance data is not real-time; it refreshes every few hours. For critical policies, use 'Audit' effect and monitor logs. Also, use policy exemptions for temporary exceptions, but track them with expiration dates.

compliance-query.kqlKQL
1
2
3
4
5
6
// Query non-compliant resources using Azure Resource Graph
policyresources
| where type =~ 'microsoft.authorization/policyassignments'
| extend complianceState = tostring(properties.complianceState)
| where complianceState == 'NonCompliant'
| project subscriptionId, resourceGroup, resourceName = properties.resourceId, policyAssignmentName = name
Output
subscriptionId, resourceGroup, resourceName, policyAssignmentName
00000000-0000-0000-0000-000000000000, prod-rg, vm-web-01, require-costcenter-tag-assignment
💡Export Compliance to Log Analytics
Enable 'Azure Policy Compliance' diagnostic setting to stream compliance data to Log Analytics for long-term retention and custom dashboards.
📊 Production Insight
We missed a compliance drift because the dashboard refreshes every 8 hours. We now set up alerts on policy compliance changes using Activity Log alerts.
🎯 Key Takeaway
Monitor compliance via dashboard, Resource Graph, and alerts to catch drift.

Policy as Code: CI/CD for Azure Policy

Treat policies as code: store definitions in Git, validate with tests, and deploy via CI/CD. Use Azure DevOps or GitHub Actions. Steps: 1) Export existing policies to JSON. 2) Store in a repo. 3) Use az policy definition create in pipeline. 4) Validate with az policy definition list and custom tests. 5) Assign policies via ARM templates or Bicep. Benefits: version control, peer review, automated testing. A common failure: deploying a policy that breaks production because it wasn't tested. Use separate environments (dev, test, prod) with different scopes. Also, use policy parameters to make definitions reusable across environments.

azure-pipeline.ymlYAML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
trigger:
- main

pool:
  vmImage: 'ubuntu-latest'

steps:
- task: AzureCLI@2
  displayName: 'Create or update policy definitions'
  inputs:
    azureSubscription: 'my-service-connection'
    scriptType: 'bash'
    scriptLocation: 'inlineScript'
    inlineScript: |
      for file in policies/*.json; do
        name=$(basename $file .json)
        az policy definition create --name $name --rules $file --mode Indexed --display-name $name
      done

- task: AzureCLI@2
  displayName: 'Assign policies'
  inputs:
    azureSubscription: 'my-service-connection'
    scriptType: 'bash'
    scriptLocation: 'inlineScript'
    inlineScript: |
      az policy assignment create --name 'require-tags' --policy /providers/Microsoft.Authorization/policyDefinitions/require-costcenter-tag --scope '/subscriptions/00000000-0000-0000-0000-000000000000'
🔥Test in Isolation
Always test policy assignments in a non-production subscription. Use a separate management group for testing to avoid impacting production.
📊 Production Insight
We once merged a policy that had a typo in the field name. It passed syntax check but didn't enforce anything. Now we include integration tests that create a test resource and verify compliance.
🎯 Key Takeaway
Store policies in Git, validate, and deploy via CI/CD for consistency and auditability.

Common Pitfalls and How to Avoid Them

  1. Overly restrictive policies: Deny effects without audit first block deployments. Always start with Audit. 2) Ignoring inheritance: Policies at higher scopes affect all children. Use exclusions sparingly. 3) Not using parameters: Hardcoded values make policies inflexible. Use parameters for allowed locations, tag names, etc. 4) Neglecting remediation permissions: Managed identities need proper RBAC. 5) Forgetting to monitor: Compliance dashboards are not real-time. Set up alerts. 6) Policy conflicts: Two policies can conflict (e.g., one denies a location, another requires it). Test in a sandbox. 7) Not planning for exceptions: Use exemptions with expiration dates for temporary waivers. Avoid permanent exemptions.
⚠ Policy Conflicts
If two policies assign different effects to the same resource, the most restrictive effect wins. For example, if one policy denies a location and another audits, the deny takes precedence.
📊 Production Insight
We had a policy that denied all public IP addresses, but another policy required a public IP for a load balancer. The deny won, breaking the load balancer deployment. We had to add an exclusion for load balancers.
🎯 Key Takeaway
Avoid pitfalls by auditing first, using parameters, and monitoring compliance.

Integrating with Azure Blueprints and Landing Zones

Azure Blueprints (deprecated) and Enterprise-Scale Landing Zones use Azure Policy to enforce governance. Blueprints package policies, RBAC, and resource templates. Landing zones (via Terraform or Bicep) include policy assignments as part of the foundation. For example, the Azure Landing Zone accelerator includes policies for encryption, networking, and monitoring. When adopting landing zones, you inherit a set of policies. Customize them by adding your own. Be careful: modifying landing zone policies can break upgrades. Use policy exemptions for deviations. Also, consider using Azure Policy's 'Initiative' to group your custom policies alongside landing zone policies.

🔥Landing Zone Policy Updates
Microsoft periodically updates landing zone policies. Review changes before applying to avoid unexpected compliance failures.
📊 Production Insight
We customized a landing zone policy to allow a specific VM size. When Microsoft updated the landing zone, our customization was overwritten. Now we use policy exemptions instead of modifying the base definition.
🎯 Key Takeaway
Integrate Azure Policy with landing zones for consistent governance at scale.

Production Monitoring and Alerting for Policy Compliance

Set up Azure Monitor alerts for policy compliance changes. Use Activity Log alerts when a policy assignment is created, modified, or deleted. Also, alert on compliance state changes using Azure Resource Graph scheduled queries. For example, alert if more than 10 resources become non-compliant in an hour. Integrate with ITSM tools like ServiceNow. In production, compliance drift often happens after deployments or configuration changes. Automate remediation where possible, but always have a manual approval for critical changes. Also, use Azure Policy's 'Guest Configuration' for in-VM compliance (e.g., installed software, security settings).

alert-rule.ps1POWERSHELL
1
2
3
4
5
6
# Create an alert rule for policy compliance changes
$actionGroup = New-AzActionGroup -Name 'PolicyAlertGroup' -ShortName 'Policy' -EmailReceiver @{Name='admin';EmailAddress='admin@contoso.com'}

$condition = New-AzMetricAlertRuleV2Criteria -MetricName 'NonCompliantResources' -TimeAggregation 'Total' -Operator 'GreaterThan' -Threshold 10

Add-AzMetricAlertRuleV2 -Name 'HighNonCompliance' -ResourceGroupName 'monitoring-rg' -WindowSize 01:00:00 -Frequency 00:05:00 -TargetResourceId '/subscriptions/00000000-0000-0000-0000-000000000000' -Condition $condition -ActionGroupId $actionGroup.Id -Severity 2
💡Use Guest Configuration for VM Compliance
Guest Configuration policies audit settings inside VMs, like installed applications or security policies. They require the Guest Configuration extension.
📊 Production Insight
We set up an alert for non-compliant resources but didn't include a suppression window. It fired every 5 minutes during a planned maintenance. Always use suppression for known events.
🎯 Key Takeaway
Monitor compliance with alerts and integrate with ITSM for rapid response.

Cost Management with Azure Policy

Azure Policy can help control costs by enforcing resource limits. For example, deny VMs above a certain size, require auto-shutdown schedules, or enforce resource group naming conventions for cost tracking. Use 'Audit' effect to report on expensive resources. Combine with Azure Cost Management budgets. A common pattern: require a 'CostCenter' tag on all resources, then use tag-based cost reports. Also, use policy to block creation of expensive services (e.g., Azure NetApp Files) unless approved. Be careful: overly restrictive cost policies can block innovation. Balance with exemptions for approved projects.

cost-policy.jsonJSON
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
{
  "properties": {
    "displayName": "Deny VMs larger than Standard_D4s_v3",
    "policyType": "Custom",
    "mode": "All",
    "description": "Deny creation of VMs with SKU larger than D4s v3",
    "metadata": {
      "category": "Compute"
    },
    "parameters": {
      "allowedSizes": {
        "type": "Array",
        "defaultValue": ["Standard_D2s_v3", "Standard_D4s_v3"]
      }
    },
    "policyRule": {
      "if": {
        "allOf": [
          {
            "field": "type",
            "equals": "Microsoft.Compute/virtualMachines"
          },
          {
            "field": "Microsoft.Compute/virtualMachines/sku.name",
            "notIn": "[parameters('allowedSizes')]"
          }
        ]
      },
      "then": {
        "effect": "deny"
      }
    }
  }
}
⚠ Cost Policies Can Block Innovation
If you deny all large VMs, teams may not be able to deploy performance-critical workloads. Use Audit first and review exceptions quarterly.
📊 Production Insight
We denied all VMs larger than D4s v3. A data science team needed a GPU VM for model training. We had to create an exemption, which delayed their project. Now we use Audit and a manual approval process.
🎯 Key Takeaway
Use Azure Policy to enforce cost controls like VM size limits and mandatory tags.

Next Steps: Advanced Policy Patterns

After mastering basics, explore advanced patterns: 1) Policy exemptions with expiration dates for temporary waivers. 2) Using 'Modify' effect to add tags automatically. 3) Cross-subscription policies using management groups. 4) Policy for Azure Kubernetes Service (AKS) to enforce pod security. 5) Custom policy aliases for new resource properties. 6) Using Azure Policy with Terraform via azurerm_policy_definition resource. 7) Policy-driven governance for Azure DevOps pipelines (e.g., require approval for production deployments). Always stay updated with Azure Policy documentation as new features are added regularly.

🔥Policy Aliases
Azure Policy uses aliases to access resource properties. You can find aliases using Get-AzPolicyAlias or the portal. Custom aliases are not supported.
📊 Production Insight
We used Modify effect to automatically add a 'CreatedBy' tag with the user principal name. It helped with cost allocation but required careful permission scoping to avoid overwriting existing tags.
🎯 Key Takeaway
Explore advanced patterns like Modify effect, AKS policies, and Terraform integration.

Regulatory Compliance Built-in Initiatives

Azure Policy includes built-in regulatory compliance initiatives mapped to major frameworks: SOC 2, ISO 27001, HIPAA/HITRUST, FedRAMP Moderate/High, PCI DSS, and the Microsoft Cloud Security Benchmark (MCSB). These initiatives bundle 50-200+ policy definitions scoped to specific compliance controls. Assign them at the root management group to evaluate compliance across the entire organization. Use the Compliance dashboard in Microsoft Defender for Cloud to see a unified view of regulatory compliance posture, with drill-down to specific controls and resources. For new regulations, Microsoft publishes initiatives in preview that you can test in audit-only mode. Customize built-in initiatives by adding your own policies via 'custom initiative' definitions. In production, always review the specific control mappings — some built-in policies may not apply to your architecture. Export compliance reports to Excel, CSV, or integrate with GRC tools via Power BI.

assign-regulatory-initiative.shBASH
1
2
3
4
5
6
7
8
9
10
11
12
az policy set-definition show \
  --name "SOC2Type1" \
  --query "{displayName:displayName, description:description, policyType:policyType}" \
  -o table

# Assign SOC 2 initiative at subscription scope
az policy assignment create \
  --name "soc2-compliance" \
  --display-name "SOC 2 Type 1 Compliance" \
  --policy-set-definition "SOC2Type1" \
  --scope /subscriptions/00000000-0000-0000-0000-000000000000 \
  --enforcement-mode Default
Output
displayName description policyType
--------------------------- --------------------------------------------------- ----------
SOC 2 Type 1 Microsoft's SOC 2 Type 1 attestation initiative... BuiltIn
Policy assignment created successfully.
🔥Regulatory vs Custom
Built-in regulatory initiatives map to specific compliance frameworks. They are updated by Microsoft as regulations evolve. For organization-specific rules, create custom initiatives built on top of or alongside regulatory ones.
📊 Production Insight
We assigned the SOC 2 initiative at our root management group and discovered 200+ non-compliant resources immediately. Most were missing diagnostic settings or encryption. The audit reporting became a one-click export instead of a month-long manual process.
🎯 Key Takeaway
Built-in regulatory compliance initiatives map Azure Policy to SOC 2, ISO 27001, HIPAA, and other frameworks for automated compliance assessment.

Microsoft Cloud Security Benchmark and Defender for Cloud Integration

The Microsoft Cloud Security Benchmark (MCSB) is the successor to the Azure Security Benchmark, providing prescriptive best practices for security across Azure, multicloud, and on-premises. It maps to CIS, NIST, and PCI frameworks. MCSB recommendations are available in Microsoft Defender for Cloud, which provides a unified security posture management platform. Defender for Cloud has two tiers: (1) Free tier — continuous assessment, secure score, and Azure Policy integration; (2) Paid (Defender plans) — advanced threat detection, vulnerability scanning, and just-in-time VM access. Defender for Cloud automatically assigns the MCSB initiative to your subscriptions. Use its secure score to track progress: each recommendation has a potential score increase, and you can prioritize by impact. Integrate Defender for Cloud with Azure Policy: enabling Defender plans can be governed via policy. For production, enable at least Defender for Cloud foundational CSPM (free) and consider Defender for Servers, Defender for Storage, and Defender for SQL on critical workloads.

enable-defender-plans.shBASH
1
2
3
4
az security pricing create --name "CloudPosture" --tier "Standard"
az security pricing create --name "VirtualMachines" --tier "Standard"
az security pricing create --name "StorageAccounts" --tier "Standard"
az security pricing create --name "SqlServers" --tier "Standard"
Output
{
"id": "/subscriptions/.../providers/Microsoft.Security/pricings/CloudPosture",
"name": "CloudPosture",
"pricingTier": "Standard"
}
💡Secure Score Prioritization
Use the secure score in Defender for Cloud to prioritize remediation. Each security recommendation shows its potential score impact. Focus on high-impact items first — a few changes can move your score significantly.
📊 Production Insight
We enabled Defender for Cloud's free tier and immediately identified a storage account with public blob access that contained PII data. The secure score dropped by 5 points just from that one misconfiguration. We locked it down and created a policy to deny public access.
🎯 Key Takeaway
MCSB provides the security baseline; Defender for Cloud operationalizes it with continuous assessment, secure score, and threat detection.
Built-in vs Custom Azure Policy Trade-offs between pre-defined and custom policy definitions Built-in Policy Custom Policy Definition Source Microsoft-provided User-authored JSON Flexibility Limited to predefined rules Fully customizable conditions Maintenance Automatically updated by Azure Manual updates required Deployment Speed Immediate assignment Requires testing and CI/CD Compliance Coverage Common regulatory standards Specific organizational needs THECODEFORGE.IO
thecodeforge.io
Azure Policy Compliance

Azure Policy Effects Deep Dive and Evaluation Logic

Azure Policy supports nine effects: Deny, Audit, Append, AuditIfNotExists, DeployIfNotExists, Modify, Disabled, Manual, and DenyAction. Each effect has specific behavior and performance implications. Deny blocks create/update operations — use for hard guardrails. Audit logs non-compliant resources without blocking — use for discovery and soft governance. Append adds fields (e.g., tags) during create/update — use for enforcing required tags. DeployIfNotExists triggers a deployment to fix non-compliant resources — use with a managed identity. Modify is faster than Append for adding/altering tags and works on existing resources. DenyAction (Preview) blocks specific actions (e.g., delete) on resources. Policy evaluation happens at resource create/update, when a policy is assigned/updated, and during the 24-hour compliance cycle. Multiple policies at the same scope are evaluated independently; if any have Deny effect on a condition, the resource is denied. Use policy exemptions with expiration dates for temporary waivers instead of disabling policies.

effect-comparison.jsonJSON
1
2
3
4
5
6
7
8
9
10
{
  "effects": {
    "Deny": { "use": "Hard block on non-compliant resources", "cost": "Low", "existing": "No impact" },
    "Audit": { "use": "Discover non-compliant resources", "cost": "Low", "existing": "Marked non-compliant" },
    "Append": { "use": "Add missing fields during create", "cost": "Low", "existing": "No impact" },
    "Modify": { "use": "Add/alter tags on existing resources", "cost": "Medium", "existing": "Remediation task needed" },
    "DeployIfNotExists": { "use": "Deploy missing resource (e.g., diagnostic settings)", "cost": "High", "existing": "Remediation task needed" },
    "DenyAction": { "use": "Block delete action on critical resources", "cost": "Low", "existing": "Action blocked at runtime" }
  }
}
⚠ Policy Evaluation Cost
DeployIfNotExists policies trigger ARM deployments during remediation, which incur cost and time. Use Modify for simple tag changes instead. Deny is cheapest — it blocks before resource creation.
📊 Production Insight
We used DenyAction effect on production resource groups to prevent accidental deletion. When a developer tried to delete a resource group containing a critical database, the action was blocked immediately. No more accidental deletions.
🎯 Key Takeaway
Choose the right effect based on your goal: Deny for hard blocks, Audit for discovery, Modify/DeployIfNotExists for auto-remediation.
⚙ Quick Reference
11 commands from this guide
FileCommand / CodePurpose
policy-definition.json{Core Concepts
create-policy.ps1$definition = New-AzPolicyDefinition -Name 'require-costcenter-tag' `Writing Your First Custom Policy
assign-mg.shMG_ID="my-root-group"Assigning Policies at Scale with Management Groups
remediation-policy.json{Remediation
compliance-query.kqlpolicyresourcesCompliance Dashboard and Reporting
azure-pipeline.ymltrigger:Policy as Code
alert-rule.ps1$actionGroup = New-AzActionGroup -Name 'PolicyAlertGroup' -ShortName 'Policy' -E...Production Monitoring and Alerting for Policy Compliance
cost-policy.json{Cost Management with Azure Policy
assign-regulatory-initiative.shaz policy set-definition show \Regulatory Compliance Built-in Initiatives
enable-defender-plans.shaz security pricing create --name "CloudPosture" --tier "Standard"Microsoft Cloud Security Benchmark and Defender for Cloud In
effect-comparison.json{Azure Policy Effects Deep Dive and Evaluation Logic

Key takeaways

1
Azure Policy enforces compliance
Define rules using JSON, assign to scopes, and use effects like Deny, Audit, or DeployIfNotExists.
2
Start with Audit, not Deny
Always test policies with Audit effect to understand impact before enforcing Deny in production.
3
Use management groups for scale
Assign policies at the management group level to apply to all child subscriptions, reducing duplication.
4
Automate with Policy as Code
Store definitions in Git, validate with CI/CD, and deploy via pipelines for version control and auditability.

Common mistakes to avoid

3 patterns
×

Not planning policy compliance properly before deployment

Fix
Design your architecture with redundancy, scaling, and security in mind from the start.
×

Ignoring Azure best practices for policy compliance

Fix
Follow Microsoft's Well-Architected Framework and review Azure Advisor recommendations regularly.
×

Overlooking cost implications of policy compliance

Fix
Set budgets and alerts, right-size resources, and use Azure pricing calculator before deploying.
INTERVIEW PREP · PRACTICE MODE

Interview Questions on This Topic

Q01JUNIOR
Explain Azure Policy & Compliance and its use cases.
Q02JUNIOR
How does Azure Policy & Compliance handle high availability?
Q03JUNIOR
What are the security best practices for policy compliance?
Q04JUNIOR
How do you optimize costs for policy compliance?
Q05JUNIOR
Compare Azure policy compliance with self-hosted alternatives.
Q01 of 05JUNIOR

Explain Azure Policy & Compliance and its use cases.

ANSWER
Microsoft Azure — Azure Policy & Compliance is an Azure service for managing policy compliance in the cloud. Use it when you need reliable, scalable policy compliance without managing underlying infrastructure.
FAQ · 6 QUESTIONS

Frequently Asked Questions

01
What is the difference between Azure Policy and RBAC?
02
Can Azure Policy block resource creation?
03
How do I remediate existing non-compliant resources?
04
How can I test a policy before enforcing it?
05
What is a policy initiative?
06
How do I handle policy conflicts?
N
Naren Founder & Principal Engineer

20+ years shipping production infrastructure and CI/CD at scale. Lessons pulled from things that broke in production.

Follow
Verified
production tested
July 12, 2026
last updated
1,983
articles · all by Naren
🔥

That's Azure. Mark it forged?

6 min read · try the examples if you haven't

Previous
Managed Identities & Service Principals
7 / 55 · Azure
Next
Azure vs AWS vs GCP