AZ-500 Objective 4.1: Implement and Manage Enforcement of Cloud Governance Policies
AZ-500 Exam Focus: This objective covers cloud governance and Key Vault security including Azure Policy with policy definitions (IF-THEN conditions), effects (Deny, Audit, DeployIfNotExists, Modify), initiatives grouping policies, assignment at subscription/resource group scope with exclusions, compliance evaluation and remediation. Key Vault network settings with Private Endpoints (private IP), Service Endpoints, firewall rules, and trusted Microsoft services. Access control using vault access policies (legacy per-object permissions) or Azure RBAC (recommended unified model) with built-in roles (Administrator, Secrets Officer, Secrets User). Managing secrets, keys, certificates with versions, lifecycle operations, tagging. Key rotation policies with automatic rotation schedules, secret rotation via automation. Backup and recovery using soft delete (7-90 day retention), purge protection, backup blobs, restore procedures.
Understanding Cloud Governance and Key Vault Security
Cloud governance ensures Azure resources comply with organizational standards, regulatory requirements, and security best practices through automated policy enforcement and centralized secret management. Governance challenges include resource proliferation with teams deploying resources without oversight leading to security gaps and compliance violations, configuration drift where resources deviate from approved configurations over time increasing security risks, credential sprawl with secrets scattered across applications, configuration files, and documentation creating management nightmares and security vulnerabilities, insufficient auditing making it difficult to prove compliance and investigate security incidents, inconsistent security practices across teams and projects resulting in uneven security posture, and manual enforcement requiring constant vigilance and leading to human error. Traditional approaches relied on manual reviews, documentation-based policies, and decentralized secret management but lacked real-time enforcement, automated compliance assessment, and centralized credential lifecycle management.
Azure provides comprehensive governance through Azure Policy enforcing standards at scale—defining rules as code, automatically evaluating resources, preventing non-compliant deployments, and remediating existing resources. Policy covers security requirements (encryption must be enabled), operational standards (required tags for cost tracking), compliance mandates (resources must be in approved regions), and resource configurations (allowed VM sizes, storage account types). Azure Key Vault provides centralized secret management protecting credentials, encryption keys, and certificates with hardware security module (HSM) backing for keys, network isolation with Private Endpoints, granular access control through Azure RBAC, comprehensive auditing of secret access, automatic key rotation policies, soft delete protection against accidental deletion, and backup capabilities for disaster recovery. Together they enable organization-wide governance ensuring resources meet security requirements while protecting sensitive credentials from unauthorized access, loss, or compromise. This objective explores Azure Policy for enforcing cloud governance policies and Azure Key Vault for secure secret management including network security, access control, lifecycle management, rotation, backup, and recovery procedures essential for maintaining security and compliance at scale.
Azure Policy - Creating and Assigning Policies
Policy Definitions and Structure
Azure Policy definition specifies compliance rule as JSON document defining conditions to evaluate and action to take when conditions met. Policy structure: Mode determines resource types evaluated—"Indexed" for resources supporting tags and location (most resources), "All" for all resource types including those without tags. DisplayName and description document policy purpose. Metadata includes category for organization (Security, Compute, Monitoring), version, and additional information. Parameters make policies reusable accepting values at assignment time (example: listOfAllowedLocations parameter accepts location array). PolicyRule contains IF-THEN logic: IF section defines conditions to evaluate (resource type, property values, logical operators), THEN section defines effect (action when conditions match). Policy rule example enforcing storage encryption: IF: resourceType equals Microsoft.Storage/storageAccounts AND properties.encryption.services.blob.enabled notEquals true, THEN: deny (prevents creation/update of unencrypted storage). Common conditions: Resource type (Microsoft.Compute/virtualMachines), resource location (location in allowed list), tags (specific tag exists with required value), resource properties (encryption enabled, HTTPS required, specific SKU), resource existence (related resources must exist). Logical operators: allOf (all conditions must be true—AND logic), anyOf (at least one condition true—OR logic), not (negates condition).
Policy effects determine action when policy rule matches: Deny prevents resource creation or update, most restrictive effect, returns error explaining policy violation, use for security requirements that must be enforced. Audit creates warning event in activity log when non-compliant resource detected, doesn't prevent deployment, suitable for discovering non-compliant resources before enforcing. AuditIfNotExists evaluates if related resource exists (example: if VM exists, audit if antimalware extension doesn't exist), discovers missing security configurations. DeployIfNotExists automatically deploys resource if doesn't exist (example: if SQL server created without auditing, automatically enable auditing), remediates missing configurations, requires managed identity with permissions to deploy. Modify adds, updates, or removes resource tags, changes property values, enforces tagging standards or configuration changes. Append adds fields to resource during creation (example: add subnet configuration to virtual network), deprecated in favor of Modify. Disabled turns off policy evaluation temporarily without removing assignment. Effect selection: Use Deny for hard requirements (encryption, locations, resource types), Audit for soft requirements or initial compliance assessment, DeployIfNotExists for automatic remediation of missing configurations, Modify for tag enforcement and property updates.
Creating Custom Policies and Initiatives
Built-in policies: Azure provides 300+ built-in policies covering common scenarios (require tag on resources, allowed locations, allowed virtual machine SKUs, enforce HTTPS for storage accounts, require encryption for SQL databases, enforce HTTPS for App Service, audit VM without managed disks). Start with built-in policies reducing custom development effort. Custom policies: Create for organization-specific requirements. Creation: Portal—Policy → Definitions → Policy definition → Definition location (management group or subscription for scope), Name, Description, Category (existing or new), Policy rule (JSON editor with IF-THEN logic), Parameters (optional variables) → Save. Example custom policy denying public IPs: {. Test policies in non-production before applying broadly. Initiatives (Policy Sets): Group multiple related policies into single unit simplifying assignment and management. Built-in initiatives: Azure Security Benchmark (150+ policies for comprehensive security), PCI DSS 3.2.1 (30+ policies for payment card compliance), NIST SP 800-53 (800+ controls for government compliance), ISO 27001 (50+ policies for information security management). Create custom initiative: Policy → Definitions → Initiative definition → Add policy definitions (search and add built-in or custom policies), Configure parameters, Organize by categories → Save. Example security baseline initiative: Include policies for encryption, HTTPS, network security, logging, identity, access control. Initiative provides: Single assignment for multiple policies, simplified compliance reporting (initiative compliance percentage), logical grouping of related requirements.
"if": {
"field": "type",
"equals": "Microsoft.Network/publicIPAddresses"
},
"then": {
"effect": "deny"
}
}
Policy assignment: Applies policy or initiative to scope determining where evaluated. Scope: Management group (all subscriptions in group), subscription (all resources in subscription), resource group (resources in specific group), individual resource (rare). Assignments inherit to child scopes (assigned at subscription applies to all resource groups and resources). Exclusions: Exempt specific scopes from policy evaluation (example: assign deny public IPs at subscription, exclude test resource group for experimentation), document exclusion justification. Parameters: Provide values for policy parameters at assignment (example: allowed locations policy—specify [East US, West US] at assignment). Non-compliance messages: Custom message shown when policy prevents deployment explaining violation and remediation. Managed identity: Required for DeployIfNotExists and Modify policies (policy needs permissions to deploy/modify resources), system-assigned or user-assigned identity, grant appropriate permissions (Contributor for deployments). Assignment process: Policy → Assignments → Assign policy or initiative → Scope: Select management group, subscription, or resource group → Exclusions: Optionally exclude specific resources → Parameters: Provide parameter values → Remediation: Configure for DeployIfNotExists policies → Review + Create. Effect precedence: Multiple policies can apply to same resource, deny effect has highest precedence (one deny blocks deployment regardless of other policies), disabled effect excluded from evaluation.
Policy Compliance and Remediation
Compliance evaluation: Automatic evaluation every 24 hours for all assigned policies, on-demand evaluation when resource created or updated, compliance scan triggered after policy assignment. Compliance results: Portal—Policy → Compliance → Shows compliance percentage, number of non-compliant resources per policy, policies not started (evaluation not yet run), exempt resources. Compliance states: Compliant (resource meets policy requirements), Non-compliant (resource violates policy), Conflict (multiple policies with contradictory effects), Exempt (resource excluded from policy), Not started (evaluation pending). Viewing non-compliant resources: Policy → Compliance → Select policy → Non-compliant resources tab → Lists resources with reason for non-compliance, clicking resource shows details (which policy rule failed, property values causing violation). Non-compliance reasons: Deny effect blocked deployment (user attempted to create non-compliant resource), Audit effect logged violation (existing resource found non-compliant during evaluation), Missing required property (resource lacks mandatory field), Property value out of range (value doesn't meet policy constraints). Remediation: Process of bringing non-compliant resources into compliance. Automatic: DeployIfNotExists policies automatically deploy missing resources, Modify policies automatically update tags or properties. Manual: Admin reviews non-compliant resources, manually updates resources to comply, re-evaluation detects compliance. Remediation tasks: For DeployIfNotExists and Modify policies, create remediation task applying policy retroactively to existing non-compliant resources (policies normally apply only to new/updated resources, remediation applies to existing). Create remediation: Policy → Remediation → Select policy with DeployIfNotExists or Modify effect → Create remediation task → Specify scope and managed identity → Remediate. Task runs deployment for each non-compliant resource. Track progress in Remediation tasks view.
Policy exemptions: Waive policy enforcement for specific resources with documented justification. Exemption categories: Waiver (resource exempt for specific reason—planned maintenance window, approved exception), Mitigation (resource has compensating control—uses alternative security mechanism). Exemption properties: Scope (subscription, resource group, or specific resources), policy assignment, exemption category, expiration date (maximum 2 years, recommended for time-limited exceptions), description (document business justification, approval, and review date). Create exemption: Resource → Policies → Non-compliant policies → Create exemption → Select category, provide description and justification, set expiration → Create. Best practice: Use sparingly, document thoroughly, set expiration dates, regular reviews. Policy testing: Start with Audit effect discovering non-compliance without blocking deployments, review audit results over period (1-4 weeks), identify false positives requiring policy adjustment or legitimate exceptions, after tuning switch to Deny effect for enforcement, test in non-production environment first, gradual rollout (test resource group → non-prod subscription → prod subscription). Best practices: Assign policies at highest appropriate scope (management group for organization-wide), use built-in policies and initiatives where possible, start with Audit before Deny giving teams time to remediate, provide clear non-compliance messages guiding users to fix, implement exemptions with expiration dates and documented justification, regular compliance reviews with stakeholders, automate remediation for DeployIfNotExists policies, integrate policy compliance in CI/CD pipelines (Azure DevOps policy validation), document custom policies with business justification and ownership, monitor policy compliance trends over time, combine with Azure Blueprints for complete environment governance.
Key Vault Network Settings
Firewall and Virtual Network Integration
Key Vault network settings control network-level access protecting secrets, keys, and certificates from unauthorized network exposure. Default configuration: Public endpoint accessible from any internet location, firewall allows all networks (insecure default), any user with credentials can access from anywhere. Firewall and virtual networks: Configure: Key Vault → Networking → Firewalls and virtual networks → Three options: Allow public access from all networks (default, least secure, use only for development or when required), Allow public access from specific virtual networks and IP addresses (selected networks with firewall rules), Disable public access (most secure, requires Private Endpoint for access). Selected networks configuration: Virtual networks—add VNet subnets (requires Service Endpoint Microsoft.KeyVault enabled on subnet first), IP networks—add public IPv4 address ranges for on-premises or internet clients (single IPs or CIDR ranges), allow trusted Microsoft services—exception for Azure services (Virtual Machines, App Service, Azure Data Factory, Azure Backup, Azure Site Recovery, Azure DevOps) bypassing firewall. Service Endpoints: Azure networking feature routing Key Vault traffic over Azure backbone instead of internet, optimized routing and reduced latency, enables VNet-based firewall rules, doesn't provide private IP (still uses public endpoint). Enable: VNet → Subnets → Select subnet → Service endpoints → Add Microsoft.KeyVault → Save. Add subnet to Key Vault: Key Vault → Networking → Virtual networks → Add existing virtual network → Select VNet and subnet (must have Service Endpoint) → Add. Benefits: Improved performance, VNet-based access control, reduced internet exposure.
Trusted Microsoft services bypass: Allows specific Azure services accessing Key Vault even when firewall configured or public access disabled. Trusted services: Azure Virtual Machines (retrieving certificates for VM extensions), Azure App Service and Azure Functions (retrieving application secrets), Azure Resource Manager (deploying with ARM templates using Key Vault references), Azure Backup (backing up Key Vault), Azure Site Recovery (failover with Key Vault secrets), Azure DevOps (pipelines accessing secrets), Azure Data Factory (retrieving credentials for data integration), Azure SQL Database (customer-managed encryption keys), Azure Disk Encryption (disk encryption keys). Enable: Key Vault → Networking → Allow trusted Microsoft services to bypass this firewall → Yes. Rationale: Operational Azure services require Key Vault access for functionality, trusted services have security controls and audit trails, alternative would require overly permissive firewall rules. Best practice: Enable for operational services, review trusted service access regularly, ensure services use managed identities for Key Vault authentication. Disable public network access: Completely disables public endpoint, Key Vault accessible only via Private Endpoint, most secure configuration, use for production Key Vaults with sensitive secrets. Configure: Key Vault → Networking → Public access → Disabled → All internet access blocked, connection attempts fail. Requires Private Endpoint deployed first. Network troubleshooting: Connection fails from expected location—verify firewall includes client network, verify Service Endpoint enabled on subnet if using VNet rules, verify Private Endpoint configured if public access disabled, check client IP against allowed ranges. Test connectivity: nslookup myvault.vault.azure.net (resolves to private IP if Private Endpoint used, public IP otherwise), Test-NetConnection myvault.vault.azure.net -Port 443, curl https://myvault.vault.azure.net (should fail if firewall blocks, succeed if allowed).
Private Endpoint Configuration
Private Endpoint provides dedicated private IP address from VNet for Key Vault eliminating public internet exposure. Architecture: Private Endpoint deployed in VNet subnet, receives private IP from subnet address space, links to Key Vault (target resource), DNS resolution required (privatelink.vaultcore.azure.net resolves to private IP), traffic between VNet and Key Vault over Microsoft backbone. Deploy Private Endpoint: Portal—Private Link Center or Key Vault → Networking → Private endpoint connections → Add → Subscription, resource group, name, region (must match VNet), target sub-resource: vault → Networking: Select VNet and subnet → Private DNS integration: Yes (automatically creates private DNS zone or integrates with existing) → Create. CLI: az network private-endpoint create --name kvpe --resource-group rg --vnet-name vnet --subnet subnet --private-connection-resource-id /subscriptions/.../Microsoft.KeyVault/vaults/myvault --group-id vault --connection-name kvconn. Private DNS zone: Automatic integration creates privatelink.vaultcore.azure.net zone with A record pointing vault FQDN to private IP, VNet links to private DNS zone, DNS queries for myvault.vault.azure.net resolve to private IP. Manual DNS: On-premises DNS conditional forwarder for privatelink.vaultcore.azure.net pointing to Azure DNS (168.63.129.16), or configure hosts file (not recommended for production).
Multiple Private Endpoints: Create separate endpoints in different VNets for multi-region access, connect from multiple VNets without peering (each VNet has own endpoint), hub-spoke architecture (private endpoint in hub, spokes access via VNet peering). Benefits: Key Vault accessible only from connected networks, no public internet exposure, traffic over private Microsoft network (lower latency, higher security), suitable for hybrid scenarios (on-premises via VPN/ExpressRoute to VNet with private endpoint). Private Endpoint and firewall: Combine for defense-in-depth—disable public access (only private endpoint works) OR enable selected networks (both private endpoint and allowed public IPs work). Recommended: Disable public access completely when Private Endpoint configured. Testing Private Endpoint: Verify DNS resolution: nslookup myvault.vault.azure.net (should return private IP from subnet range), Verify connectivity from VNet: Test-NetConnection from VM in VNet to private IP port 443, Verify public access blocked: Attempt connection from internet (should fail), Retrieve secret from application in VNet using SDK (should succeed). Best practices: Use Private Endpoints for all production Key Vaults containing sensitive secrets, disable public network access when Private Endpoint deployed, implement Private DNS zone for automatic name resolution, deploy private endpoints in hub VNet for centralized management, use VNet peering connecting spoke VNets to hub with private endpoint, document private endpoint configuration and DNS setup, test connectivity from all expected networks before production, monitor private endpoint connections with diagnostic logs, implement NSG rules on private endpoint subnet for additional security, regular security reviews of network configuration, combine with firewall rules for hybrid scenarios requiring limited public access.
Key Vault Access Control
Vault Access Policies vs Azure RBAC
Azure Key Vault supports two access control models: Vault access policies (legacy model with per-object-type permissions) and Azure RBAC (recommended unified model with role-based access). Vault access policies (classic): Fine-grained permissions per Azure AD principal per object type (keys, secrets, certificates). Permission types: Key permissions (cryptographic operations—Decrypt, Encrypt, Unwrap Key, Wrap Key, Verify, Sign; management operations—Get, List, Update, Create, Import, Delete, Recover, Backup, Restore, Purge; rotation—Rotate, GetRotationPolicy, SetRotationPolicy), Secret permissions (Get, List, Set, Delete, Recover, Backup, Restore, Purge), Certificate permissions (Get, List, Update, Create, Import, Delete, Recover, Backup, Restore, ManageContacts, ManageIssuers, GetIssuers, ListIssuers, SetIssuers, DeleteIssuers, Purge). Configure: Key Vault → Access policies → Add Access Policy → Select template (Key & Secret Management, Certificate Management, Key Management, Secret Management, Application—limited read access) or configure individual permissions → Select principal (user, group, service principal, managed identity) → Add → Save. Permission templates: Key Management (all key operations), Secret Management (all secret operations), Certificate Management (all certificate operations), Key & Secret Management (both keys and secrets), Application (Get for keys and secrets—minimum for applications). Access policies limitations: Permissions granted at vault level not per-object (can't restrict user to specific secret), complex permission matrix with many options, separate from Azure RBAC (different model for Key Vault vs other Azure services), difficult to audit and manage at scale, doesn't support management group scope.
Azure RBAC (recommended): Unified access control model using Azure built-in and custom roles, consistent with other Azure services, supports management group, subscription, resource group, and Key Vault scope. Enable: Key Vault → Access configuration → Permission model → Azure role-based access control → Save (converts existing access policies to role assignments, access policies no longer editable). Built-in data plane roles: Key Vault Administrator (all operations on keys, secrets, certificates except manage permissions), Key Vault Certificates Officer (all certificate operations—Get, List, Update, Create, Import, Delete, Recover, Backup, Restore, ManageContacts, ManageIssuers, Purge), Key Vault Crypto Officer (all key operations—cryptographic and management), Key Vault Secrets Officer (all secret operations—Get, List, Set, Delete, Recover, Backup, Restore, Purge), Key Vault Crypto User (cryptographic operations—Decrypt, Encrypt, Unwrap Key, Wrap Key, Verify, Sign, read keys), Key Vault Secrets User (read secret content—Get secret value, list secrets), Key Vault Certificate User (read certificates), Key Vault Reader (read metadata of keys, secrets, certificates but not values—list names, properties), Key Vault Data Access Administrator (manage access control, no data access), Key Vault Crypto Service Encryption User (wrap/unwrap keys for service-side encryption). Management plane roles: Key Vault Contributor (manage vault—create, delete, configure but no data access), Owner (full control including permissions), Reader (view vault but no data access). Assign roles: Key Vault → Access control (IAM) → Add role assignment → Select role → Assign access to: User, group, service principal, or Managed identity → Select principal → Review + assign.
Managed Identities and Service Principals
Managed identities: Azure AD identities for Azure services automatically managed by platform, eliminate credential storage in code or configuration, support system-assigned (lifecycle tied to resource) and user-assigned (independent lifecycle, reusable). Enable: Azure service → Identity → System-assigned: On → Save (creates identity), or User-assigned → Add → Select managed identity. Grant Key Vault access: Key Vault → Access control (IAM) → Add role assignment → Select role (Key Vault Secrets User for reading secrets, Key Vault Crypto User for encryption) → Assign to: Managed identity → Select resource → Assign. Application code: Use Azure SDK with DefaultAzureCredential automatically using managed identity: var credential = new DefaultAzureCredential();. No credentials in code. Supported services: Virtual Machines, App Service, Azure Functions, Logic Apps, Azure Container Instances, Azure Kubernetes Service, Azure Data Factory, Azure Databricks. Service principals: Azure AD application identities for external applications and automation, authenticate using client ID with secret (password) or certificate (recommended). Create: Azure AD → App registrations → New registration → Name → Register → Certificates & secrets → New client secret (or Upload certificate) → Copy value (shown once). Grant Key Vault access: Same as managed identity assignment but select service principal name. Application authentication:
var client = new SecretClient(new Uri("https://myvault.vault.azure.net"), credential);
var secret = await client.GetSecretAsync("secretname");var credential = new ClientSecretCredential(tenantId, clientId, clientSecret);. Best practice: Use certificates instead of secrets, rotate credentials regularly, store credentials in secure location (Azure Key Vault for secrets in bootstrap scenario or environment variables with restricted access).
var client = new SecretClient(vaultUri, credential);
Access control best practices: Use Azure RBAC for new Key Vaults (unified model, better management, consistent with Azure), migrate from access policies to RBAC on existing vaults, use managed identities for all Azure services (no credentials in code), use service principals with certificates for external applications (more secure than secrets), implement least privilege (Secrets User instead of Administrator when read-only needed), assign roles at appropriate scope (vault level generally, object level for specific secrets in preview), use Azure AD groups for role assignments (simplify management as users change), regularly audit access permissions (quarterly reviews removing unused access), combine with Conditional Access for user accounts (require MFA for Key Vault access), document access control architecture (who has access to what and why), separate Key Vaults by sensitivity (different vaults for dev, test, prod; different vaults for low and high sensitivity), implement JIT access for administrative operations (PIM for elevated access), enable diagnostic logging tracking access and permission changes, test access permissions (verify users have required access, verify unauthorized access denied), integrate access reviews in security processes (regular attestation of Key Vault permissions), maintain principle of least privilege (grant minimum permissions required for task), use custom RBAC roles for specific scenarios (combine permissions from built-in roles differently).
Managing Certificates, Secrets, and Keys
Secret and Key Operations
Secrets: Store any sensitive data as string value (passwords, connection strings, API keys, certificates as PFX). Create secret: Portal—Key Vault → Secrets → Generate/Import → Name (unique within vault), Value (sensitive data), Content type (optional metadata like application/json or text/plain), Set activation date (optional—secret becomes usable at date), Set expiration date (optional—secret expires at date), Enabled (yes/no) → Create. CLI: az keyvault secret set --vault-name myvault --name secretname --value "secret-value". PowerShell: Set-AzKeyVaultSecret -VaultName myvault -Name secretname -SecretValue (ConvertTo-SecureString "secret-value" -AsPlainText -Force). SDK: await client.SetSecretAsync("secretname", "secret-value");. Secret versions: Each update creates new version with unique identifier, previous versions retained (accessible by version ID), latest version always returned when version not specified. List versions: Portal—Secret → Versions tab → Shows all versions with creation date, CLI: az keyvault secret list-versions --vault-name myvault --name secretname. Retrieve secret: Portal—Secret → Show Secret Value (requires permission), CLI: az keyvault secret show --vault-name myvault --name secretname returns value, SDK: var secret = await client.GetSecretAsync("secretname"); var value = secret.Value.Value;. Use secret in application: Retrieve at startup or on-demand, cache if appropriate (balance performance vs freshness), refresh periodically (support rotation without restart).
Keys: Cryptographic keys for encryption, signing, and key wrapping. Key types: RSA (asymmetric, 2048/3072/4096-bit, most common), RSA-HSM (hardware security module protected, FIPS 140-2 Level 2 validated, higher security), EC (elliptic curve, P-256, P-384, P-521 curves), EC-HSM (HSM-protected elliptic curve), symmetric keys (AES for encryption—preview feature). Create key: Key Vault → Keys → Generate/Import → Options: Generate (Key Vault creates key), Import (upload existing key), Restore backup → Key type → RSA or EC → RSA key size (2048, 3072, 4096—larger more secure but slower), Set activation/expiration dates, Enabled → Create. Key operations: Cryptographic (Encrypt/Decrypt data, Sign/Verify signatures, Wrap/Unwrap keys, performed by Key Vault without exposing key material), Management (Get, List, Update, Create, Import, Delete, Recover, Backup, Restore, Purge, Rotate). Using keys in code: var keyClient = new KeyClient(vaultUri, credential);. Key never leaves Key Vault for HSM keys. Use cases: Customer-managed encryption keys for Azure services (Storage, SQL, Disk), data encryption in applications, digital signatures, key encryption keys (wrap other keys).
var key = await keyClient.GetKeyAsync("keyname");
var cryptoClient = new CryptographyClient(key.Value.Id, credential);
var encrypted = await cryptoClient.EncryptAsync(EncryptionAlgorithm.RsaOaep256, plaintext);
var decrypted = await cryptoClient.DecryptAsync(EncryptionAlgorithm.RsaOaep256, encrypted.Ciphertext);
Certificate Management
Certificates: X.509 certificates with automatic lifecycle management, Key Vault handles certificate generation, renewal, and storage. Certificate components: X.509 certificate (public certificate), private key (stored securely in Key Vault), secret (certificate + key exportable as PFX for use outside Key Vault). Certificate sources: Integrated Certificate Authorities (DigiCert, GlobalSign—automatic lifecycle), Self-signed (for testing and development), Non-integrated CA (manual renewal). Create certificate: Key Vault → Certificates → Generate/Import → Method of Certificate Creation: Generate (Key Vault creates certificate), Import (upload existing PFX/PEM), Certificate Name, Certificate Authority: Integrated CA (DigiCert, GlobalSign), Self-signed, or Non-integrated CA (manual process) → Advanced policy configuration: Subject (CN=example.com, O=Organization), DNS Names (SANs), Key type (RSA or EC), Key size (2048, 3072, 4096), Content type (PKCS #12 or PEM), Lifetime actions (auto-renew at percentage of lifetime or specific days before expiry, action: Automatically renew or Email contacts), Validity period (months, years) → Create. Integrated CA certificate creation: Key Vault generates key pair, creates CSR (Certificate Signing Request), submits CSR to CA, CA validates domain ownership (DNS or HTTP challenge), CA issues certificate, Key Vault receives and stores certificate. Auto-renewal: Key Vault monitors expiration, automatically renews before expiration (at configured percentage of lifetime), generates new CSR, contacts CA, receives renewed certificate, creates new certificate version. Non-integrated CA: Key Vault generates CSR, admin downloads CSR, submits to CA manually, CA issues certificate, admin uploads certificate to Key Vault. Manual renewal required.
Certificate versions: Each renewal creates new version, previous versions retained with expiration dates, applications use latest version by default (don't specify version in URL). Access certificate: Download: Portal—Certificate → Download in CER (public only) or PFX/PEM (with private key, requires export permission) format. Use in application: var certClient = new CertificateClient(vaultUri, credential);. Certificate policies: Define certificate properties (subject, validity, key type/size), Lifetime actions (when and how to renew), Issuer parameters (which CA, account credentials), configure during creation or update later: Certificate → Policy → Edit → Update fields → Save. Certificate operations: Enable/Disable certificate, Update policy (subject, validity, renewal settings), Merge CSR (for non-integrated CA—download CSR, obtain certificate from CA, merge certificate with pending request), Delete and recover (soft delete protection), Backup and restore, Tag for organization. Certificate contacts: Email addresses notified of certificate events (expiration approaching, renewal failed), Configure: Certificate → Contacts → Add email → Save. Best practices: Use integrated CAs for production (automatic renewal), enable auto-renewal for all certificates, set renewal trigger at 60-80% of lifetime (adequate time for troubleshooting if renewal fails), configure multiple contacts for notifications, use appropriate validity period (1-2 years for most certificates), monitor certificate expiration with alerts, test certificate renewal in non-production, document certificate purposes and owners, regularly review and remove unused certificates, use self-signed only for development/testing, implement certificate transparency for public-facing certificates.
var certificate = await certClient.GetCertificateAsync("certname");
var x509cert = new X509Certificate2(certificate.Value.Cer);
Key Rotation and Backup
Implementing Key Rotation
Key rotation replaces cryptographic keys reducing risk if key compromised. Manual rotation: Create new key or secret version manually, update applications to use new version, old versions retained for decrypting existing data. Automatic rotation: Configure policy for automatic rotation on schedule reducing operational overhead. Key rotation policy: Define schedule for automatic key rotation. Configure: Key → Rotation policy → Enable automatic key rotation → Rotation frequency (days before expiry or time period—30, 60, 90, 180, 365 days) → Notification (time before expiry to send notification, email or Event Grid) → Rotation action (automatically rotate or notify only) → Save. Example: Rotate key every 90 days automatically, notify 7 days before rotation. Secret rotation: More complex than keys as secret values arbitrary (not generated). Approach: Use Azure Automation, Functions, or Logic Apps for custom rotation logic, trigger rotation on schedule or Event Grid events, implement rotation workflow: Generate new secret value (call API to rotate password, regenerate connection string), store new value as new Key Vault secret version, old version remains for applications not yet updated, notify operations team of rotation. Key Vault managed storage accounts: Special feature for automatic storage account key rotation. Configure: Key Vault → Storage accounts → Add → Select storage account → Regeneration period (days) → Active key (key1 or key2 to rotate) → Save. Key Vault automatically regenerates storage key on schedule, stores as secret, applications retrieve current key from Key Vault.
Event Grid integration: Subscribe to Key Vault events triggering automation. Events: SecretNearExpiry (secret approaching expiration), SecretExpired, CertificateNearExpiry, CertificateExpired, SecretNewVersionCreated, KeyNewVersionCreated. Setup: Event Grid → Event Subscriptions → Create → Source: Key Vault → Event types: Select events → Endpoint: Azure Function, Logic App, Webhook → Create. Function implements rotation logic: Receive event, call external API to regenerate secret (database password, API key), update Key Vault with new secret value, log rotation activity. Rotation best practices: Rotate cryptographic keys annually minimum (quarterly or semi-annually for high-security), rotate secrets every 90 days (more frequently for critical systems—30-60 days), implement overlap period (new secret valid before old expires, grace period for application updates), design applications to retrieve secrets dynamically (fetch from Key Vault periodically not just at startup), use managed storage accounts for automatic storage key rotation, test rotation procedures in non-production first, monitor rotation events and alert on failures, document rotation procedures and schedules, automate rotation where possible (custom functions for complex scenarios), implement zero-downtime rotation (applications support both old and new version during transition), maintain rotation audit logs for compliance, notify stakeholders of planned rotations, have rollback procedures if rotation causes issues. Application considerations: Implement secret refresh logic (check for new version periodically), cache secrets appropriately (balance performance vs freshness—5-15 minutes typical), graceful handling of rotation (try new version, fall back to old if fails), logging of secret retrieval for audit, retry logic for transient Key Vault errors, circuit breaker pattern if Key Vault unavailable.
Backup and Recovery Procedures
Soft delete: Protection against accidental deletion, enabled by default on new vaults. Configuration: Key Vault → Properties → Soft delete → Retention days (7-90, default 90) → Enable. When enabled: Deleted secrets, keys, certificates move to deleted state, retained for retention period, recoverable during retention, automatically purged after retention expires. View deleted objects: Secrets → Manage deleted secrets (toggle) → Lists deleted secrets with deletion date, expiration date, CLI: az keyvault secret list-deleted --vault-name myvault. Recover deleted object: Portal—Deleted objects → Select → Recover, CLI: az keyvault secret recover --vault-name myvault --name secretname, restores object to active state with all versions. Purge deleted object: Permanently delete bypassing soft delete recovery. Portal—Deleted object → Purge, CLI: az keyvault secret purge --vault-name myvault --name secretname. Requires purge permission. Purge protection: Prevents purging deleted objects until retention period expires, required for compliance in regulated industries. Enable: Key Vault → Properties → Purge protection → Enable (cannot be disabled once enabled). When enabled: Deleted objects can't be purged until retention period expires, provides mandatory retention period, meets compliance requirements for immutability.
Backup: Export encrypted backup blob containing object data (all versions and metadata). Backup secret: az keyvault secret backup --vault-name myvault --name secretname --file secret-backup.blob, PowerShell: Backup-AzKeyVaultSecret -VaultName myvault -Name secretname -OutputFile backup.blob. Backup key: az keyvault key backup --vault-name myvault --name keyname --file key-backup.blob. Backup certificate: az keyvault certificate backup --vault-name myvault --name certname --file cert-backup.blob. Backup blobs: Encrypted (secure), contain all versions, region-restricted (restorable only in same subscription and geography), suitable for disaster recovery and migration. Backup entire vault: No built-in full vault backup, script backup of all objects: List all secrets, keys, certificates, iterate and backup each, store backups securely. Restore: Restore from backup blob: az keyvault secret restore --vault-name myvault --file secret-backup.blob, restores object with all versions and properties, fails if object with same name exists (delete first or restore to different vault). Restore considerations: Restore to same vault or different vault in same region/subscription, cross-region restore not supported (backup geography-restricted), HSM keys restore only to premium vaults (with HSM). Backup security: Store backup blobs in secure location (encrypted storage, access-controlled, geo-redundant for disaster recovery), implement retention policy (7 years financial, 6 years healthcare, 1-3 years general), offsite storage (separate subscription or on-premises for critical keys), immutable storage (prevent tampering with backup files).
Disaster recovery: Key Vault geo-redundancy—data replicated to secondary region within geography automatically, failover within geography automatic (no action needed), cross-geography requires custom replication. Cross-region replication: Implement custom process exporting secrets/keys and replicating to vault in target region, Azure Automation or Functions for continuous replication, failover requires application reconfiguration pointing to replica vault. Best practices: Enable soft delete on all vaults (required for production, default on new vaults), enable purge protection for production vaults (prevents accidental permanent deletion), configure 90-day soft delete retention (maximum protection), implement regular backup schedule (daily for critical vaults, weekly for standard vaults), automate backup with Azure Automation or Functions (scheduled runbooks backing up all objects), store backups in geo-redundant storage with encryption (redundancy for disaster recovery), test restore procedures regularly (quarterly minimum validating backup integrity), document backup and restore procedures (for disaster recovery playbook), implement immutable storage for backup blobs (meet compliance requirements, prevent tampering), maintain offsite backup copies for critical keys (separate geography or offline storage), monitor backup job success with alerts on failures (immediate notification of backup issues), combine soft delete, purge protection, and backups for defense-in-depth (multiple recovery mechanisms), regular disaster recovery drills (full vault recovery including network and access), audit backup and restore operations (track who backed up/restored what when), cross-region replication for mission-critical vaults (business continuity across geographies), implement backup retention aligning with compliance requirements (retain backups for required duration), secure backup storage separately from production Key Vault (different subscription, access controls).
Security Controls and Asset Management
Backup Security Controls
Protecting Key Vault backups critical as backup files contain sensitive keys and secrets. Access control: Store backup blobs in Azure Storage account, configure RBAC restricting access (Storage Blob Data Reader for backup restore, no write access prevents tampering), use separate storage account for backups (not general-purpose storage, dedicated backup storage), implement network restrictions on backup storage (Private Endpoints, firewall rules allowing only backup automation). Encryption: Backup blobs encrypted by Key Vault before export (native encryption), additional encryption at rest using storage account encryption (platform-managed or customer-managed keys), consider client-side encryption for additional layer (encrypt backup blob before storing). Immutable storage: Configure immutable blob storage preventing deletion or modification for specified period, time-based retention policy (retain for X days, months, years), legal hold for compliance investigations, meets compliance requiring tamper-proof backups (financial services—7 years, healthcare—6 years). Configure: Storage account → Containers → Access policy → Add policy → Immutability type: Time-based retention → Retention period → Lock policy. Geo-redundancy: Store backups in geo-redundant storage (GRS or GZRS), automatic replication to secondary region, protects against regional disasters, enables recovery if primary region unavailable. Offline backup: For highest-security keys (root CAs, master encryption keys), export backup and store offline (air-gapped storage, safe deposit box, offline tape), prevents any network-based compromise, requires manual process for disaster recovery.
Backup monitoring: Enable diagnostic logs on storage account tracking backup blob access, alert on unexpected access or deletion attempts, regular audit of backup retention (verify backups exist and are complete), automated backup validation (periodically test restore ensuring backup integrity). Backup lifecycle: Automated backup creation on schedule (Azure Automation runbook, Azure Functions timer trigger), backup encryption and upload to storage, geo-replication to secondary region, retention management (delete backups older than retention period), disaster recovery testing (quarterly restore drill). Best practices: Implement immutable storage for backup blobs preventing tampering, use geo-redundant storage for disaster recovery across regions, store backups separately from production (different subscription, tenant for highest security), encrypt backups at multiple layers (native Key Vault encryption + storage encryption), restrict access with RBAC (minimum required permissions for backup and restore), monitor backup storage access with alerts on anomalies, implement offline backup for critical keys (air-gapped storage for root keys), regular backup testing (quarterly validation of restore process), document backup and restore procedures (disaster recovery playbook), audit backup access regularly (who accessed backup blobs when), automate backup lifecycle (creation, retention, testing), combine multiple controls for defense-in-depth (access control + encryption + immutability + monitoring).
Asset Management Security
Asset management tracks and secures Azure resources ensuring proper governance. Resource tagging: Apply metadata to resources for organization, cost tracking, access control, compliance. Required tags: Environment (Production, Development, Testing), Owner (team or individual responsible), CostCenter (charge-back code), DataClassification (Confidential, Internal, Public), ComplianceRequirement (PCI, HIPAA, SOC2). Enforce tagging: Azure Policy requiring tags on resources (deny creation without required tags), initiative for complete tagging strategy, policy effects: Deny (prevents deployment without tags), Modify (automatically adds tags), Append (adds default values). Example policy: Require Environment and Owner tags on all resources. Resource locks: Prevent accidental deletion or modification. Lock types: CanNotDelete (allows read and modify but prevents deletion), ReadOnly (allows only read operations, prevents modification and deletion). Apply locks: Resource → Locks → Add lock → Lock type → Notes → OK. Inheritance: Locks inherit to child resources (lock on resource group applies to all resources in group). Use cases: Production resources requiring stability (prevent accidental deletion of database, storage), shared infrastructure (prevent modification of networking resources). Resource groups: Logical container for related resources, enables bulk operations (apply policies, tags, locks to group), RBAC assignment at group level, lifecycle management (delete group removes all resources). Best practice: Organize resources by application, environment, or lifecycle (app-prod-rg, app-dev-rg). Azure Resource Graph: Query and explore resources at scale, KQL-based queries across subscriptions, identify non-compliant resources, track resource changes over time. Example: Find all storage accounts without encryption: Resources | where type == 'microsoft.storage/storageaccounts' | where properties.encryption.services.blob.enabled != true.
Inventory management: Maintain inventory of critical assets (Key Vaults, storage accounts, databases, VMs), document purpose, owner, data classification, compliance requirements, regularly review inventory removing unused resources. Asset security baseline: Define security requirements per asset type (Key Vaults: Private Endpoint, RBAC, soft delete; Storage: Private Endpoint, encryption, firewall), Azure Policy enforcing baseline, Security Center recommendations for non-compliant assets, regular security assessments validating compliance. Change management: Document changes to critical assets, approval process for production changes, Azure Policy auditing resource changes (audit log in Activity Log), change tracking for configuration drift detection. Best practices: Implement comprehensive tagging strategy (required tags for all resources), enforce tags with Azure Policy (deny resources without tags), apply resource locks to production resources (prevent accidental deletion), use Resource Graph for inventory queries (find non-compliant resources at scale), maintain asset inventory with ownership and purpose (documentation for compliance), define security baselines per asset type (standardized security configurations), regular security assessments (quarterly reviews of asset compliance), implement change management for critical assets (documented approval for changes), use Azure Blueprints for repeatable environment deployment (consistent security configurations), monitor asset changes with Activity Log and Azure Policy (detect unauthorized modifications), regular cleanup of unused assets (reduce attack surface and costs), separate assets by security zones (production, development, test in separate resource groups or subscriptions), implement least privilege access to assets (RBAC at appropriate scope), document asset security controls (for audits and compliance), integrate asset management with CMDB (configuration management database for enterprise tracking).
Exam Preparation Tips
Key Concepts to Master
- Azure Policy: Policy definition (IF-THEN), effects (Deny, Audit, DeployIfNotExists, Modify), initiatives, assignment scope, exclusions, compliance evaluation
- Key Vault networking: Private Endpoints (private IP), Service Endpoints, firewall rules (selected networks), trusted Microsoft services, disable public access
- Key Vault access: Vault access policies (legacy) vs Azure RBAC (recommended), built-in roles (Administrator, Secrets Officer, Secrets User, Crypto User)
- Objects: Secrets (sensitive strings), Keys (cryptographic operations, RSA/EC, HSM), Certificates (X.509 with auto-renewal)
- Rotation: Automatic key rotation policy, secret rotation via automation, storage account managed keys, Event Grid integration
- Backup: Soft delete (7-90 days), purge protection, backup blobs, restore procedures, geography restrictions
- Security: Immutable storage for backups, geo-redundancy, offline backups for critical keys, access control on backup storage
Practice Questions
Sample AZ-500 Exam Questions:
- Question: Which Azure Policy effect prevents resource creation when policy rule matches?
- A) Audit
- B) Deny
- C) AuditIfNotExists
- D) Disabled
Answer: B) Deny - Deny effect prevents resource creation or modification when conditions match.
- Question: What Key Vault network feature provides a private IP address eliminating public internet exposure?
- A) Service Endpoint
- B) Firewall rule
- C) Private Endpoint
- D) VNet integration
Answer: C) Private Endpoint - Provides dedicated private IP from VNet subnet for Key Vault.
- Question: Which Key Vault access control model is recommended for new vaults?
- A) Vault access policies
- B) Shared access signatures
- C) Azure RBAC
- D) Account keys
Answer: C) Azure RBAC - Recommended unified access control model consistent with other Azure services.
- Question: What is the soft delete retention period range for Key Vault?
- A) 1-7 days
- B) 7-90 days
- C) 30-365 days
- D) 1-2 years
Answer: B) 7-90 days - Soft delete configurable from 7 to 90 days (default 90).
- Question: Which Azure Policy effect automatically deploys missing resources?
- A) Audit
- B) Modify
- C) DeployIfNotExists
- D) Append
Answer: C) DeployIfNotExists - Automatically deploys resource if doesn't exist (e.g., enable SQL auditing).
- Question: What Key Vault feature prevents deleted objects from being purged?
- A) Soft delete
- B) Purge protection
- C) Backup
- D) Access policies
Answer: B) Purge protection - Prevents permanent deletion during soft delete retention period.
- Question: Which built-in RBAC role allows reading secret values from Key Vault?
- A) Key Vault Reader
- B) Key Vault Contributor
- C) Key Vault Secrets User
- D) Key Vault Administrator
Answer: C) Key Vault Secrets User - Allows reading secret content; Reader only sees metadata.
- Question: What Azure feature groups multiple policies into a single assignment?
- A) Management group
- B) Resource group
- C) Initiative (Policy Set)
- D) Blueprint
Answer: C) Initiative (Policy Set) - Groups related policies for simplified management and compliance.
AZ-500 Success Tip: Remember Azure Policy effects: Deny blocks deployment, Audit logs violations, DeployIfNotExists auto-deploys, Modify updates properties. Initiatives group policies for simplified assignment. Key Vault networking: Private Endpoints (private IP, no public exposure), Service Endpoints (optimized routing), firewall (selected networks). Access control: Azure RBAC recommended (Administrator, Secrets Officer/User, Crypto Officer/User). Objects: Secrets (strings), Keys (crypto ops, RSA/HSM), Certificates (X.509 with auto-renewal). Soft delete 7-90 days (default 90), purge protection prevents permanent deletion. Backup blobs encrypted, geography-restricted. Combine soft delete + purge protection + backups for defense-in-depth.
Hands-On Practice Lab
Lab Objective
Implement cloud governance with Azure Policy and secure Key Vault including network isolation, access control, object management, and backup procedures.
Lab Activities
Activity 1: Create and Assign Azure Policy
- Create custom policy: Policy → Definitions → Policy definition → Name "Require-Storage-HTTPS" → Policy rule: Deny storage accounts without HTTPS → Save
- Assign policy: Policy → Assignments → Assign policy → Scope: Select subscription or resource group → Policy definition: Search "Require-Storage-HTTPS" → Assign
- Test policy: Attempt to create storage account with "Secure transfer required" disabled → Should be denied by policy → Enable HTTPS → Creation succeeds
- View compliance: Policy → Compliance → Select policy → View non-compliant resources (existing storage without HTTPS)
- Assign initiative: Policy → Assignments → Assign initiative → Select "Azure Security Benchmark" → Review included policies → Assign
Activity 2: Configure Key Vault Network Settings
- Create Key Vault: Key vaults → Create → Standard tier → Enable soft delete, purge protection → Create
- Configure firewall: Key Vault → Networking → Firewalls and virtual networks → Allow access from: Selected networks → Add your client IP → Allow trusted Microsoft services → Save
- Test access: Attempt to access from allowed IP (succeeds) → Attempt from different IP (blocked)
- (Optional) Create Private Endpoint: Key Vault → Networking → Private endpoint connections → Add → Select VNet and subnet → Enable private DNS integration → Create
- Verify Private Endpoint: nslookup myvault.vault.azure.net (should resolve to private IP) → Test connection from VM in VNet
Activity 3: Configure RBAC Access Control
- Enable RBAC: Key Vault → Access configuration → Permission model: Azure role-based access control → Save
- Assign roles: Key Vault → Access control (IAM) → Add role assignment → Key Vault Secrets User → Select your user account → Assign
- Test access: Create secret → Attempt to read secret (succeeds with Secrets User role) → Attempt to delete secret (fails without Secrets Officer role)
- Managed identity: Create App Service or VM → Enable system-assigned identity → Grant Key Vault Secrets User role to managed identity
- Test managed identity: Deploy code reading secret using DefaultAzureCredential → Verify retrieval succeeds without credentials in code
Activity 4: Manage Secrets, Keys, and Certificates
- Create secret: Key Vault → Secrets → Generate/Import → Name "db-connection", Value "Server=...;Database=..." → Set expiration date → Create
- Create key: Keys → Generate/Import → RSA 2048-bit → Name "encryption-key" → Create
- Create certificate: Certificates → Generate/Import → Subject CN=example.com → Self-signed → Validity 12 months → Create
- Version management: Update secret with new value → View versions → Retrieve specific version by ID
- Tagging: Add tags to objects (Environment: Production, Owner: TeamA) → Query by tags
Activity 5: Backup and Recovery
- Backup secret: CLI:
az keyvault secret backup --vault-name myvault --name db-connection --file secret-backup.blob→ Verify backup file created - Delete secret: Key Vault → Secrets → Select secret → Delete → Secret moves to deleted state
- View deleted: Secrets → Show deleted secrets → Verify secret appears with deletion date and recovery period
- Recover deleted: Select deleted secret → Recover → Secret restored to active state
- Test restore from backup: Delete secret → Purge (if purge protection disabled) → Restore:
az keyvault secret restore --vault-name myvault --file secret-backup.blob→ Verify secret restored - Configure rotation policy: Key → Rotation policy → Enable automatic rotation every 90 days → Save
Activity 6: Review and Document
- Policy compliance: Policy → Compliance → Review percentage compliant, list non-compliant resources → Document findings
- Key Vault security: Verify soft delete enabled (90 days), purge protection enabled, RBAC configured, network restrictions applied
- Access audit: Key Vault → Diagnostic settings → Enable logs → Query access logs in Log Analytics
- Backup verification: Verify backup blobs stored securely, test restore procedures, document backup schedule
- Document configuration: Create documentation covering policies assigned, Key Vault network settings, RBAC roles, objects managed, backup/recovery procedures
- Clean up: Delete Key Vault (moves to deleted state), purge deleted vault (if testing), remove policy assignments, delete resource group
Lab Outcomes
After completing this lab, you'll have hands-on experience with cloud governance and Key Vault security. You'll understand how Azure Policy enforces compliance through deny and audit effects, Key Vault network isolation with Private Endpoints and firewall rules protects secrets, Azure RBAC provides unified access control with role-based permissions, object management handles secrets, keys, and certificates with versioning, and backup/recovery procedures use soft delete, purge protection, and backup blobs. These practical skills demonstrate governance and secret management capabilities tested in AZ-500 exam and provide foundation for implementing comprehensive cloud governance in production Azure environments.
Frequently Asked Questions
How do you create, assign, and interpret Azure Policy?
Azure Policy enforces organizational standards and assesses compliance at scale across Azure resources. Policy evaluates resources comparing properties against business rules defined in policy definitions. Policy definition: JSON document specifying conditions and effects. Built-in policies: Azure provides hundreds of built-in policies (require tag, allowed locations, allowed VM SKUs, enforce HTTPS, require SQL encryption). Custom policies: Create organization-specific policies for unique requirements. Policy structure: Mode (Indexed for resource types supporting tags and locations, All for all resources), Parameters (variables making policies reusable—allowed locations parameter accepts location list), Policy rule with IF-THEN logic: IF condition (resource type = storage account AND encryption not enabled) THEN effect (audit or deny). Effects determine action when policy rule matches: Deny prevents resource creation/update, Audit logs non-compliant resources without blocking, AuditIfNotExists audits if related resource doesn't exist, DeployIfNotExists automatically deploys resource if missing (creates resource), Modify adds/updates/removes tags or properties, Disabled turns off policy evaluation. Create custom policy: Portal: Policy → Definitions → Policy definition → Mode, Category, Policy rule JSON → Save. Example deny policy: If resourceType = Microsoft.Storage/storageAccounts AND properties.encryption.services.blob.enabled != true THEN deny. Policy assignment: Assigns policy definition to scope (management group, subscription, resource group, resource). Scope determines where policy applies (child resources inherit assignments). Exclusions exempt specific resources from policy. Parameters provide values for policy parameters at assignment time. Assignment effects: New resources evaluated during creation (denied if non-compliant with Deny policy), existing resources evaluated for compliance (Audit discovers non-compliant resources). Compliance evaluation runs automatically every 24 hours or on-demand. Initiatives (Policy Sets): Group multiple policies into single assignment, simplifies management of related policies (security baseline initiative contains 50+ policies). Built-in initiatives: Azure Security Benchmark, PCI DSS, NIST 800-53, ISO 27001. Custom initiatives: Create by grouping custom and built-in policies. Interpreting policy results: Compliance dashboard shows percentage compliant, non-compliant resource count, policy effect (Deny, Audit), reason for non-compliance (which condition failed). Non-compliant resources: Click policy → View non-compliant resources → Shows resource name, compliance state, last evaluation, reason. Remediation: Create remediation task for DeployIfNotExists and Modify policies, applies policy retroactively to existing resources, generates managed identity for deployment. Policy exemptions: Waiver exempts resources from policy evaluation (planned maintenance, approved exceptions), Mitigation exempts with documented compensating control, specify expiration date (maximum 2 years), document justification. Best practices: Start with audit effects discovering non-compliance before blocking, use built-in policies and initiatives reducing custom policy development, assign policies at highest appropriate scope (management group for organization-wide), use policy parameters for flexibility, implement exemptions carefully with expiration dates, regular compliance reviews identifying and remediating non-compliant resources, combine policies in initiatives for related requirements, test policies on non-production before production assignment, document custom policies explaining business rule and intent, integrate with Azure DevOps enforcing policies in CI/CD, use Azure Policy Guest Configuration for in-VM configuration compliance.
Written by Joe De Coppi - Last Updated November 14, 2025