Skip to content

About

An open-source PowerShell module that gives Azure Policy authors a Pester-style DSL.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

Β 

History

249 Commits

Folders and files

Repository files navigation

Bylaw

CI coverage PowerShell Gallery Version PowerShell Gallery Downloads

Bylaw is a PowerShell module for writing Azure Policy in a Pester-style language. You describe what a compliant resource looks like, and Bylaw compiles that into Azure Policy definition JSON, in the Enterprise Policy as Code (EPAC) format or as plain definitions for other tools.

A simple example:

Policy 'storage-require-tls12' {

    Properties @{
        DisplayName = 'Storage accounts should require TLS 1.2'
        Category    = 'Storage'
        Version     = '1.0.0'
        Mode        = 'Indexed'
    }

    Resource 'Microsoft.Storage/storageAccounts' {
        Require 'TLS 1.2 or later' {
            Field minimumTlsVersion | Must -Be 'TLS1_2'
        }
    }

    Effect Deny
}

What Bylaw gives you over writing Azure Policy JSON by hand:

  • Desired state, not violation logic. You write what must be true. Bylaw works out the if condition that finds resources breaking it, including the negations and the handling of missing properties.
  • Short field names, checked at compile time. minimumTlsVersion becomes Microsoft.Storage/storageAccounts/minimumTlsVersion. A misspelled alias fails the build, rather than producing a policy that silently never matches.
  • Simple array conditions. Each replaces hand-written count and where expressions, and Count handles the rest.
  • Related resources written the same way. For AuditIfNotExists and DeployIfNotExists, you describe the related resource's compliant state with Require, and its field names are checked against its own type.
  • Less boilerplate. Effect parameters and their metadata are generated, and role names become role definition IDs.
  • Remediation checked against the rule. Modify and Append operations sit beside the requirements they fix, and the build warns when an operation changes a field no requirement checks. Deployment templates are checked against the parameters passed to them.
  • Initiatives checked against their policies. An initiative names the policies it includes, and the build checks that they exist and that the values passed to them fit their parameters.
  • Deterministic output. The same input always produces byte-identical files, so diffs show only real changes.

Bylaw only compiles. Deploy the output with EPAC, or any other tool that takes policy definition files.

Warning

Compiling a policy file runs it. A .bylaw.ps1 file is a PowerShell script, and Build-Bylaw runs it with your permissions. Each file runs in its own runspace, but that is not a security sandbox. Don't build files you don't trust. In CI, don't run Build-Bylaw on pull requests from forks with access to secrets.

Status

Bylaw is a preview on the PowerShell Gallery: the language may still change before 1.0. It has the compiler core (the language below, alias validation, EPAC and plain JSON output) and covers every Azure Policy effect: Audit, Deny, Disabled, Modify, Append, DenyAction, Manual, AuditIfNotExists and DeployIfNotExists, with Count for field and value counts. It also builds initiatives, checking each member against the policies it includes, and converts existing policy and initiative JSON into Bylaw files with ConvertTo-Bylaw, proving each conversion.

Install

Bylaw needs PowerShell 7.2 or later, on Windows, Linux or macOS. Compiling needs no Azure modules and no Azure connection.

Install it from the PowerShell Gallery. It is a prerelease, so it needs -Prerelease:

Install-PSResource -Name Bylaw -Prerelease

Or build it from source:

git clone https://github.com/markwragg/PowerShell-Bylaw.git
Set-Location PowerShell-Bylaw
./build/build.ps1 -Task Package
Import-Module ./out/Bylaw/Bylaw.psd1

Quick start

Save this as policies/storage-tls.bylaw.ps1:

Policy 'storage-require-tls12' {

    Properties @{
        DisplayName = 'Storage accounts should require TLS 1.2'
        Category    = 'Storage'
        Version     = '1.0.0'
        Mode        = 'Indexed'
    }

    Resource 'Microsoft.Storage/storageAccounts' {
        Require 'TLS 1.2 or later' {
            Field minimumTlsVersion | Must -Be 'TLS1_2'
        }
    }

    Effect Deny
}

Compile everything under policies:

Build-Bylaw ./policies -OutputPath ./Definitions/policyDefinitions

This writes Definitions/policyDefinitions/storage-require-tls12.json. Its rule denies storage accounts whose minimumTlsVersion is anything other than TLS1_2, including accounts that don't set it:

{
  "$schema": "https://raw.githubusercontent.com/Azure/enterprise-azure-policy-as-code/main/Schemas/policy-definition-schema.json",
  "name": "storage-require-tls12",
  "properties": {
    "displayName": "Storage accounts should require TLS 1.2",
    "policyType": "Custom",
    "mode": "Indexed",
    "metadata": {
      "version": "1.0.0",
      "category": "Storage"
    },
    "parameters": {
      "effect": {
        "type": "String",
        "metadata": {
          "displayName": "Effect",
          "description": "Enable or disable the execution of the policy"
        },
        "allowedValues": [
          "Audit",
          "Deny",
          "Disabled"
        ],
        "defaultValue": "Deny"
      }
    },
    "policyRule": {
      "if": {
        "allOf": [
          {
            "field": "type",
            "equals": "Microsoft.Storage/storageAccounts"
          },
          {
            "field": "Microsoft.Storage/storageAccounts/minimumTlsVersion",
            "notEquals": "TLS1_2"
          }
        ]
      },
      "then": {
        "effect": "[parameters('effect')]"
      }
    }
  }
}

Effect Deny became a parameter: allowed values Audit, Deny and Disabled, with a default of Deny. The policy behaves as written unless an assignment overrides the effect.

To see the output without writing files, use -PassThru:

Build-Bylaw ./policies -PassThru | Select-Object Name, Json

If something is wrong, the build fails, writes nothing, and reports every error with its file, line and keyword, and a link to each code's page in the wiki, which explains it and how to fix it:

