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
ifcondition that finds resources breaking it, including the negations and the handling of missing properties. - Short field names, checked at compile time.
minimumTlsVersionbecomesMicrosoft.Storage/storageAccounts/minimumTlsVersion. A misspelled alias fails the build, rather than producing a policy that silently never matches. - Simple array conditions.
Eachreplaces hand-writtencountandwhereexpressions, andCounthandles the rest. - Related resources written the same way. For
AuditIfNotExistsandDeployIfNotExists, you describe the related resource's compliant state withRequire, 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.
ModifyandAppendoperations 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.
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.
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 -PrereleaseOr 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.psd1Save 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/policyDefinitionsThis 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, JsonIf 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 PlainJsonThis 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"
}
}
}
}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 twoRequireblocks must both hold, so a resource violates the policy if either fails: ananyOfof the two violations.Eachbecame acountof the elements that break the condition, andMust -Not -Bebecameequals.- Short field names became full aliases.
kindandtypeare standard fields, so they stay as written. Whennarrows 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.
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.
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.
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).
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.
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
}-
-Whereselects what to count. It is emitted as written, likeWhen: it isn't inverted and gets no missing-field checks. Field names are relative to the element,Elementis the element itself, andAnyOf,AllOfand nested counts work inside. Without-Where, every element is counted. -
A value count counts the members of a list: a literal array,
ParamorArm.Currentis the member being counted, and-Namegives 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 }
Currentcan't name a tag:Tag (Current tagName)is a compile error (BYL1059), because Azure rejects a field named withcurrent(). -
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 0emitslessOrEquals 0. A count is never missing, so it gets no guard. -
Each path[*] { P }is the same asCount 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.
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
WhenandCount -Where, it is emitted as written, like everything else there. - In
RequireandEach, statements describe the compliant state and are inverted, which Bylaw can't do correctly for raw JSON. So say which form you wrote:-Violationis the condition that finds a non-compliant resource, emitted as written;-Compliantis the compliant state, emitted asnot(...). - Field names resolve like
Field: a short name against theResourcetype, or relative to the element insideEach. A full alias, a path with[*](as policy JSON writes it inside acount'swhere), or an ARM expression is used as written. Unknown aliases are still an error. - Values can be
ParamandArm, 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
AuditIfNotExistsandDeployIfNotExists,Requiredescribes the related resource's compliant state, which Azure's existence condition is, so the forms swap:-Compliantis emitted as written, and-Violationasnot(...). - Nothing else is checked. Bylaw adds no missing-field handling to a raw condition, and can't tell whether it means what its
Requiresays. Prefer the language wherever it can express the condition.
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/.
-Rolenames the roles the assignment's managed identity needs, as built-in role names, GUIDs or full role definition IDs. See Roles.-ConflictEffectisAudit,Deny(Azure's default) orDisabled. WhenModifychanges an alias rather than a tag, Azure recommendsAudit, 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 allowModify,AuditandDisabled.Auditreports non-compliant resources without changing them. Without-Effect, EPAC output gets a generatedeffectparameter allowingModifyandDisabled, 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()andsubscription()aren't supported there.- What can be changed: tags,
identity.typeon 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,AddOrReplaceonx[*]replaces every member with one, andField '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
Requirechecks, because a remediated resource would still be non-compliant. It also warns about tag operations in a policy whoseModeisn'tIndexed.
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.
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 NonCompliantAppendwarns when it adds a tag (Azure recommendsModifyfor tags), and when it adds a field that noRequirechecks. Itsdetailsare an array, as Azure requires, which the EPAC schema doesn't allow, so EPAC output warns (BYL4010). EPAC deploys it.DenyActionandManualusually have onlyWhenconditions: they apply to every resource that matches. AResourcetype DenyAction never applies to, such as locks, is a warning.
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:
Requiredescribes the compliant state everywhere. - Missing fields still fail. A related resource without the field doesn't count, so
Must -Not -Be 'x'emitsallOf[exists: true, notEquals 'x'].-IfPresentlets a missing field pass. - Reserved names such as
nameandtypeare the related resource's own. A property with the same name as a reserved field, like an extension'stype, needs its full alias, as above. -Name,-ResourceGroupName,-ExistenceScopeand-EvaluationDelaynarrow which related resources are checked, and when.-EvaluationDelaytakes a delay such asPT30M, or a parameter,(Param EvaluationDelay), whose values are checked. When-Typeis theResourcetype,-Namemust be(Arm "[field('name')]").Resourcestill says which resources are evaluated.-Typeis 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'.Requireblocks inResourcestill 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
})
}-TemplateFileis an ARM template JSON file, relative to the.bylaw.ps1file.-Templatetakes the template as a hashtable instead. Bicep isn't supported yet: build it to JSON first.-Parametersis 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 Subscriptiondeploys 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).-SecretVersionpicks a version; without it, the current one is used. - The keyword sets the details,
-Effectsets the effect. Azure can run adeployIfNotExistsrule asAuditIfNotExists, which reports without deploying, or asDisabled. So the effect parameter may allowDeployIfNotExists,AuditIfNotExistsandDisabled, and whoever assigns the policy chooses. You only need-Effect (Param Effect)to allowAuditIfNotExists: without it, EPAC output gets a generated parameter allowingDeployIfNotExistsandDisabled.AuditIfNotExistsworks the same way, allowingAuditIfNotExistsandDisabled.
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'
}
}-
PolicyDefinitiontakes-ReferenceId(the member'spolicyDefinitionReferenceId, defaulting to the policy name and required with-Id),-Parameters,-Version(adefinitionVersionsuch as1.*.*) and-Group. Values passed are literals,Param(an initiative parameter),ArmorResourceGroupTag. -
DefinitionGroup 'name'declares a group, with-DisplayName,-Category,-Descriptionand-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
effectto a policy with a literal effect, whose generated parameter has a default. -
-Idtakes 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. -
-Versionon a member from the build must match the policy'sPolicyVersionif it has one, which is the top-levelversionAzure matches it against. Otherwise it must match the policy'sVersion, and the build warns that the pin may not select the version you expect, since the policy has no top-levelversion. -
Output: EPAC initiatives reference members from the build by
policyDefinitionName, as EPAC requires, and anything else bypolicyDefinitionId. Plain JSON needs a full ID for every member, so set the scope the build's policies are deployed at with-DefinitionScopeordefinitionScopeinbylaw.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
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 ./policiesEvery 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
Requireblocks. The conditions before it areWhen, and each alternative of the violation is aRequire, inverted back into the compliant state, with the missing-field handling recognised so-IfPresentand-Strictcome back where they were. JSON has no descriptions, so aRequireis named after its statement, orRequirement <n>: rename them to say what they require. - Effects come back as their keywords, with their details:
Modify,Append,DenyAction,Manual,AuditIfNotExistsandDeployIfNotExists, 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. ADeployIfNotExiststemplate is written beside the file, astemplates/<name>.json. - Initiatives become
Initiativefiles. 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 isEscapeHatchrather thanConverted, 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
BYL6xxxcode and the reason, and nothing is written for it; the other definitions still convert. Use-ErrorAction Stopto stop at the first. - Names: a definition without a name, such as a
propertiesfile, 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, soBuild-Bylawholds 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): runUpdate-BylawAliasCachefirst for short names everywhere. - Existing files are left as they are, with a warning (BYL6006), unless
-Forceis given.-WhatIfwrites nothing,-Verboselists the files written, and without-OutputPath, or with-PassThru, each result is returned:Name,Source,Status,Script,Templates,OutputFileandDiagnostics.
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.
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: aneffectparameter for a literal effect, and parameter display names. EPAC also needsCategoryandVersioninProperties.PlainJsonwrites{ "name", "properties" }, the layout Azure publishes built-in definitions in, forNew-AzPolicyDefinition, the Azure CLI, Bicep or Terraform. It emits the policy as written: a literal effect stays literal, nothing is generated, andCategoryandVersionare 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
-InitiativeOutputPathwhen 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;
-ThrottleLimitsets how many, and-ThrottleLimit 1compiles 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.
-PassThrureturns a result for each policy and initiative, with itsKind,Name, source, output file, JSON and warnings.
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-BylawAliasCacheThat 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.
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-BylawRoleCacheThat 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.
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.
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.
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 ./DefinitionsBylaw 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.
The only full proof is Azure itself. In a test subscription:
- Deploy the definitions, and assign them to a resource group with the effect set to
Audit. - 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.
- Run
Start-AzPolicyComplianceScan -ResourceGroupName <group>, then compareGet-AzPolicyStatewith what you expected. - For
Deny, assign withDenyinstead, and check that deploying a non-compliant resource fails withRequestDisallowedByPolicy.
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).
./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.
