Azure Policy Enforces Compliance — But Only If Done Right
Azure Policy is the guardrail system for your cloud environment. It evaluates resources against organizational rules and can prevent non-compliant deployments. However, a poorly implemented policy framework creates false security — policies that audit but don’t enforce, overlapping assignments that conflict, or exemptions that undermine the entire system. This guide covers how to build an effective policy framework.
Threat Landscape and Attack Surface
Hardening Azure Policy requires understanding the threat landscape specific to this service. Azure services are attractive targets because they often store, process, or transmit sensitive data and provide control-plane access to cloud infrastructure. Attackers probe for misconfigured services using automated scanners that continuously sweep Azure IP ranges for exposed endpoints, weak authentication, and default configurations.
The attack surface for Azure Policy includes several dimensions. The network perimeter determines who can reach the service endpoints. The identity and access layer controls what authenticated principals can do. The data plane governs how data is protected at rest and in transit. The management plane controls who can modify the service configuration itself. A comprehensive hardening strategy addresses all four dimensions because a weakness in any single layer can be exploited to bypass the controls in other layers.
Microsoft’s shared responsibility model means that while Azure secures the physical infrastructure, network fabric, and hypervisor, you are responsible for configuring the service securely. Default configurations prioritize ease of setup over security. Every Azure service ships with settings that must be tightened for production use, and this guide walks through the critical configurations that should be changed from their defaults.
The MITRE ATT&CK framework for cloud environments provides a structured taxonomy of attack techniques that adversaries use against Azure services. Common techniques relevant to Azure Policy include initial access through exposed credentials or misconfigured endpoints, lateral movement through overly permissive RBAC assignments, and data exfiltration through unmonitored data plane operations. Each hardening control in this guide maps to one or more of these attack techniques.
Compliance and Regulatory Context
Security hardening is not just a technical exercise. It is a compliance requirement for virtually every regulatory framework that applies to cloud workloads. SOC 2 Type II requires evidence of security controls for cloud services. PCI DSS mandates network segmentation and encryption for payment data. HIPAA requires access controls and audit logging for health information. ISO 27001 demands a systematic approach to information security management. FedRAMP requires specific configurations for government workloads.
Azure Policy and Microsoft Defender for Cloud provide built-in compliance assessments against these frameworks. After applying the hardening configurations in this guide, run a compliance scan to verify your security posture against your applicable regulatory standards. Address any remaining findings to achieve and maintain compliance. Export compliance reports on a scheduled basis to satisfy audit requirements and demonstrate continuous adherence.
The Microsoft cloud security benchmark provides a comprehensive set of security controls mapped to common regulatory frameworks. Use this benchmark as a checklist to verify that your hardening effort covers all required areas. Each control includes Azure-specific implementation guidance and links to the relevant Azure service documentation.
Step 1: Start with Built-In Initiatives
# Assign Microsoft Cloud Security Benchmark
az policy assignment create \
--name mcsb-assignment \
--display-name "Microsoft Cloud Security Benchmark" \
--policy-set-definition "1f3afdf9-d0c9-4c3d-847f-89da613e70a8" \
--scope "/subscriptions/{sub}" \
--enforcement-mode Default
# Assign CIS Microsoft Azure Foundations
az policy assignment create \
--name cis-assignment \
--display-name "CIS Azure Foundations" \
--policy-set-definition "06f19060-9e68-4070-92ca-f15cc126059e" \
--scope "/subscriptions/{sub}"
Step 2: Enable Enforcement Mode
# Check current enforcement mode
az policy assignment list --query "[].{Name:name, Enforcement:enforcementMode}" -o table
# Update from DoNotEnforce to Default (enforcing)
az policy assignment update \
--name deny-public-storage \
--enforcement-mode Default
Many organizations deploy policies in DoNotEnforce mode for testing and never switch to enforcement. Regularly audit enforcement modes and escalate audit-only policies to deny/enforce.
Step 3: Create Deny Policies for Critical Controls
# Deny storage accounts without HTTPS
az policy assignment create \
--name deny-http-storage \
--display-name "Deny storage accounts without HTTPS" \
--policy "404c3081-a854-4457-ae30-26a93ef643f9" \
--scope "/subscriptions/{sub}" \
--params '{"effect": {"value": "Deny"}}'
# Deny public IP addresses
az policy definition create \
--name deny-public-ip \
--display-name "Deny Public IP creation" \
--mode All \
--rules '{
"if": {
"field": "type",
"equals": "Microsoft.Network/publicIPAddresses"
},
"then": {
"effect": "deny"
}
}'
az policy assignment create \
--name deny-public-ips \
--policy deny-public-ip \
--scope "/subscriptions/{sub}"
Step 4: Implement DeployIfNotExists for Auto-Remediation
# Auto-deploy diagnostic settings on storage accounts
az policy assignment create \
--name deploy-storage-diag \
--display-name "Deploy diagnostics for Storage" \
--policy "built-in-deploy-diag-policy-id" \
--scope "/subscriptions/{sub}" \
--params '{"effect": {"value": "DeployIfNotExists"}, "logAnalyticsWorkspaceId": {"value": "/subscriptions/{sub}/resourceGroups/rg-monitor/providers/Microsoft.OperationalInsights/workspaces/law-prod"}}' \
--mi-system-assigned --location eastus
# Grant the policy assignment's managed identity remediation permissions
az role assignment create \
--assignee $(az policy assignment show --name deploy-storage-diag --query identity.principalId -o tsv) \
--role "Contributor" \
--scope "/subscriptions/{sub}"
Step 5: Organize with Management Group Hierarchy
# Apply policies at management group level
az policy assignment create \
--name require-tags \
--display-name "Require Environment tag" \
--policy "871b6d14-10aa-478d-b590-94f262ecfa99" \
--scope "/providers/Microsoft.Management/managementGroups/mg-production" \
--params '{"tagName": {"value": "Environment"}}'
Assign policies at the highest appropriate level. Use management groups for organization-wide policies, subscriptions for workload-specific policies, and resource groups for exceptions.
Identity and Access Management Deep Dive
Identity is the primary security perimeter in cloud environments. For Azure Policy, implement a robust identity and access management strategy that follows the principle of least privilege.
Managed Identities: Use system-assigned or user-assigned managed identities for service-to-service authentication. Managed identities eliminate the need for stored credentials (connection strings, API keys, or service principal secrets) that can be leaked, stolen, or forgotten in configuration files. Azure automatically rotates the underlying certificates, removing the operational burden of credential rotation.
Custom RBAC Roles: When built-in roles grant more permissions than required, create custom roles that include only the specific actions needed. For example, if a monitoring service only needs to read metrics and logs from Azure Policy, create a custom role with only the Microsoft.Insights/metrics/read and Microsoft.Insights/logs/read actions rather than assigning the broader Reader or Contributor roles.
Conditional Access: For human administrators accessing Azure Policy through the portal or CLI, enforce Conditional Access policies that require multi-factor authentication, compliant devices, and approved locations. Set session lifetime limits so that administrative sessions expire after a reasonable period, forcing re-authentication.
Just-In-Time Access: Use Azure AD Privileged Identity Management (PIM) to provide time-limited, approval-required elevation for administrative actions. Instead of permanently assigning Contributor or Owner roles, require administrators to activate their role assignment for a specific duration with a business justification. This reduces the window of exposure if an administrator’s account is compromised.
Service Principal Hygiene: If managed identities cannot be used (for example, for external services or CI/CD pipelines), use certificate-based authentication for service principals rather than client secrets. Certificates are harder to accidentally expose than text secrets, and Azure Key Vault can automate their rotation. Set short expiration periods for any client secrets and monitor for secrets that are approaching expiration.
Step 6: Manage Exemptions Carefully
# Create time-bound exemption with justification
az policy exemption create \
--name legacy-app-exemption \
--policy-assignment deny-http-storage \
--scope "/subscriptions/{sub}/resourceGroups/rg-legacy" \
--exemption-category Waiver \
--description "Legacy app requires HTTP. Migration planned for Q3." \
--expires-on "2025-09-30T00:00:00Z"
Every exemption should have:
- A documented business justification
- An expiration date
- An owner responsible for remediation
- A compensating control
Step 7: Create Custom Policy Definitions
# Custom policy: deny resources without required tags
az policy definition create \
--name require-cost-center \
--display-name "Require CostCenter tag" \
--mode Indexed \
--rules '{
"if": {
"allOf": [
{"field": "tags['\''CostCenter'\'']", "exists": "false"},
{"field": "type", "notEquals": "Microsoft.Resources/subscriptions"}
]
},
"then": {"effect": "deny"}
}'
Step 8: Monitor Compliance
# Get compliance summary
az policy state summarize --query "policyAssignments[].{Assignment:policyAssignmentId, NonCompliant:results.nonCompliantResources}" -o table
# Get non-compliant resources for a specific assignment
az policy state list --policy-assignment deny-public-storage \
--filter "complianceState eq 'NonCompliant'" \
--query "[].{Resource:resourceId, Policy:policyDefinitionName}" -o table
Step 9: Create Remediation Tasks
# Trigger remediation for existing non-compliant resources
az policy remediation create \
--name remediate-storage-diag \
--policy-assignment deploy-storage-diag \
--resource-group rg-production
# Check remediation progress
az policy remediation show \
--name remediate-storage-diag \
--resource-group rg-production \
--query "{Status:provisioningState, Succeeded:deploymentStatus.totalDeployments}"
Step 10: Audit Policy Health
- Review compliance dashboard monthly
- Track compliance trend over time
- Audit exemptions quarterly — remove expired ones
- Test policies before production assignment
- Alert on compliance percentage drops
- Document policy decisions in a governance wiki
Defense in Depth Strategy
No single security control is sufficient. Apply a defense-in-depth strategy that layers multiple controls so that the failure of any single layer does not expose the service to attack. For Azure Policy, this means combining network isolation, identity verification, encryption, monitoring, and incident response capabilities.
At the network layer, restrict access to only the networks that legitimately need to reach the service. Use Private Endpoints to eliminate public internet exposure entirely. Where public access is required, use IP allowlists, service tags, and Web Application Firewall (WAF) rules to limit the attack surface. Configure network security groups (NSGs) with deny-by-default rules and explicit allow rules only for required traffic flows.
At the identity layer, enforce least-privilege access using Azure RBAC with custom roles when built-in roles are too broad. Use Managed Identities for service-to-service authentication to eliminate stored credentials. Enable Conditional Access policies to require multi-factor authentication and compliant devices for administrative access.
At the data layer, enable encryption at rest using customer-managed keys (CMK) in Azure Key Vault when the default Microsoft-managed keys do not meet your compliance requirements. Enforce TLS 1.2 or higher for data in transit. Enable purge protection on any service that supports soft delete to prevent malicious or accidental data destruction.
At the monitoring layer, enable diagnostic logging and route logs to a centralized Log Analytics workspace. Configure Microsoft Sentinel analytics rules to detect suspicious access patterns, privilege escalation attempts, and data exfiltration indicators. Set up automated response playbooks that can isolate compromised resources without human intervention during off-hours.
Continuous Security Assessment
Security hardening is not a one-time activity. Azure services evolve continuously, introducing new features, deprecating old configurations, and changing default behaviors. Schedule quarterly security reviews to reassess your hardening posture against the latest Microsoft security baselines.
Use Microsoft Defender for Cloud’s Secure Score as a quantitative measure of your security posture. Track your score over time and investigate any score decreases, which may indicate configuration drift or new recommendations from updated security baselines. Set a target Secure Score and hold teams accountable for maintaining it.
Subscribe to Azure update announcements and security advisories to stay informed about changes that affect your security controls. When Microsoft introduces a new security feature or changes a default behavior, assess the impact on your environment and update your hardening configuration accordingly. Automate this assessment where possible using Azure Policy to continuously evaluate your resources against your security standards.
Conduct periodic penetration testing against your Azure environment. Azure’s penetration testing rules of engagement allow testing without prior notification to Microsoft for most services. Engage a qualified security testing firm to assess your Azure Policy deployment using the same techniques that real attackers would employ. The findings from these tests often reveal gaps that automated compliance scans miss.
Hardening Checklist
- Built-in initiatives (MCSB, CIS) assigned
- Enforcement mode enabled (not audit-only)
- Deny policies for critical controls
- DeployIfNotExists for auto-remediation
- Management group hierarchy for policy inheritance
- Exemptions time-bound with justification
- Custom policies for organization-specific rules
- Compliance monitoring and dashboards
- Regular remediation tasks
- Quarterly policy health audit
For more details, refer to the official documentation: What is Azure Policy?, Get compliance data of Azure resources.