Skip to content

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/.

  • -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, the effect is Modify; 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 on x[*] adds an element to the array. On a property of the elements, such as Field '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).
  • 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.

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.