Lesson 2 of 4 Governance with Azure Policy and Infrastructure as Code

Using Built-in and Custom Policy Definitions

This lesson explains how a definition is structured, and how to create and test a custom rule.

Learning outcomes

After completing this lesson, you will be able to:

  • Choose when to write a custom definition.
  • Read a policy rule.
  • Explain what an alias is.
  • Describe a safe process for deploying a custom policy.

Using built-in definitions and initiatives

Always look for a built-in definition first. Microsoft maintains them, they use the correct aliases, and many have parameters. Security-related categories cover Key Vault, Storage, SQL, Network, Security Center and others. Built-in initiatives map whole frameworks, such as the Microsoft Cloud Security Benchmark.

A built-in definition often comes in several forms for one topic. One example audits whether Key Vault purge protection is on, another configures diagnostic settings through DeployIfNotExists, and a third restricts allowed locations. Reading the name carefully helps, because names begin with what the policy expects, for example Storage accounts should disable public network access.

True or false

Built-in definitions

Exam skills 1.3.1

Check how built-in definitions and initiatives are used.

Log in to try this activity Interactive activities are free with an account.

The structure of a definition

A custom definition is a JSON document. Its central part is the policyRule, an if-then structure. The following definition denies any storage account that allows Shared Key access. It uses a parameter for the effect so that it can begin in Audit.

{
  "mode": "All",
  "parameters": {
    "effect": {
      "type": "String",
      "allowedValues": ["Audit", "Deny", "Disabled"],
      "defaultValue": "Audit"
    }
  },
  "policyRule": {
    "if": {
      "allOf": [
        {"field": "type", "equals": "Microsoft.Storage/storageAccounts"},
        {"field": "Microsoft.Storage/storageAccounts/allowSharedKeyAccess", "notEquals": false}
      ]
    },
    "then": {"effect": "[parameters('effect')]"}
  }
}

The following table explains the main elements.

ElementPurpose
modeWhich resource types are evaluated. All covers resource groups, subscriptions and all types; Indexed covers types that support tags and location.
parametersValues set at assignment, which make a definition reusable.
ifA condition, built from field comparisons and the logical operators allOf, anyOf and not.
thenThe effect, and for Modify or DeployIfNotExists, the details of what to change.
fieldA resource property, written as an alias.
Match the pairs

Inside a policy definition

Exam skills 1.3.1

Match each element of a policy definition with its purpose.

Log in to try this activity Interactive activities are free with an account.

Aliases

Policy cannot use just any property path. Resource providers publish aliases, which are stable names for properties. The alias Microsoft.Storage/storageAccounts/allowSharedKeyAccess maps to a property in the resource's JSON. If a property has no alias, policy cannot evaluate it. You can search aliases with the Azure CLI, or use the VS Code extension for Azure Policy.

az provider show --namespace Microsoft.Storage --expand "resourceTypes/aliases" \
  --query "resourceTypes[?resourceType=='storageAccounts'].aliases[].name" -o tsv | grep -i sharedkey

A subtle trap appears in the example above: the condition is notEquals false, not equals true. If the property is not set, which is the default for this setting, Shared Key access is permitted. A rule that tests only for true would miss every account in which the property is null. Security rules should treat a missing value as noncompliant when the default is unsafe.

Testing and deploying a custom definition

A custom definition can be stored at a management group or subscription, and it can be assigned at or below that level, so store it at the highest level at which it will be used. The sequence below reduces risk.

  1. Author

    Write the rule, and check the alias for each property.

  2. Create

    Create the definition at the management group that will use it.

  3. Assign in Audit

    Assign it to a test subscription with the effect set to Audit.

  4. Evaluate

    Trigger a scan with az policy state trigger-scan, and compare the results with what you expect.

  5. Promote

    Add it to an initiative, assign it more widely, and move to Deny when the results are correct.

Group custom definitions into a custom initiative. An initiative gives one compliance figure, can be assigned once, and can be managed as code. It can also be added to Defender for Cloud as a custom security standard, so that the rules appear as recommendations.

Put in order

Rolling out a custom policy

Exam skills 1.3.1

Put the steps of deploying a custom definition in order.

Log in to try this activity Interactive activities are free with an account.
Worked example

Requiring a tag and blocking a location

A policy must prevent VMs from being created unless they carry a costCentre tag, but only in subscriptions under the Production management group. A second team asks to be excused for one experimental subscription until 31 December. What should you do?

Assign the built-in definition Require a tag on resources, or a custom equivalent limited to virtual machines, at the Production management group, with the tag name as a parameter. For the experimental subscription, create an exemption with an expiry date of 31 December and the category Waiver, so that the exception is recorded and ends by itself.

An exclusion on the assignment would also skip the subscription, but it has no expiry and no recorded reason. Moving the subscription out of the management group would remove all other policies from it too. A resource lock has no relation to tag rules.

Check yourself

A policy tests whether a property equals true, but accounts with the property unset slip through. Why?

Show answer

A null value is not true. The rule should use notEquals false when an unset value is unsafe.

Exam Tips

Remember for the exam

  • Look for a built-in definition before writing a custom one.
  • A property needs an alias before policy can evaluate it.
  • A definition can be assigned only at or below where it is stored.
  • Treat a missing value as noncompliant when the default is unsafe.