Build failed with 1 error:
policies/storage-tls.bylaw.ps1:12 [Field] BYL2001: Field 'minimumTlsVersoin' of 'Microsoft.Storage/storageAccounts' is not in the alias snapshot. Did you mean 'minimumTlsVersion'? Use Field <name> -AllowUnknownAlias if the alias is newer than the snapshot, or refresh it with Update-BylawAliasCache.
More about this code:
  BYL2001: https://github.com/markwragg/PowerShell-Bylaw/wiki/Diagnostics-BYL2xxx#byl2001

A warning ends with its link, as See https://.... The wiki describes main, which can be a little ahead of the version you have installed.

EPAC is the default format, to return just name, properties use -Format PlainJson:

Build-Bylaw ./policies -OutputPath ./Definitions/policyDefinitions -Format PlainJson

This outputs the same way Azure publishes built-in ones, for New-AzPolicyDefinition, the Azure CLI, Bicep or Terraform. The policy is emitted as written: a literal effect stays literal and nothing is generated.

{
  "name": "storage-require-tls12",
  "properties": {
    "displayName": "Storage accounts should require TLS 1.2",
    "policyType": "Custom",
    "mode": "Indexed",
    "metadata": {
      "version": "1.0.0",
      "category": "Storage"
    },
    "policyRule": {
      "if": {
        "allOf": [
          {
            "field": "type",
            "equals": "Microsoft.Storage/storageAccounts"
          },
          {
            "field": "Microsoft.Storage/storageAccounts/minimumTlsVersion",
            "notEquals": "TLS1_2"
          }
        ]
      },
      "then": {
        "effect": "Deny"
      }
    }
  }
}

Before and after

A storage policy with two requirements: public network access must be disabled, and no IP rule may allow every address. It applies only to two kinds of storage account.

You write:

Policy 'storage-deny-public-network-access' {

    Properties @{
        DisplayName = 'Storage accounts should disable public network access'
        Description = 'Denies storage accounts that allow public network access or allow-all IP rules.'
        Category    = 'Storage'
        Version     = '1.0.0'
        Mode        = 'All'
    }

    Parameter Effect -AllowedValues Audit, Deny, Disabled -Default Deny

    Resource 'Microsoft.Storage/storageAccounts' {

        When {
            Field kind | Must -BeIn 'StorageV2', 'BlockBlobStorage'
        }

        Require 'Public network access is disabled' {
            Field publicNetworkAccess | Must -Be 'Disabled'
        }

        Require 'No allow-all IP rules' {
            Each networkAcls.ipRules[*] {
                Field value | Must -Not -Be '0.0.0.0/0'
            }
        }
    }

    Effect (Param Effect)
}

Bylaw produces:

{
  "$schema": "https://raw.githubusercontent.com/Azure/enterprise-azure-policy-as-code/main/Schemas/policy-definition-schema.json",
  "name": "storage-deny-public-network-access",
  "properties": {
    "displayName": "Storage accounts should disable public network access",
    "policyType": "Custom",
    "mode": "All",
    "description": "Denies storage accounts that allow public network access or allow-all IP rules.",
    "metadata": {
      "version": "1.0.0",
      "category": "Storage"
    },
    "parameters": {
      "effect": {
        "type": "String",
        "metadata": {
          "displayName": "Effect",
          "description": "Enable or disable the execution of the policy"
        },
        "allowedValues": [
          "Audit",
          "Deny",
          "Disabled"
        ],
        "defaultValue": "Deny"
      }
    },
    "policyRule": {
      "if": {
        "allOf": [
          {
            "field": "type",
            "equals": "Microsoft.Storage/storageAccounts"
          },
          {
            "field": "kind",
            "in": [
              "StorageV2",
              "BlockBlobStorage"
            ]
          },
          {
            "anyOf": [
              {
                "field": "Microsoft.Storage/storageAccounts/publicNetworkAccess",
                "notEquals": "Disabled"
              },
              {
                "count": {
                  "field": "Microsoft.Storage/storageAccounts/networkAcls.ipRules[*]",
                  "where": {
                    "field": "Microsoft.Storage/storageAccounts/networkAcls.ipRules[*].value",
                    "equals": "0.0.0.0/0"
                  }
                },
                "greater": 0
              }
            ]
          }
        ]
      },
      "then": {
        "effect": "[parameters('effect')]"
      }
    }
  }
}

What the compiler did:

  • Must -Be 'Disabled' became its violation, notEquals. The two Require blocks must both hold, so a resource violates the policy if either fails: an anyOf of the two violations.
  • Each became a count of the elements that break the condition, and Must -Not -Be became equals.
  • Short field names became full aliases. kind and type are standard fields, so they stay as written.
  • When narrows the resources the policy applies to. It is not inverted.

examples/ has eighteen more policies and two initiatives, each with the JSON it compiles to: tag inheritance with Modify, every other effect, counts, initiatives built from those policies, and one that uses a PowerShell loop to generate its requirements.

Writing policies

A file can hold any number of Policy blocks. Bylaw finds every *.bylaw.ps1 file under the path you give it.

