Effects¶
Every effect except Audit, Deny and Disabled, which are written with Effect, has its own keyword, in place of Effect.
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": "Modify",
"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, the effect isModify; 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 toAudit. 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
Appendonx[*]adds an element to the array. On a property of the elements, such asField 'networkAcls.ipRules[*].action' | Add 'Allow', it adds the value to that property of every element. One array level is allowed, as Learn documents;x[*].y[*]is an error (BYL3080).Appendwarns 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.
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:
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.