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. Every policy has one Resource, but the { } after it is optional: Resource 'type' on its own, with no requirements, selects every resource of the type, as an AuditIfNotExists or DeployIfNotExists policy often does. |
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. |
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. |
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. |
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. |
More keywords: tags, counts, other effects, initiatives and raw conditions
| Keyword | Purpose |
|---|---|
AllOf { } |
Inside AnyOf, one alternative made of several statements that must all hold. |
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 Bylaw's keywords can't express. In Require and Each it needs -Violation or -Compliant. See Raw conditions. |
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. |
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.
PowerShell in policy files¶
A .bylaw.ps1 file is a PowerShell script, so variables, loops, if, functions and data files can decide what the keywords are given and how many times they run. It all happens at build time: the output is the same plain JSON a hand-written file would give. Here one loop generates a policy per service, and another adds each one to an initiative:
$services = @(
@{ Name = 'key-vault'; DisplayName = 'Key Vault'; Type = 'Microsoft.KeyVault/vaults' }
@{ Name = 'sql-server'; DisplayName = 'Azure SQL Database'; Type = 'Microsoft.Sql/servers' }
)
foreach ($service in $services) {
Policy "public-network-access-$($service.Name)" {
Properties @{
DisplayName = "$($service.DisplayName) should disable public network access"
Category = 'Network'
Version = '1.0.0'
Mode = 'Indexed'
}
Parameter Effect -AllowedValues Audit, Deny, Disabled -Default Deny
Resource $service.Type {
Require 'Public network access is disabled' {
Field publicNetworkAccess | Must -Be 'Disabled'
}
}
Effect (Param Effect)
}
}
Initiative 'public-network-access' {
Properties @{ DisplayName = 'Services should disable public network access'; Category = 'Network'; Version = '1.0.0' }
Parameter Effect -AllowedValues Audit, Deny, Disabled -Default Audit
foreach ($service in $services) {
PolicyDefinition "public-network-access-$($service.Name)" -Parameters @{ effect = Param Effect }
}
}
Loop over arrays, not the keys of a plain hashtable, so the output is the same every build (ADR-0009). Each file runs in a fresh runspace (ADR-0014): to share a function between files, dot-source a .ps1 file, which Build-Bylaw doesn't compile on its own. examples/ has the full version of this, policies generated from a .psd1 data file, and a helper function that uses if to write each tag's requirement.