Keyword Purpose
Policy 'name' { } One policy definition. The name becomes the definition's name and its file name, so renaming it creates a new definition. Any name Azure accepts that is also a safe file name works, such as Deny-Storage-minTLS (ADR-0010); lowercase with hyphens is the suggested style for new policies. Names are unique across a build, ignoring case.
Properties @{ } DisplayName, Description, Category, Version, PolicyVersion, Mode, Preview, Deprecated, Metadata. EPAC output needs Category and Version. Version is metadata.version; PolicyVersion is the top-level version of Azure's custom policy versioning, which is in preview, and only plain JSON output writes it. Mode is All (the default) or Indexed. Unknown keys fail the build.
Parameter Name A policy parameter, with -Type, -AllowedValues, -Default, -DisplayName, -Description, -JsonName, -Metadata. AllowedLocations is emitted as allowedLocations. For a long declaration, give the options as a hashtable after the name, one per line: Parameter AllowedLocations @{ Type = 'Array'; Default = 'uksouth' }. See Parameters.
Resource 'type' { } The resource type the rule applies to, and the type short field names resolve against. Resource * applies to every type; use standard fields such as location, or full aliases. The block is optional: Resource 'type' alone selects every resource of the type.
When { } Conditions that decide whether the policy applies. Written and emitted as is.
Require 'description' { } A requirement a compliant resource meets. All Require blocks must hold, and so must all Must statements inside one.
Each path[*] { } A condition on every element of an array. Can be nested.
AnyOf { } Alternatives: holds when any statement inside it holds. Works in When, Require and Each.
AllOf { } Inside AnyOf, one alternative made of several statements that must all hold.
Field name A field: a short name, a standard field (name, type, location, tags, ...), or a full alias. -AllowUnknownAlias accepts an alias missing from the snapshot.
Element The element itself, inside Each over an array of plain values, or in a field count's -Where.
Tag name A tag field, tags['name']. Tag (Param TagName) takes the name from a parameter.
ResourceGroupTag name The resource group's value for a tag, for example Tag CostCenter | Must -Be (ResourceGroupTag CostCenter).
Count path[*], Count -Value list The number of array elements, or list members, that match -Where, piped to Must. See Counts.
Current [name] Inside Count -Where: the element or member being counted.
Condition @{ } A raw policy condition, for what the language can't express. In Require and Each it needs -Violation or -Compliant. See Raw conditions.
Must An assertion about the Field, Tag, Element or Count piped into it. See the operators below.
Effect Audit, Deny or Disabled, or (Param Effect). The other effects have their own keywords, in place of Effect.
Modify -Role ... { } The modify effect: what to change on a non-compliant resource. See Modify.
... | AddOrReplace v Inside Modify: sets the piped field or tag to v.
... | Add v Inside Modify: sets the piped field or tag to v only if it has no value. Inside Append: adds v to the request.
... | Remove Inside Modify: removes the piped tag. Only tags can be removed.
Append { } The append effect: values to add to a create or update request. See Append, DenyAction and Manual.
DenyAction Delete The denyAction effect: blocks deleting matching resources.
Manual The manual effect: owners attest compliance.
AuditIfNotExists ... { } The auditIfNotExists effect: audits a resource with no related resource in the compliant state. See Related resources.
DeployIfNotExists ... -Role ... { } The deployIfNotExists effect: the same, and deploys a template to fix it.
Deployment Inside DeployIfNotExists: the template to deploy, and the values passed to it.
KeyVaultSecret A Key Vault secret passed to a template parameter in Deployment -Parameters, read when the template is deployed.
Initiative 'name' { } An initiative (policy set definition), alongside Policy. It takes Properties, Parameter, PolicyDefinition and DefinitionGroup. See Initiatives.
PolicyDefinition 'name', PolicyDefinition -Id ... Inside Initiative: a policy it includes, from this build by name, or any definition by ID.
DefinitionGroup 'name' Inside Initiative: a policy definition group, such as a regulatory compliance control.
Param Name A parameter's value, for example Must -BeIn (Param AllowedLocations). Param Name -Length is the number of members of an Array parameter (or characters of a String), [length(parameters('name'))]. Write Param Name or (Param Name), not Param(Name): at the start of a block, PowerShell reads param( as a parameter declaration.
Arm '[...]' A raw ARM template expression, for anything else.

Each over objects uses the element's fields. Over plain values, it uses Element:

Require 'No access policy grants purge' {
    Each accessPolicies[*] {
        Each permissions.keys[*] {
            Element | Must -Not -Be 'purge'
        }
    }
}

Statements combine with AND. For alternatives, use AnyOf. Here a rule is acceptable if it is outbound, or denies traffic, or doesn't come from the internet:

Require 'No rule allows inbound traffic from the internet' {
    Each securityRules[*] {
        AnyOf {
            Field direction | Must -Not -Be 'Inbound'
            Field access | Must -Not -Be 'Allow'
            Field sourceAddressPrefix | Must -Not -BeIn '*', 'Internet'
        }
    }
}

Keywords other than Policy and Initiative exist only inside those blocks, so they don't clash with commands of the same name, and calling them elsewhere gives a clear error. Must was chosen over Should so Bylaw and Pester can be used in the same session.

Parameters

A parameter with one or two options fits on one line. When it has more, give them as a hashtable after the name, one option per line. Bylaw files don't use backtick line continuation.

Parameter Effect -AllowedValues Audit, Deny, Disabled -Default Deny

Parameter AllowedValues @{
    Type        = 'Array'
    Default     = 'Public', 'Private', 'Confidential', 'Restricted'
    DisplayName = 'Allowed values'
    Description = 'Allowed classifications'
}

The keys are the option names: Type, AllowedValues, Default, DisplayName, Description, JsonName and Metadata. An unknown key fails the build, and so does mixing the hashtable with -Type and the other options. The name can also go inside the hashtable as Name, as in Parameter @{ Name = 'AllowedValues'; ... }. When Type is left out, it is inferred from Default or AllowedValues.

Operators

Each Must takes one operator. The violation column is what Bylaw emits: the condition that finds a resource breaking the requirement.

Must Compliant when the value... Azure operator Violation emitted
-Be v equals v equals notEquals
-BeIn a is one of a in notIn
-BeLike p matches a wildcard pattern, with at most one * like notLike
-Match p matches an Azure match pattern, ignoring case matchInsensitively notMatchInsensitively
-MatchCase p matches an Azure match pattern, case-sensitively match notMatch
-ContainText s contains the text s contains notContains
-ContainKey k has the key k (for example a tag) containsKey notContainsKey
-Exist is present exists: true exists: false
-BeGreaterThan n is greater than n greater lessOrEquals
-BeGreaterOrEqual n is greater than or equal to n greaterOrEquals less
-BeLessThan n is less than n less greaterOrEquals
-BeLessOrEqual n is less than or equal to n lessOrEquals greater
Switch Effect
-Not Reverses the operator: Must -Not -Be 'X' emits equals 'X' as the violation.
-IfPresent A missing field is compliant. Not valid inside Each, with -Exist, or in When.
-Strict A missing element field is a violation. Only valid inside Each.

Azure match patterns are not regular expressions. # matches a digit, ? a letter, . any character, and every other character, including *, matches only itself. Bylaw warns about patterns that look like a regex.

-Match is case-insensitive, like PowerShell's. -ContainText tests text, unlike Pester's -Contain, which tests membership of a collection. Values can be literals, (Param Name), (ResourceGroupTag name) or (Arm '[...]').

Must can also test an expression instead of a field: pipe ResourceGroupTag, Param or Arm into it. For example, When { ResourceGroupTag CostCenter | Must -Not -Be '' } applies a policy only to resource groups that have the tag. An expression is never missing, so -IfPresent, -Strict and -Exist don't apply to it, and it can't be used inside Each yet (a Count can).

Missing fields

A resource often doesn't set the property a requirement checks. Bylaw fails closed: inside a Require, a missing field breaks the requirement unless you say otherwise.

Where A missing field is To change it
Require a violation Must -IfPresent makes it compliant
A field inside Each compliant Must -Strict makes it a violation
When not treated specially; operators are emitted as written
The array of an Each compliant: a missing or empty array has no elements to break the condition add Field path | Must -Exist to require it, or Count path[*] | Must -BeGreaterThan 0
An existence condition (AuditIfNotExists, DeployIfNotExists) a related resource without the field doesn't count Must -IfPresent, as in Require
Count -Where not treated specially; emitted as written, like When

Some operators already give the right answer on a missing field, and others don't. notEquals finds a missing value, so Must -Be 'Disabled' needs nothing extra. equals doesn't, so for Must -Not -Be 'X' Bylaw adds an exists check:

"anyOf": [
  {
    "field": "Microsoft.Storage/storageAccounts/allowSharedKeyAccess",
    "exists": false
  },
  {
    "field": "Microsoft.Storage/storageAccounts/allowSharedKeyAccess",
    "equals": true
  }
]

Bylaw adds these checks only where they change the result. An empty string counts as present. To require a non-empty value, add Must -Not -Be ''.

The behaviour of each operator on a missing field isn't documented by Microsoft. Bylaw's rules come from measurements in a real subscription, where missing tags and missing properties behaved the same. ADR-0004 has the full table and the measurement script.

Counts

Each says that every element of an array meets a condition. Count says how many do, and is tested with Must like any number: -Be, -BeIn and the four comparisons.

Require 'At least one IP rule' {
    Count networkAcls.ipRules[*] | Must -BeGreaterThan 0
}

Require 'Few rules allow inbound traffic' {
    Count securityRules[*] -Where {
        Field direction | Must -Be 'Inbound'
        Field access | Must -Be 'Allow'
    } | Must -BeLessOrEqual 5
}
  • -Where selects what to count. It is emitted as written, like When: it isn't inverted and gets no missing-field checks. Field names are relative to the element, Element is the element itself, and AnyOf, AllOf and nested counts work inside. Without -Where, every element is counted.

  • A value count counts the members of a list: a literal array, Param or Arm. Current is the member being counted, and -Name gives it a name, which nested counts need:

    Require 'The name matches an allowed pattern' {
        Count -Value (Param NamePatterns) -Name pattern -Where {
            Field name | Must -BeLike (Current pattern)
        } | Must -BeGreaterThan 0
    }

    Current can't name a tag: Tag (Current tagName) is a compile error (BYL1059), because Azure rejects a field named with current().

  • To compare with the length of a list, use Param Name -Length. Here every pattern must match, not just one:

    Require 'The name matches every pattern' {
        Count -Value (Param NamePatterns) -Name pattern -Where {
            Field name | Must -BeLike (Current pattern)
        } | Must -Be (Param NamePatterns -Length)
    }
  • In Require, the comparison is inverted like any other: -BeGreaterThan 0 emits lessOrEquals 0. A count is never missing, so it gets no guard.

  • Each path[*] { P } is the same as Count path[*] -Where { <violation of P> } | Must -Be 0, and stays the simple way to say "every element".

  • Azure allows at most 5 field counts per array, 10 value counts per rule, and 100 iterations over literal lists. The build checks all three.

Raw conditions

For a condition the language can't express, Condition takes one Azure Policy condition as it would appear in policy JSON, as a hashtable or as JSON text:

When {
    Condition @{ value = '[requestContext().apiVersion]'; greaterOrEquals = '2020-01-01' }
}

Require 'No rule allows SSH from anywhere' {
    Condition -Violation @{
        count   = @{
            field = 'securityRules[*]'
            where = @{ allOf = @(
                    @{ field = 'securityRules[*].sourceAddressPrefix'; equals = '*' }
                    @{ field = 'securityRules[*].destinationPortRange'; equals = '22' }
                ) }
        }
        greater = 0
    }
}
  • In When and Count -Where, it is emitted as written, like everything else there.
  • In Require and Each, statements describe the compliant state and are inverted, which Bylaw can't do correctly for raw JSON. So say which form you wrote: -Violation is the condition that finds a non-compliant resource, emitted as written; -Compliant is the compliant state, emitted as not(...).
  • Field names resolve like Field: a short name against the Resource type, or relative to the element inside Each. A full alias, a path with [*] (as policy JSON writes it inside a count's where), or an ARM expression is used as written. Unknown aliases are still an error.
  • Values can be Param and Arm, so parameters are still declared and checked. Use a [ordered] hashtable, or JSON text, where the order of a literal object's keys matters.
  • In AuditIfNotExists and DeployIfNotExists, Require describes the related resource's compliant state, which Azure's existence condition is, so the forms swap: -Compliant is emitted as written, and -Violation as not(...).
  • Nothing else is checked. Bylaw adds no missing-field handling to a raw condition, and can't tell whether it means what its Require says. Prefer the language wherever it can express the condition.

Modify

Modify changes resources instead of denying them: when they're created or updated, and through remediation tasks for existing ones. It takes the place of Effect. The Require blocks say what a compliant resource looks like, and the operations say how to make one compliant.

This keeps a tag in step with the resource group, as the built-in "Inherit a tag from the resource group" policy does:

Policy 'tags-inherit-from-resource-group' {

    Properties @{
        DisplayName = 'Inherit a tag from the resource group'
        Category    = 'Tags'
        Version     = '1.0.0'
        Mode        = 'Indexed'
    }

    Parameter TagName -Type String

    Resource * {
        When {
            ResourceGroupTag (Param TagName) | Must -Not -Be ''
        }
        Require 'The tag matches the resource group' {
            Tag (Param TagName) | Must -Be (ResourceGroupTag (Param TagName))
        }
    }

    Modify -Role 'Tag Contributor' {
        Tag (Param TagName) | AddOrReplace (ResourceGroupTag (Param TagName))
    }
}

Its rule and details block:

"policyRule": {
  "if": {
    "allOf": [
      {
        "value": "[resourceGroup().tags[parameters('tagName')]]",
        "notEquals": ""
      },
      {
        "field": "[concat('tags[', parameters('tagName'), ']')]",
        "notEquals": "[resourceGroup().tags[parameters('tagName')]]"
      }
    ]
  },
  "then": {
    "effect": "[parameters('effect')]",
    "details": {
      "roleDefinitionIds": [
        "/providers/Microsoft.Authorization/roleDefinitions/4a9ae827-6dc8-4573-8ac7-8239d42aa03f"
      ],
      "operations": [
        {
          "operation": "addOrReplace",
          "field": "[concat('tags[', parameters('tagName'), ']')]",
          "value": "[resourceGroup().tags[parameters('tagName')]]"
        }
      ]
    }
  }
}

To add the tag only where it is missing, and keep any value a resource already has, require Tag (Param TagName) | Must -Exist and use Add instead of AddOrReplace. Both forms are in examples/tags/.

  • -Role names the roles the assignment's managed identity needs, as built-in role names, GUIDs or full role definition IDs. See Roles.
  • -ConflictEffect is Audit, Deny (Azure's default) or Disabled. When Modify changes an alias rather than a tag, Azure recommends Audit, so that requests using an API version where the property can't be modified aren't denied. Bylaw warns otherwise.
  • -Effect (Param Effect) makes the effect a parameter you declare, which can allow Modify, Audit and Disabled. Audit reports non-compliant resources without changing them. Without -Effect, EPAC output gets a generated effect parameter allowing Modify and Disabled, as built-in Modify policies do.
  • -Condition (Arm '[...]') on an operation applies it only when the expression is true, for example [greaterOrEquals(requestContext().apiVersion, '2019-04-01')]. field(), resourceGroup() and subscription() aren't supported there.
  • What can be changed: tags, identity.type on virtual machines and scale sets, and aliases marked Modifiable in the alias snapshot. Only tags can be removed. Anything else fails the build.
  • Array elements can be changed, as Learn documents in preview, with a warning: Field 'securityRules[*]' | Add @{ ... } adds a member, AddOrReplace on x[*] replaces every member with one, and Field 'x[*].property' | AddOrReplace ... sets the property in every member. One array level only.
  • Remediation that works: the build warns when an operation changes a field that no Require checks, because a remediated resource would still be non-compliant. It also warns about tag operations in a policy whose Mode isn't Indexed.

Note

An assignment of a Modify policy needs a managed identity with the roles in -Role, even if the assignment sets the effect to Audit. Bylaw only writes the definition: create the identity and its role assignments when you assign it.

Append, DenyAction and Manual

Each of these takes the place of Effect, and takes -Effect (Param Effect) to make the effect a parameter that may also allow Disabled.

# Adds values to a create or update request. With a [*] field, it adds an array element.
Append {
    Field supportsHttpsTrafficOnly | Add $true
    Field 'networkAcls.ipRules[*]' | Add ([ordered]@{ value = '40.40.40.0/24'; action = 'Allow' })
}

# Blocks deleting the resources that match Resource and When. -CascadeBehavior Deny also blocks
# deleting their resource group, and needs Mode = 'Indexed'.
DenyAction Delete -CascadeBehavior Deny

# Resource owners attest compliance. -DefaultState is Unknown (the default), Compliant or NonCompliant.
Manual -DefaultState NonCompliant
  • Append warns when it adds a tag (Azure recommends Modify for tags), and when it adds a field that no Require checks. Its details are an array, as Azure requires, which the EPAC schema doesn't allow, so EPAC output warns (BYL4010). EPAC deploys it.
  • DenyAction and Manual usually have only When conditions: they apply to every resource that matches. A Resource type DenyAction never applies to, such as locks, is a warning.

Related resources: AuditIfNotExists and DeployIfNotExists

These effects check a related resource: a virtual machine's extensions, or a key vault's diagnostic settings. The first argument, -Type, is the related resource's type (the name can be left out, as with Resource), and the Require blocks inside describe it: what a related resource must look like for the evaluated resource to be compliant. Their field names resolve against -Type.

Resource 'Microsoft.Compute/virtualMachines' {
    When {
        Field storageProfile.osDisk.osType | Must -Be 'Windows'
    }
}

AuditIfNotExists 'Microsoft.Compute/virtualMachines/extensions' {
    Require 'The antimalware extension is installed' {
        Field publisher | Must -Be 'Microsoft.Azure.Security'
        Field 'Microsoft.Compute/virtualMachines/extensions/type' | Must -Be 'IaaSAntimalware'
    }
}
  • The existence condition is emitted as written, because Azure expects the compliant form there, not the violation. You don't need to think about it: Require describes the compliant state everywhere.
  • Missing fields still fail. A related resource without the field doesn't count, so Must -Not -Be 'x' emits allOf[exists: true, notEquals 'x']. -IfPresent lets a missing field pass.
  • Reserved names such as name and type are the related resource's own. A property with the same name as a reserved field, like an extension's type, needs its full alias, as above.
  • -Name, -ResourceGroupName, -ExistenceScope and -EvaluationDelay narrow which related resources are checked, and when. -EvaluationDelay takes a delay such as PT30M, or a parameter, (Param EvaluationDelay), whose values are checked. When -Type is the Resource type, -Name must be (Arm "[field('name')]").
  • Resource still says which resources are evaluated. -Type is the related resource, not the one the policy applies to. When every resource of the type is evaluated, leave out the block: Resource 'Microsoft.KeyVault/vaults'.
  • Require blocks in Resource still work, and are inverted as usual: a resource that meets them is compliant whatever its related resources are.

DeployIfNotExists also deploys an ARM template to fix a non-compliant resource. It needs -Role, like Modify, and a Deployment:

Resource 'Microsoft.KeyVault/vaults'

DeployIfNotExists 'Microsoft.Insights/diagnosticSettings' -Role 'Contributor' -Effect (Param Effect) {
    Require 'A diagnostic setting sends logs to the workspace' {
        Field workspaceId | Must -Be (Param WorkspaceId)
    }

    Deployment -TemplateFile ./templates/diagnostic-settings.json -Parameters ([ordered]@{
            vaultName   = Arm "[field('name')]"
            workspaceId = Param WorkspaceId
        })
}
  • -TemplateFile is an ARM template JSON file, relative to the .bylaw.ps1 file. -Template takes the template as a hashtable instead. Bicep isn't supported yet: build it to JSON first.
  • -Parameters is checked against the template: every name must be a template parameter, and every template parameter without a default must be given. A misspelled parameter fails the build, not the remediation task.
  • -Scope Subscription deploys at subscription scope, and needs -Location. The deployment mode is always incremental.
  • Secrets come from Key Vault with KeyVaultSecret, so they're never in the policy: domainPassword = (KeyVaultSecret -VaultId (Param KeyVaultResourceId) -SecretName 'domain-password'). Resource Manager reads the secret when it deploys, so the vault must allow template deployment (ADR-0043). -SecretVersion picks a version; without it, the current one is used.
  • The keyword sets the details, -Effect sets the effect. Azure can run a deployIfNotExists rule as AuditIfNotExists, which reports without deploying, or as Disabled. So the effect parameter may allow DeployIfNotExists, AuditIfNotExists and Disabled, and whoever assigns the policy chooses. You only need -Effect (Param Effect) to allow AuditIfNotExists: without it, EPAC output gets a generated parameter allowing DeployIfNotExists and Disabled. AuditIfNotExists works the same way, allowing AuditIfNotExists and Disabled.

Initiatives

An initiative groups policies so they're assigned together, and passes its own parameters to theirs. It sits beside policies, in the same or other files, and includes them by name. Built-in policies are included by ID.

Initiative 'tagging-baseline' {

    Properties @{
        DisplayName = 'Tagging baseline'
        Category    = 'Tags'
        Version     = '1.0.0'
    }

    Parameter RequiredTag @{ Default = 'CostCenter' }

    PolicyDefinition 'general-require-tag' -Parameters @{
        tagName = Param RequiredTag
    }

    # The same policy twice, with a reference ID for each.
    PolicyDefinition 'tags-inherit-from-resource-group' -ReferenceId 'inherit-cost-center' -Parameters @{ tagName = 'CostCenter' }
    PolicyDefinition 'tags-inherit-from-resource-group' -ReferenceId 'inherit-owner' -Parameters @{ tagName = 'Owner' }

    # A built-in policy, by its GUID.
    PolicyDefinition -Id 96670d01-0a4d-4649-9c89-2d3abc0a5025 -ReferenceId 'require-environment' -Parameters @{
        tagName = 'Environment'
    }
}
  • PolicyDefinition takes -ReferenceId (the member's policyDefinitionReferenceId, defaulting to the policy name and required with -Id), -Parameters, -Version (a definitionVersion such as 1.*.*) and -Group. Values passed are literals, Param (an initiative parameter), Arm or ResourceGroupTag.

  • DefinitionGroup 'name' declares a group, with -DisplayName, -Category, -Description and -AdditionalMetadataId. Members join it with -Group. EPAC's schema only allows a group's name and -AdditionalMetadataId, so the other options are an EPAC error.

  • Checked when the build runs: once every file has compiled, each member from the build is checked against the policy it names. The policy must exist, every value must go to one of its parameters, every parameter without a default must be given one, and values must fit the parameter's type and allowed values. An initiative parameter passed to a policy can't allow values the policy doesn't. The checks use the parameters each format emits, so in EPAC output you can pass effect to a policy with a literal effect, whose generated parameter has a default.

  • -Id takes a definition ID, or a built-in policy's GUID on its own, which is short for /providers/Microsoft.Authorization/policyDefinitions/<guid>. When a member's arguments make a long line, splat them from a hashtable, without backticks:

    $requireEnvironment = @{
        Id          = '96670d01-0a4d-4649-9c89-2d3abc0a5025'
        ReferenceId = 'require-environment'
        Version     = '1.*.*'
        Parameters  = @{ tagName = 'Environment' }
    }
    PolicyDefinition @requireEnvironment
  • Not checked: members by -Id. Bylaw has no copy of the built-in definitions, so only the shape of the ID is checked.

  • -Version on a member from the build must match the policy's PolicyVersion if it has one, which is the top-level version Azure matches it against. Otherwise it must match the policy's Version, and the build warns that the pin may not select the version you expect, since the policy has no top-level version.

  • Output: EPAC initiatives reference members from the build by policyDefinitionName, as EPAC requires, and anything else by policyDefinitionId. Plain JSON needs a full ID for every member, so set the scope the build's policies are deployed at with -DefinitionScope or definitionScope in bylaw.json. Initiatives are written to -InitiativeOutputPath, which defaults to -OutputPath. For EPAC, use its two folders:

    Build-Bylaw ./policies -OutputPath ./Definitions/policyDefinitions -InitiativeOutputPath ./Definitions/policySetDefinitions

Converting existing policies

ConvertTo-Bylaw turns existing policy definitions and initiatives into .bylaw.ps1 files. It reads EPAC definitions, plain { name, properties } JSON, or a properties object on its own, from .json and .jsonc files, folders of them, or the pipeline:

ConvertTo-Bylaw -Path ./Definitions -OutputPath ./policies

Every file is proven before it is written: it is compiled in the input's format (EPAC when the input has a $schema, plain JSON otherwise) and compared with the input by meaning, not text (ADR-0041). A file that can't be proven equivalent isn't written. For example, storage-deny-public-network-access.json converts to:

# Converted from storage-deny-public-network-access.json by ConvertTo-Bylaw.
Policy 'storage-deny-public-network-access' {

    Properties @{
        DisplayName = 'Storage accounts should disable public network access'
        Description = 'Denies storage accounts that allow public network access or allow-all IP rules.'
        Version     = '1.0.0'
        Category    = 'Storage'
        Mode        = 'All'
    }

    Resource 'Microsoft.Storage/storageAccounts' {

        When {
            Field kind | Must -BeIn @('StorageV2', 'BlockBlobStorage')
        }

        Require 'publicNetworkAccess is Disabled' {
            Field publicNetworkAccess | Must -Be 'Disabled'
        }

        Require 'Requirement 2' {
            Each 'networkAcls.ipRules[*]' {
                Field value | Must -Not -Be '0.0.0.0/0'
            }
        }
    }

    Effect Deny
}
  • The violation becomes Require blocks. The conditions before it are When, and each alternative of the violation is a Require, inverted back into the compliant state, with the missing-field handling recognised so -IfPresent and -Strict come back where they were. JSON has no descriptions, so a Require is named after its statement, or Requirement <n>: rename them to say what they require.
  • Effects come back as their keywords, with their details: Modify, Append, DenyAction, Manual, AuditIfNotExists and DeployIfNotExists, with roles by name where the role map has them. EPAC's generated effect parameter becomes the literal effect, as above, since the EPAC build generates it again. A DeployIfNotExists template is written beside the file, as templates/<name>.json.
  • Initiatives become Initiative files. EPAC members referenced by name are written by name, built-in policies by GUID, and any other ID in full.
  • What the language can't express is written with Condition (Raw conditions), and the result's status is EscapeHatch rather than Converted, with a warning (BYL6005). Check those statements, and replace them as the language grows.
  • What it can't convert is reported as an error, with a BYL6xxx code and the reason, and nothing is written for it; the other definitions still convert. Use -ErrorAction Stop to stop at the first.
  • Names: a definition without a name, such as a properties file, is named after its file, with a warning (BYL6008).
  • Build warnings: when a converted file compiles with a warning, such as a location check under Mode = 'All', conversion reports it as BYL6009, with the warning's own code and line, so Build-Bylaw holds no surprises.
  • Aliases: fields are shortened against the alias snapshot where they resolve back. A type or alias the snapshot lacks is written in full, and the file then builds only with -AllowUnknownAlias (BYL6007): run Update-BylawAliasCache first for short names everywhere.
  • Existing files are left as they are, with a warning (BYL6006), unless -Force is given. -WhatIf writes nothing, -Verbose lists the files written, and without -OutputPath, or with -PassThru, each result is returned: Name, Source, Status, Script, Templates, OutputFile and Diagnostics.

Coverage

The test suite converts a pinned copy of the Azure Landing Zones Library, at 3ac1ed6 (2026-11-21), and fails if any definition converts worse than its recorded baseline (ADR-0042). Every conversion is proven:

  • 149 of 149 policy definitions converted (1 with Condition)
  • 44 of 44 initiatives converted

Condition holds what the language can't express yet. Every conversion is committed in tests/Alz/converted, so you can read what real ALZ policies look like in Bylaw. ./build/alz/Get-AlzCoverage.ps1 writes the full report to out/alz-coverage.md.

Building

Build-Bylaw [[-Path] <string[]>] [[-OutputPath] <string>] [-InitiativeOutputPath <string>]
            [-Format <Epac|PlainJson>] [-DefinitionScope <string>] [-PassThru]
            [-Settings <string>] [-AliasCachePath <string>] [-RoleCachePath <string>]
            [-AllowUnknownAlias] [-ThrottleLimit <int>] [-WhatIf]
  • Formats: Epac, the default, writes EPAC policy definition files with a $schema, and generates what EPAC requires: an effect parameter for a literal effect, and parameter display names. EPAC also needs Category and Version in Properties. PlainJson writes { "name", "properties" }, the layout Azure publishes built-in definitions in, for New-AzPolicyDefinition, the Azure CLI, Bicep or Terraform. It emits the policy as written: a literal effect stays literal, nothing is generated, and Category and Version are optional. The policy rule is the same in both.
  • Output layout: one file per policy or initiative, named after it, in a folder structure that mirrors the sources. Initiatives go to -InitiativeOutputPath when it is set. Files whose content hasn't changed aren't rewritten.
  • All or nothing: every file is compiled and every error reported. If anything fails, nothing is written.
  • No deletion: Bylaw never deletes output. It warns about JSON files in the output folders that the build didn't produce, so you can remove policies and initiatives you've deleted. Deployment template files are inputs, so they're never reported.
  • Isolation: each file is compiled in a fresh runspace, so variables and functions can't leak between files. Several files compile at once; -ThrottleLimit sets how many, and -ThrottleLimit 1 compiles one at a time. Files that change environment variables or other process-wide state should be built with -ThrottleLimit 1.
  • Unique names: policy and initiative names must be unique across a build, ignoring case.
  • -PassThru returns a result for each policy and initiative, with its Kind, Name, source, output file, JSON and warnings.

Aliases

Bylaw checks field names against an alias snapshot, offline. The bundled snapshot only covers the resource types used by the tests and examples (storage accounts, key vaults, virtual machines and their extensions, network security groups, and diagnostic settings). For anything else, refresh the snapshot from Azure. This needs Az.Resources and a signed-in account, and only reads alias metadata:

Connect-AzAccount
Update-BylawAliasCache

That writes ~/.bylaw/aliases.json, which Bylaw then uses by default. To limit it to some providers, use -Namespace 'Microsoft.Storage', 'Microsoft.KeyVault'. To keep a snapshot with your policies, write it with -OutputPath and point bylaw.json at it.

The snapshot used is the first of: -AliasCachePath, aliasCache in bylaw.json, ~/.bylaw/aliases.json, the bundled snapshot.

Roles

Modify -Role and DeployIfNotExists -Role take built-in role names, such as 'Security Admin', which Bylaw turns into role definition IDs using a role map, offline. The bundled map has every built-in role as of its generation date. For roles Azure has added since, refresh it from Azure, which only reads role definitions:

Update-BylawRoleCache

That writes ~/.bylaw/roles.json. Built-in role IDs are the same in every tenant, so the map can be shared. Custom roles aren't in it; give them by GUID or full role definition ID.

The map used is the first of: -RoleCachePath, roleCache in bylaw.json, ~/.bylaw/roles.json, the bundled map.

bylaw.json

An optional settings file. Bylaw looks for it from -Path upwards, stopping at the repository root, or uses -Settings.

{
  "languageVersion": "1.0",
  "aliasCache": "./aliases.json",
  "roleCache": "./roles.json",
  "initiativeOutputPath": "./Definitions/policySetDefinitions",
  "definitionScope": "/providers/Microsoft.Management/managementGroups/contoso"
}

languageVersion pins the language's behaviour, so upgrading Bylaw never changes the output of existing policies by surprise. It defaults to 1.0. Paths are relative to bylaw.json. definitionScope is a management group or subscription ID. Command-line parameters take precedence over these settings, and unknown keys fail the build.

Testing policies

Build-Bylaw already rejects many mistakes: misspelled aliases, invalid operators, undeclared parameters and Azure's limits. A build that passes means the policy is valid, not that it does what you meant. Two kinds of test help with that.

Snapshot tests: did the output change?

Commit the compiled JSON beside your sources, or in your EPAC Definitions folder, and have a Pester test fail when a build produces anything different. The output is deterministic, so any difference is a real change, and reviewing the JSON diff in a pull request shows what a change to a policy does to its rule.

# tests/Policies.Tests.ps1
BeforeDiscovery {
    Import-Module Bylaw
    # -PassThru without -OutputPath compiles in memory and writes nothing.
    $script:Results = Build-Bylaw -Path "$PSScriptRoot/../policies" -PassThru -WarningAction SilentlyContinue |
        ForEach-Object { @{ Name = $_.Name; Json = $_.Json; Warnings = @($_.Warnings) } }
}

Describe '<Name>' -ForEach $Results {
    It 'matches the approved definition' {
        $approved = Get-ChildItem -Path "$PSScriptRoot/../Definitions" -Recurse -Filter "$Name.json" | Select-Object -First 1
        $approved | Should -Not -BeNullOrEmpty -Because "$Name needs an approved definition"
        $Json | Should -BeExactly ([System.IO.File]::ReadAllText($approved.FullName))
    }

    It 'compiles without warnings' {
        # Allow warnings you have accepted, e.g. BYL4010 for Append in EPAC output.
        @($Warnings | Where-Object { $_ -notmatch ' BYL4010: ' }) | Should -BeNullOrEmpty
    }
}

To approve a change, rebuild into the committed folder and review the diff:

Build-Bylaw ./policies -OutputPath ./Definitions/policyDefinitions
git diff ./Definitions

Bylaw writes LF line endings. Add *.json text eol=lf to .gitattributes, so a Windows checkout doesn't convert the approved files to CRLF and fail the comparison.

A snapshot test catches regressions, but not a rule that is wrong from the start: a policy that compiles to exactly what you wrote passes, even when what you wrote isn't what you meant.

Sandbox tests: does Azure do what you expect?

The only full proof is Azure itself. In a test subscription:

  1. Deploy the definitions, and assign them to a resource group with the effect set to Audit.
  2. Create resources that should be compliant and resources that shouldn't, for each requirement and each edge case: a property that is missing, an array that is empty, a value in a different case.
  3. Run Start-AzPolicyComplianceScan -ResourceGroupName <group>, then compare Get-AzPolicyState with what you expected.
  4. For Deny, assign with Deny instead, and check that deploying a non-compliant resource fails with RequestDisallowedByPolicy.

Remove the resources and the assignment afterwards. The scripts in build/, such as build/verify-initiatives, show this pattern: deploy, record what Azure did, and remove everything again.

Sandbox tests are slow and need Azure access, so they suit the rules that matter most and the patterns you're unsure of. Testing policies against example resources without Azure is being considered for a later release (ADR-0038, proposed).

Development

./build/build.ps1 -Task Bootstrap                 # install the pinned Pester and PSScriptAnalyzer versions
./build/build.ps1                                 # analyze and test
./build/build.ps1 -Task Package                   # build out/Bylaw
./build/build.ps1 -Task UpdateGolden              # regenerate the expected JSON after an intended output change
./build/build.ps1 -Task Test -Coverage            # test, writing code coverage to out/coverage.xml
./build/build.ps1 -Task Test -ExcludeTag Alz      # everything but the ALZ test, about 3 minutes quicker; -Tag Alz runs only it
./build/build.ps1 -Task Docs                      # generate the wiki pages into out/wiki
./build/alz/Get-AlzCoverage.ps1                   # convert the pinned ALZ copy, writing out/alz-coverage.md
./build/alz/Get-AlzCoverage.ps1 -UpdateBaseline   # record results in tests/Alz/baseline.json and tests/Alz/converted
./build/alz/Update-AlzSnapshot.ps1 -Commit <sha>  # pin another ALZ commit, then update the baseline
./build/alz/Sync-AlzSnapshot.ps1                  # pin ALZ's latest commit if it has moved, and update everything (weekly in CI, as a pull request)
./build/data/Sync-BylawData.ps1                   # add Azure's new roles and aliases to src/Data, after Connect-AzAccount; -AllowRemoval also applies removals (weekly in CI, as a pull request)

Releases are driven by CHANGELOG.md: add your changes under a ## !Deploy heading, optionally with a version such as ## !Deploy 0.2.0, and when it reaches main the build publishes to the PowerShell Gallery, dates the changelog and creates a GitHub release. Every build of main also updates the coverage badge (ADR-0036), and publishes the command and keyword reference to the wiki (ADR-0037).

The tests include golden files: examples/, tests/Golden/ and tests/GoldenPlainJson/ hold each policy source next to the exact JSON it must compile to. tests/Golden/GoldenRoots.psd1 lists the folders and the format each is built in.

Design decisions are recorded as ADRs in docs/adr/, and the original specification is docs/SPEC.md.

Licence

MIT

About

An open-source PowerShell module that gives Azure Policy authors a Pester-style DSL.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages