了解 Azure Policy 效果Understand Azure Policy effects

Azure Policy 中的每个策略定义都有单一效果。Each policy definition in Azure Policy has a single effect. 该效果确定了在评估匹配的策略规则时发生的情况。That effect determines what happens when the policy rule is evaluated to match. 如果这些效果适用于新资源、更新的资源或现有资源,则它们的行为会有所不同。The effects behave differently if they are for a new resource, an updated resource, or an existing resource.

目前策略定义中支持以下效果:These effects are currently supported in a policy definition:

评估顺序Order of evaluation

Azure Policy 首先评估创建或更新资源的请求。Requests to create or update a resource are evaluated by Azure Policy first. Azure Policy 会创建将应用于资源的所有分配列表,然后根据每个定义评估资源。Azure Policy creates a list of all assignments that apply to the resource and then evaluates the resource against each definition. 对于资源管理器模式,Azure Policy 在将请求转交给相应的资源提供程序之前处理多个效果。For a Resource Manager mode, Azure Policy processes several of the effects before handing the request to the appropriate Resource Provider. 此顺序可以防止资源提供程序在资源不符合 Azure Policy 的设计治理控制时进行不必要的处理。This order prevents unnecessary processing by a Resource Provider when a resource doesn't meet the designed governance controls of Azure Policy. 使用资源提供程序模式,资源提供程序管理评估和结果,并将结果报告回 Azure Policy。With a Resource Provider mode, the Resource Provider manages the evaluation and outcome and reports the results back to Azure Policy.

  • 首先检查 已禁用 效果以确定是否应评估策略规则。Disabled is checked first to determine if the policy rule should be evaluated.
  • 然后评估“附加”和“修改”。 Append and Modify are then evaluated. 由于这两个效果可能会改变请求,因此所做的更改可能会阻止“审核”或“拒绝”效果的触发。Since either could alter the request, a change made may prevent an audit or deny effect from triggering. 这些效果仅在资源管理器模式下可用。These effects are only available with a Resource Manager mode.
  • 然后评估“拒绝”。Deny is then evaluated. 通过在“审核”之前评估“拒绝”,可以防止两次记录不需要的资源。By evaluating deny before audit, double logging of an undesired resource is prevented.
  • 最后评估审核。Audit is evaluated last.

资源提供程序针对资源管理器模式请求返回成功代码后,AuditIfNotExists 和 DeployIfNotExists 将进行评估以确定是否需要其他符合性日志记录或操作 。After the Resource Provider returns a success code on a Resource Manager mode request, AuditIfNotExists and DeployIfNotExists evaluate to determine if additional compliance logging or action is required.

附加Append

附加用于在创建或更新期间向请求的资源添加其他字段。Append is used to add additional fields to the requested resource during creation or update. 常见的示例是为存储资源指定允许的 Ip。A common example is specifying allowed IPs for a storage resource.

重要

附加用于非标记的属性。Append is intended for use with non-tag properties. 尽管附加可以在创建或更新请求期间将标记添加到资源,但建议使用修改效果取代标记。While Append can add tags to a resource during a create or update request, it's recommended to use the Modify effect for tags instead.

“附加”评估Append evaluation

在创建或更新资源期间,会在资源提供程序处理请求之前进行“附加”评估。Append evaluates before the request gets processed by a Resource Provider during the creation or updating of a resource. 当满足策略规则的 if 条件时,“附加”会向资源添加字段。Append adds fields to the resource when the if condition of the policy rule is met. 如果“附加”效果使用其他值替代原始请求中的值,则它会充当拒绝效果并拒绝该请求。If the append effect would override a value in the original request with a different value, then it acts as a deny effect and rejects the request. 若要将新值附加到现有数组,请使用 [*] 版本的别名。To append a new value to an existing array, use the [*] version of the alias.

当使用附加效果的策略定义作为评估周期的一部分运行时,它不会更改已存在的资源。When a policy definition using the append effect is run as part of an evaluation cycle, it doesn't make changes to resources that already exist. 相反,它会将符合 if 条件的任意资源标记为不符合。Instead, it marks any resource that meets the if condition as non-compliant.

“附加”属性Append properties

附加效果只有“详细信息”数组,它是必需的。An append effect only has a details array, which is required. 因为“详细信息”是一个数组,它可能需要单个或多个字段/值对。As details is an array, it can take either a single field/value pair or multiples. 请参阅定义结构,获取可接受的字段列表。Refer to definition structure for the list of acceptable fields.

“附加”示例Append examples

示例 1:单个“字段/值”对使用具有数组值的非 [*] 别名在存储帐户上设置 IP 规则。 Example 1: Single field/value pair using a non-[*] alias with an array value to set IP rules on a storage account. 如果非 [*] 别名是数组,则附加效果会将值附加为整个数组When the non-[*] alias is an array, the effect appends the value as the entire array. 如果数组已存在,该冲突会导致拒绝事件发生。If the array already exists, a deny event occurs from the conflict.

"then": {
    "effect": "append",
    "details": [{
        "field": "Microsoft.Storage/storageAccounts/networkAcls.ipRules",
        "value": [{
            "action": "Allow",
            "value": "134.5.0.0/21"
        }]
    }]
}

示例 2:单个“字段/值”对使用具有数组值的 [*] 别名在存储帐户上设置 IP 规则。 Example 2: Single field/value pair using an [*] alias with an array value to set IP rules on a storage account. 通过使用 [*] 别名,附加效果会将值附加到可能预先存在的数组。 By using the [*] alias, the effect appends the value to a potentially pre-existing array. 如果数组尚不存在,将会创建它。If the array doesn't exist yet, it's created.

"then": {
    "effect": "append",
    "details": [{
        "field": "Microsoft.Storage/storageAccounts/networkAcls.ipRules[*]",
        "value": {
            "value": "40.40.40.40",
            "action": "Allow"
        }
    }]
}

审核Audit

“审核”用于评估不合规资源时在活动日志中创建警告事件,但不会停止请求。Audit is used to create a warning event in the activity log when evaluating a non-compliant resource, but it doesn't stop the request.

“审核”评估Audit evaluation

“审核”是 Azure Policy 在创建或更新资源期间检查的最后一个效果。Audit is the last effect checked by Azure Policy during the creation or update of a resource. 对于资源管理器模式,Azure Policy 会将资源发送到资源提供程序。For a Resource Manager mode, Azure Policy then sends the resource to the Resource Provider. “审核”对于资源请求和评估周期的工作方式相同。Audit works the same for a resource request and an evaluation cycle. 对于新资源和已更新的资源,Azure Policy 会将 Microsoft.Authorization/policies/audit/action 操作添加到活动日志,并将该资源标记为不合规。For new and updated resources, Azure Policy adds a Microsoft.Authorization/policies/audit/action operation to the activity log and marks the resource as non-compliant.

“审核”属性Audit properties

对于资源管理器模式,Audit 效果没有任何其他属性可用于策略定义的 then 条件。For a Resource Manager mode, the audit effect doesn't have any additional properties for use in the then condition of the policy definition.

对于 Microsoft.Kubernetes.Data 的资源提供程序模式,Audit 效果具有以下 details 的附加子属性。For a Resource Provider mode of Microsoft.Kubernetes.Data, the audit effect has the following additional subproperties of details.

  • constraintTemplate(必选)constraintTemplate (required)
    • 约束模板 CustomResourceDefinition (CRD) 定义新约束。The Constraint template CustomResourceDefinition (CRD) that defines new Constraints. 该模板定义 Rego 逻辑、约束架构和通过 Azure Policy 的值传递的约束参数。The template defines the Rego logic, the Constraint schema, and the Constraint parameters that are passed via values from Azure Policy.
  • constraint(必选)constraint (required)
    • 约束模板的 CRD 实现。The CRD implementation of the Constraint template. 使用通过值传递的参数,如 {{ .Values.<valuename> }}Uses parameters passed via values as {{ .Values.<valuename> }}. 在下面的示例 2 中,这些值为 {{ .Values.excludedNamespaces }}{{ .Values.allowedContainerImagesRegex }}In example 2 below, these values are {{ .Values.excludedNamespaces }} and {{ .Values.allowedContainerImagesRegex }}.
  • values(可选)values (optional)
    • 定义要传递给约束的任何参数和值。Defines any parameters and values to pass to the Constraint. 每个值都必须在约束模板 CRD 中存在。Each value must exist in the Constraint template CRD.

“审核”示例Audit example

示例 1:对资源管理器模式使用 Audit 效果。Example 1: Using the audit effect for Resource Manager modes.

"then": {
    "effect": "audit"
}

示例 2:对 Microsoft.Kubernetes.Data 的资源提供程序模式使用 Audit 效果。Example 2: Using the audit effect for a Resource Provider mode of Microsoft.Kubernetes.Data. details 中的附加信息定义了要在 Kubernetes 中使用以限制允许的容器映像的约束模板和 CRD。The additional information in details defines the Constraint template and CRD to use in Kubernetes to limit the allowed container images.

"then": {
    "effect": "audit",
    "details": {
        "constraintTemplate": "https://raw.githubusercontent.com/Azure/azure-policy/master/built-in-references/Kubernetes/container-allowed-images/template.yaml",
        "constraint": "https://raw.githubusercontent.com/Azure/azure-policy/master/built-in-references/Kubernetes/container-allowed-images/constraint.yaml",
        "values": {
            "allowedContainerImagesRegex": "[parameters('allowedContainerImagesRegex')]",
            "excludedNamespaces": "[parameters('excludedNamespaces')]"
        }
    }
}

AuditIfNotExistsAuditIfNotExists

AuditIfNotExists 对与匹配 if 条件的资源相关的资源启用审核,但没有在 then 条件的 details 中指定的属性 。AuditIfNotExists enables auditing of resources related to the resource that matches the if condition, but don't have the properties specified in the details of the then condition.

AuditIfNotExists 评估AuditIfNotExists evaluation

AuditIfNotExists 在资源提供程序处理资源创建或更新请求并返回成功状态代码后运行。AuditIfNotExists runs after a Resource Provider has handled a create or update resource request and has returned a success status code. 如果没有相关资源或如果由 ExistenceCondition 定义的资源未评估为 true,则会发生审核。The audit occurs if there are no related resources or if the resources defined by ExistenceCondition don't evaluate to true. 对于新资源和已更新的资源,Azure Policy 会将 Microsoft.Authorization/policies/audit/action 操作添加到活动日志,并将该资源标记为不合规。For new and updated resources, Azure Policy adds a Microsoft.Authorization/policies/audit/action operation to the activity log and marks the resource as non-compliant. 触发后,满足 if 条件的资源是标记为不符合的资源。When triggered, the resource that satisfied the if condition is the resource that is marked as non-compliant.

AuditIfNotExists 属性AuditIfNotExists properties

AuditIfNotExists 效果的“details”属性具有定义要匹配的相关资源的所有子属性。The details property of the AuditIfNotExists effects has all the subproperties that define the related resources to match.

  • Type(必选)Type (required)
    • 指定要匹配的相关资源的类型。Specifies the type of the related resource to match.
    • 如果 details.type 是 if 条件资源下的一个资源类型,则策略会在已评估资源范围内查询此“类型”的资源。 If details.type is a resource type underneath the if condition resource, the policy queries for resources of this type within the scope of the evaluated resource. 否则,策略会在与已评估资源同一资源组范围内查询。Otherwise, policy queries within the same resource group as the evaluated resource.
  • Name(可选)Name (optional)
    • 指定要匹配的资源的确切名称,并使策略提取一个特定资源,而不是指定类型的所有资源。Specifies the exact name of the resource to match and causes the policy to fetch one specific resource instead of all resources of the specified type.
    • 当 if.field.type 和 then.details.type 的条件值匹配时,Name 将变为必需且必须为 [field('name')] 或子资源的 [field('fullName')]When the condition values for if.field.type and then.details.type match, then Name becomes required and must be [field('name')], or [field('fullName')] for a child resource. 但是,应考虑改用审核效果。However, an audit effect should be considered instead.
  • ResourceGroupName(可选)ResourceGroupName (optional)
    • 允许相关资源的匹配来自不同的资源组。Allows the matching of the related resource to come from a different resource group.
    • 如果 typeif 条件资源下的一个资源,则不适用。Doesn't apply if type is a resource that would be underneath the if condition resource.
    • 默认值是 if 条件资源的资源组。Default is the if condition resource's resource group.
  • ExistenceScope(可选)ExistenceScope (optional)
    • 允许的值为 Subscription 和 ResourceGroup。Allowed values are Subscription and ResourceGroup.
    • 设置从中获取相关资源以在其中进行匹配的范围。Sets the scope of where to fetch the related resource to match from.
    • 如果 typeif 条件资源下的一个资源,则不适用。Doesn't apply if type is a resource that would be underneath the if condition resource.
    • ResourceGroup 将限制在 if 条件资源的资源组或 ResourceGroupName 中指定的资源组。For ResourceGroup, would limit to the if condition resource's resource group or the resource group specified in ResourceGroupName.
    • 对于 Subscription,则查询全部订阅以获取相关资源。For Subscription, queries the entire subscription for the related resource.
    • 默认值是 ResourceGroup。Default is ResourceGroup.
  • ExistenceCondition(可选)ExistenceCondition (optional)
    • 如果未指定,任何 type 的相关资源均满足此效果,并且不会触发审核。If not specified, any related resource of type satisfies the effect and doesn't trigger the audit.
    • 使用与 if 条件的策略规则相同的语言,但会分别针对每个相关资源进行评估。Uses the same language as the policy rule for the if condition, but is evaluated against each related resource individually.
    • 如果任何匹配的相关资源评估结果为 true,该效果就会得到满足并且不会触发审核。If any matching related resource evaluates to true, the effect is satisfied and doesn't trigger the audit.
    • 可以使用 [field()] 检查 if 条件中的值的等效性。Can use [field()] to check equivalence with values in the if condition.
    • 例如,可用于验证父资源(位于 if 条件中)与匹配的相关资源位于相同的资源位置。For example, could be used to validate that the parent resource (in the if condition) is in the same resource location as the matching related resource.

AuditIfNotExists 示例AuditIfNotExists example

示例:评估虚拟机以确定是否存在反恶意软件扩展,然后在缺失时进行审核。Example: Evaluates Virtual Machines to determine if the Antimalware extension exists then audits when missing.

{
    "if": {
        "field": "type",
        "equals": "Microsoft.Compute/virtualMachines"
    },
    "then": {
        "effect": "auditIfNotExists",
        "details": {
            "type": "Microsoft.Compute/virtualMachines/extensions",
            "existenceCondition": {
                "allOf": [{
                        "field": "Microsoft.Compute/virtualMachines/extensions/publisher",
                        "equals": "Microsoft.Azure.Security"
                    },
                    {
                        "field": "Microsoft.Compute/virtualMachines/extensions/type",
                        "equals": "IaaSAntimalware"
                    }
                ]
            }
        }
    }
}

拒绝Deny

“拒绝”用于通过策略定义防止与定义的标准不匹配的资源请求,并使请求失败。Deny is used to prevent a resource request that doesn't match defined standards through a policy definition and fails the request.

“拒绝”评估Deny evaluation

在资源管理器模式下创建或更新匹配的资源时,Deny 会在发送给资源提供程序之前阻止请求。When creating or updating a matched resource in a Resource Manager mode, deny prevents the request before being sent to the Resource Provider. 该请求返回为 403 (Forbidden)The request is returned as a 403 (Forbidden). 在门户中,可以将 Forbidden(禁止)视为策略分配阻止的部署状态。In the portal, the Forbidden can be viewed as a status on the deployment that was prevented by the policy assignment. 对于资源提供程序模式,资源提供程序管理资源的评估。For a Resource Provider mode, the resource provider manages the evaluation of the resource.

在评估现有资源期间,与“拒绝”策略定义匹配的资源将标记为不合规。During evaluation of existing resources, resources that match a deny policy definition are marked as non-compliant.

“拒绝”属性Deny properties

对于资源管理器模式,Deny 效果没有任何其他属性可用于策略定义的 then 条件。For a Resource Manager mode, the deny effect doesn't have any additional properties for use in the then condition of the policy definition.

对于 Microsoft.Kubernetes.Data 的资源提供程序模式,Deny 效果具有以下 details 的附加子属性。For a Resource Provider mode of Microsoft.Kubernetes.Data, the deny effect has the following additional subproperties of details.

  • constraintTemplate(必选)constraintTemplate (required)
    • 约束模板 CustomResourceDefinition (CRD) 定义新约束。The Constraint template CustomResourceDefinition (CRD) that defines new Constraints. 该模板定义 Rego 逻辑、约束架构和通过 Azure Policy 的值传递的约束参数。The template defines the Rego logic, the Constraint schema, and the Constraint parameters that are passed via values from Azure Policy.
  • constraint(必选)constraint (required)
    • 约束模板的 CRD 实现。The CRD implementation of the Constraint template. 使用通过值传递的参数,如 {{ .Values.<valuename> }}Uses parameters passed via values as {{ .Values.<valuename> }}. 在下面的示例 2 中,这些值为 {{ .Values.excludedNamespaces }}{{ .Values.allowedContainerImagesRegex }}In example 2 below, these values are {{ .Values.excludedNamespaces }} and {{ .Values.allowedContainerImagesRegex }}.
  • values(可选)values (optional)
    • 定义要传递给约束的任何参数和值。Defines any parameters and values to pass to the Constraint. 每个值都必须在约束模板 CRD 中存在。Each value must exist in the Constraint template CRD.

“拒绝”示例Deny example

示例 1:对资源管理器模式使用 Deny 效果。Example 1: Using the deny effect for Resource Manager modes.

"then": {
    "effect": "deny"
}

示例 2:对 Microsoft.Kubernetes.Data 的资源提供程序模式使用 Deny 效果。Example 2: Using the deny effect for a Resource Provider mode of Microsoft.Kubernetes.Data. details 中的附加信息定义了要在 Kubernetes 中使用以限制允许的容器映像的约束模板和 CRD。The additional information in details defines the Constraint template and CRD to use in Kubernetes to limit the allowed container images.

"then": {
    "effect": "deny",
    "details": {
        "constraintTemplate": "https://raw.githubusercontent.com/Azure/azure-policy/master/built-in-references/Kubernetes/container-allowed-images/template.yaml",
        "constraint": "https://raw.githubusercontent.com/Azure/azure-policy/master/built-in-references/Kubernetes/container-allowed-images/constraint.yaml",
        "values": {
            "allowedContainerImagesRegex": "[parameters('allowedContainerImagesRegex')]",
            "excludedNamespaces": "[parameters('excludedNamespaces')]"
        }
    }
}

DeployIfNotExistsDeployIfNotExists

与 AuditIfNotExists 类似,DeployIfNotExists 策略定义在条件满足时将执行模板部署。Similar to AuditIfNotExists, a DeployIfNotExists policy definition executes a template deployment when the condition is met.

备注

deployIfNotExists 支持 嵌套模板,但目前不支持 链接模版Nested templates are supported with deployIfNotExists, but linked templates are currently not supported.

DeployIfNotExists 评估DeployIfNotExists evaluation

DeployIfNotExists 将在资源提供程序处理创建或更新资源请求并返回成功状态代码后运行约 15 分钟。DeployIfNotExists runs about 15 minutes after a Resource Provider has handled a create or update resource request and has returned a success status code. 如果没有相关资源或如果由 ExistenceCondition 定义的资源未评估为 true,则会发生模板部署。A template deployment occurs if there are no related resources or if the resources defined by ExistenceCondition don't evaluate to true. 部署持续时间取决于模板中包含资源的复杂性。The duration of the deployment depends on the complexity of resources included in the template.

在评估周期中,具有与资源匹配的 DeployIfNotExists 效果的策略定义被标记为不合规,但不对该资源执行任何操作。During an evaluation cycle, policy definitions with a DeployIfNotExists effect that match resources are marked as non-compliant, but no action is taken on that resource. 使用修正任务来修正现有不符合资源。Existing non-compliant resources can be remediated with a remediation task.

DeployIfNotExists 属性DeployIfNotExists properties

DeployIfNotExists 效果的“details”属性具有定义要匹配的相关资源和要执行的模板部署的所有子属性。The details property of the DeployIfNotExists effect has all the subproperties that define the related resources to match and the template deployment to execute.

  • Type(必选)Type (required)

    • 指定要匹配的相关资源的类型。Specifies the type of the related resource to match.
    • 首先尝试提取 if 条件资源下的资源,然后在与 if 条件资源相同的资源组中进行查询。Starts by trying to fetch a resource underneath the if condition resource, then queries within the same resource group as the if condition resource.
  • Name(可选)Name (optional)

    • 指定要匹配的资源的确切名称,并使策略提取一个特定资源,而不是指定类型的所有资源。Specifies the exact name of the resource to match and causes the policy to fetch one specific resource instead of all resources of the specified type.
    • 当 if.field.type 和 then.details.type 的条件值匹配时,Name 将变为必需且必须为 [field('name')] 或子资源的 [field('fullName')]When the condition values for if.field.type and then.details.type match, then Name becomes required and must be [field('name')], or [field('fullName')] for a child resource.
  • ResourceGroupName(可选)ResourceGroupName (optional)

    • 允许相关资源的匹配来自不同的资源组。Allows the matching of the related resource to come from a different resource group.
    • 如果 typeif 条件资源下的一个资源,则不适用。Doesn't apply if type is a resource that would be underneath the if condition resource.
    • 默认值是 if 条件资源的资源组。Default is the if condition resource's resource group.
    • 如果执行模板部署,则将其部署在此值的资源组中。If a template deployment is executed, it's deployed in the resource group of this value.
  • ExistenceScope(可选)ExistenceScope (optional)

    • 允许的值为 Subscription 和 ResourceGroup。Allowed values are Subscription and ResourceGroup.
    • 设置从中获取相关资源以在其中进行匹配的范围。Sets the scope of where to fetch the related resource to match from.
    • 如果 typeif 条件资源下的一个资源,则不适用。Doesn't apply if type is a resource that would be underneath the if condition resource.
    • ResourceGroup 将限制在 if 条件资源的资源组或 ResourceGroupName 中指定的资源组。For ResourceGroup, would limit to the if condition resource's resource group or the resource group specified in ResourceGroupName.
    • 对于 Subscription,则查询全部订阅以获取相关资源。For Subscription, queries the entire subscription for the related resource.
    • 默认值是 ResourceGroup。Default is ResourceGroup.
  • ExistenceCondition(可选)ExistenceCondition (optional)

    • 如果未指定,任何 type 的相关资源均满足此效果,并且不会触发部署。If not specified, any related resource of type satisfies the effect and doesn't trigger the deployment.
    • 使用与 if 条件的策略规则相同的语言,但会分别针对每个相关资源进行评估。Uses the same language as the policy rule for the if condition, but is evaluated against each related resource individually.
    • 如果任何匹配的相关资源评估结果为 true,该效果就会得到满足并且不会触发部署。If any matching related resource evaluates to true, the effect is satisfied and doesn't trigger the deployment.
    • 可以使用 [field()] 检查 if 条件中的值的等效性。Can use [field()] to check equivalence with values in the if condition.
    • 例如,可用于验证父资源(位于 if 条件中)与匹配的相关资源位于相同的资源位置。For example, could be used to validate that the parent resource (in the if condition) is in the same resource location as the matching related resource.
  • roleDefinitionIds(必选)roleDefinitionIds (required)

    • 此属性必须包含与可通过订阅访问的基于角色的访问控制角色 ID 匹配的字符串数组。This property must include an array of strings that match role-based access control role ID accessible by the subscription. 有关详细信息,请参阅修正 - 配置策略定义For more information, see remediation - configure policy definition.
  • DeploymentScope(可选)DeploymentScope (optional)

    • 允许的值为 Subscription 和 ResourceGroup。Allowed values are Subscription and ResourceGroup.
    • 设置要触发的部署类型。Sets the type of deployment to be triggered. Subscription 指示 在订阅级别部署ResourceGroup 指示部署到资源组。Subscription indicates a deployment at subscription level, ResourceGroup indicates a deployment to a resource group.
    • 使用订阅级别部署时,必须在 Deployment 中指定 location 属性。A location property must be specified in the Deployment when using subscription level deployments.
    • 默认值是 ResourceGroup。Default is ResourceGroup.
  • Deployment(必选)Deployment (required)

    • 该属性应包含完整的模板部署,因为它将传递给 Microsoft.Resources/deployments PUT API。This property should include the full template deployment as it would be passed to the Microsoft.Resources/deployments PUT API. 有关详细信息,请参阅部署 REST APIFor more information, see the Deployments REST API.

    备注

    Deployment 属性中的所有函数都将作为模板(而不是策略)的组件进行评估。All functions inside the Deployment property are evaluated as components of the template, not the policy. 此异常是将值从策略传递到模板的 parameters 属性。The exception is the parameters property that passes values from the policy to the template. 本节中模板参数名称下的 value 用于执行此值传递操作(请参阅 DeployIfNotExists 示例中的 fullDbName)。The value in this section under a template parameter name is used to perform this value passing (see fullDbName in the DeployIfNotExists example).

DeployIfNotExists 示例DeployIfNotExists example

示例:评估 SQL Server 数据库以确定是否启用 transparentDataEncryption。Example: Evaluates SQL Server databases to determine if transparentDataEncryption is enabled. 如果未启用,则执行启用它的部署。If not, then a deployment to enable is executed.

"if": {
    "field": "type",
    "equals": "Microsoft.Sql/servers/databases"
},
"then": {
    "effect": "DeployIfNotExists",
    "details": {
        "type": "Microsoft.Sql/servers/databases/transparentDataEncryption",
        "name": "current",
        "roleDefinitionIds": [
            "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/roleDefinitions/{roleGUID}",
            "/providers/Microsoft.Authorization/roleDefinitions/{builtinroleGUID}"
        ],
        "existenceCondition": {
            "field": "Microsoft.Sql/transparentDataEncryption.status",
            "equals": "Enabled"
        },
        "deployment": {
            "properties": {
                "mode": "incremental",
                "template": {
                    "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
                    "contentVersion": "1.0.0.0",
                    "parameters": {
                        "fullDbName": {
                            "type": "string"
                        }
                    },
                    "resources": [{
                        "name": "[concat(parameters('fullDbName'), '/current')]",
                        "type": "Microsoft.Sql/servers/databases/transparentDataEncryption",
                        "apiVersion": "2014-04-01",
                        "properties": {
                            "status": "Enabled"
                        }
                    }]
                },
                "parameters": {
                    "fullDbName": {
                        "value": "[field('fullName')]"
                    }
                }
            }
        }
    }
}

已禁用Disabled

对于测试情况以及在策略定义已参数化效果时,此效果很有用。This effect is useful for testing situations or for when the policy definition has parameterized the effect. 借助这种灵活性可以禁用单个分配,而无需禁用该策略的所有分配。This flexibility makes it possible to disable a single assignment instead of disabling all of that policy's assignments.

Disabled 效果的替代方法是 enforcementMode,可在策略分配上设置。An alternative to the Disabled effect is enforcementMode, which is set on the policy assignment. enforcementMode 已禁用时,仍可评估资源。When enforcementMode is Disabled, resources are still evaluated. 日志(例如活动日志)和策略效果不会出现。Logging, such as Activity logs, and the policy effect don't occur. 有关详细信息,请参阅策略分配 - 强制模式For more information, see policy assignment - enforcement mode.

修改Modify

Modify 用于在创建或更新期间在资源中添加、更新或删除属性或标记。Modify is used to add, update, or remove properties or tags on a resource during creation or update. 常见的示例是在 costCenter 等资源上更新标记。A common example is updating tags on resources such as costCenter. 使用修正任务来修正现有不符合资源。Existing non-compliant resources can be remediated with a remediation task. 单个修改规则可以有任意数量的操作。A single Modify rule can have any number of operations.

Modify 支持以下操作:The following operations are supported by Modify:

  • 添加、替换或删除资源标记。Add, replace or remove resource tags. 对于标记,除非目标资源是资源组,否则 Modify 策略的 mode 应设置为 Indexed。For tags, a Modify policy should have mode set to Indexed unless the target resource is a resource group.
  • 添加或替换虚拟机和虚拟机规模集的托管标识类型 (identity.type) 的值。Add or replace the value of managed identity type (identity.type) of virtual machines and virtual machine scale sets.
  • 添加或替换某些别名的值(预览)。Add or replace the values of certain aliases (preview).
    • 使用 Get-AzPolicyAlias | Select-Object -ExpandProperty 'Aliases' | Where-Object { $_.DefaultMetadata.Attributes -eq 'Modifiable' }Use Get-AzPolicyAlias | Select-Object -ExpandProperty 'Aliases' | Where-Object { $_.DefaultMetadata.Attributes -eq 'Modifiable' } 在 Azure PowerShell 4.6.0 或更高版本中,获取可与 Modify 一起使用的别名列表。in Azure PowerShell 4.6.0 or higher to get a list of aliases that can be used with Modify.

重要

如果你正在管理标记,我们建议使用 Modify 而不要使用 Append,因为 Modify 提供更多的操作类型,且能够修正现有的资源。If you're managing tags, it's recommended to use Modify instead of Append as Modify provides additional operation types and the ability to remediate existing resources. 但如果无法创建托管标识或 Modify 尚不支持资源属性的别名,则建议使用 Append。However, Append is recommended if you aren't able to create a managed identity or Modify doesn't yet support the alias for the resource property.

修改评估Modify evaluation

在创建或更新资源期间,修改会在资源提供程序处理请求之前进行评估。Modify evaluates before the request gets processed by a Resource Provider during the creation or updating of a resource. 如果策略规则的 if 条件得到满足,则 Modify 操作将应用于请求内容。The Modify operations are applied to the request content when the if condition of the policy rule is met. 每个 Modify 操作可以指定一个条件来决定何时应用它。Each Modify operation can specify a condition that determines when it's applied. 条件评估为 false 的操作将被跳过。Operations with conditions that are evaluated to false are skipped.

别名指定后,执行以下附加检查,确保 Modify 操作更改请求内容后不会导致资源提供程序拒绝该请求:When an alias is specified, the following additional checks are performed to ensure that the Modify operation doesn't change the request content in a way that causes the resource provider to reject it:

  • 在请求 API 版本中,别名映射到的属性标记为“可修改”。The property the alias maps to is marked as 'Modifiable' in the request's API version.
  • Modify 操作中的令牌类型与请求 API 版本中的属性的预期令牌类型匹配。The token type in the Modify operation matches the expected token type for the property in the request's API version.

如果这些检查中的任何一个失败,策略评估将回退到指定的 conflictEffect。If either of these checks fail, the policy evaluation falls back to the specified conflictEffect.

重要

建议包含别名的 Modify 定义采用 Audit 冲突效果,避免使用 API 版本(其中映射的属性不是“可修改”)的请求失败。It's recommeneded that Modify definitions that include aliases use the audit conflict effect to avoid failing requests using API versions where the mapped property isn't 'Modifiable'. 如果同一别名在不同 API 版本中的行为不同,可以使用 Conditional Modify 操作来确定对每个 API 版本使用的 Modify 操作。If the same alias behaves differently between API versions, conditional modify operations can be used to determine the modify operation used for each API version.

当使用修改效果的策略定义作为评估周期的一部分运行时,它不会更改已存在的资源。When a policy definition using the Modify effect is run as part of an evaluation cycle, it doesn't make changes to resources that already exist. 相反,它会将符合 if 条件的任意资源标记为不符合。Instead, it marks any resource that meets the if condition as non-compliant.

修改属性Modify properties

修改效果的“Details”属性包含定义修正所需权限以及用于添加、更新或删除标记值操作的所有子属性。 The details property of the Modify effect has all the subproperties that define the permissions needed for remediation and the operations used to add, update, or remove tag values.

  • roleDefinitionIds(必选)roleDefinitionIds (required)
    • 此属性必须包含与可通过订阅访问的基于角色的访问控制角色 ID 匹配的字符串数组。This property must include an array of strings that match role-based access control role ID accessible by the subscription. 有关详细信息,请参阅修正 - 配置策略定义For more information, see remediation - configure policy definition.
    • 定义的角色必须包括所有授予参与者角色的操作。The role defined must include all operations granted to the Contributor role.
  • conflictEffect(可选)conflictEffect (optional)
    • 确定在多个策略定义修改同一属性的情况下,或在 Modify 操作不适用于指定别名的情况下,哪个策略定义“胜出”。Determines which policy definition "wins" in the event that more than one policy definition modifies the same property or when the Modify operation doesn't work on the specified alias.
      • 对于新的或更新的资源,具有 Deny 的策略定义优先。For new or updated resources, the policy definition with deny takes precedence. 具有 Audit 的策略定义会跳过所有操作。Policy definitions with audit skip all operations. 如果多个策略定义具有 Deny,则该请求作为冲突被拒绝。If more than one policy definition has deny, the request is denied as a conflict. 如果所有策略定义都具有 Audit,则不处理冲突策略定义的任何操作。If all policy definitions have audit, then none of the operations of the conflicting policy definitions are processed.
      • 对于现有资源,如果多个策略定义具有 Deny,则符合性状态为“冲突” 。For existing resources, if more than one policy definition has deny, the compliance status is Conflict. 如果一个或更少的策略定义具有 Deny,则每个分配都返回“不符合”的符合性状态 。If one or fewer policy definitions have deny, each assignment returns a compliance status of Non-compliant.
    • 可用值:audit、deny、disabled 。Available values: audit, deny, disabled.
    • 默认值为 deny。Default value is deny.
  • operations(必选)operations (required)
    • 要在匹配资源上完成的所有标记操作的数组。An array of all tag operations to be completed on matching resources.
    • 属性:Properties:
      • operation(必选)operation (required)
        • 定义要在匹配资源上执行的操作。Defines what action to take on a matching resource. 选项为:addOrReplace 添加 删除Options are: addOrReplace, Add, Remove. 添加 行为与 附加效果类似。Add behaves similar to the Append effect.
      • field(必选)field (required)
        • 要添加、替换或删除的标记。The tag to add, replace, or remove. 对于其他字段,标记名称必须遵循相同的命名约定。Tag names must adhere to the same naming convention for other fields.
      • (可选)value (optional)
        • 要设置标记的值。The value to set the tag to.
        • 如果 操作addOrReplace添加,则需要此属性。This property is required if operation is addOrReplace or Add.
      • condition(可选)condition (optional)
        • 一个字符串,其中包含使用 Policy 函数的 Azure Policy 语言表达式,该表达式计算结果为 true 或 false 。A string containing an Azure Policy language expression with Policy functions that evaluates to true or false.
        • 不支持以下 Policy 函数:field()resourceGroup()subscription()Doesn't support the following Policy functions: field(), resourceGroup(), subscription().

修改操作Modify operations

操作 属性数组能够以不同的方式从单个策略定义中更改多个标记。The operations property array makes it possible to alter several tags in different ways from a single policy definition. 每个操作都由 操作 字段 属性组成。Each operation is made up of operation, field, and value properties. 操作确定修正任务对标记执行的操作,字段确定更改的标记,值定义该标记的新设置。Operation determines what the remediation task does to the tags, field determines which tag is altered, and value defines the new setting for that tag. 下面的示例进行了以下标记更改:The example below makes the following tag changes:

  • environment 标记设置为“Test”,即使它已存在且具有不同的值。Sets the environment tag to "Test", even if it already exists with a different value.
  • 删除标记 TempResourceRemoves the tag TempResource.
  • Dept 标记设置为在策略分配上配置的策略参数 DeptNameSets the Dept tag to the policy parameter DeptName configured on the policy assignment.
"details": {
    ...
    "operations": [
        {
            "operation": "addOrReplace",
            "field": "tags['environment']",
            "value": "Test"
        },
        {
            "operation": "Remove",
            "field": "tags['TempResource']",
        },
        {
            "operation": "addOrReplace",
            "field": "tags['Dept']",
            "value": "[parameters('DeptName')]"
        }
    ]
}

操作 属性具有以下选项:The operation property has the following options:

OperationOperation 说明Description
addOrReplaceaddOrReplace 将定义的属性或标记和值添加到资源,即使该属性或标记已存在并使用不同的值。Adds the defined property or tag and value to the resource, even if the property or tag already exists with a different value.
添加Add 将定义的属性或标记和值添加到资源。Adds the defined property or tag and value to the resource.
删除Remove 从资源中删除定义的属性或标记。Removes the defined property or tag from the resource.

修改示例Modify examples

示例 1:添加 environment 标记并将现有 environment 标记替换为“Test”:Example 1: Add the environment tag and replace existing environment tags with "Test":

"then": {
    "effect": "modify",
    "details": {
        "roleDefinitionIds": [
            "/providers/Microsoft.Authorization/roleDefinitions/b24988ac-6180-42a0-ab88-20f7382dd24c"
        ],
        "operations": [
            {
                "operation": "addOrReplace",
                "field": "tags['environment']",
                "value": "Test"
            }
        ]
    }
}

示例 2:删除 env 标记并添加 environment 标记,或将现有 environment 标记替换为参数化的值:Example 2: Remove the env tag and add the environment tag or replace existing environment tags with a parameterized value:

"then": {
    "effect": "modify",
    "details": {
        "roleDefinitionIds": [
            "/providers/Microsoft.Authorization/roleDefinitions/b24988ac-6180-42a0-ab88-20f7382dd24c"
        ],
        "conflictEffect": "deny",
        "operations": [
            {
                "operation": "Remove",
                "field": "tags['env']"
            },
            {
                "operation": "addOrReplace",
                "field": "tags['environment']",
                "value": "[parameters('tagValue')]"
            }
        ]
    }
}

示例 3:确保存储帐户不允许 blob 公共访问,仅在评估所用 API 版本大于或等于“2019-04-01”的请求时,才应用 Modify 操作:Example 3: Ensure that a storage account doesn't allow blob public access, the Modify operation is applied only when evaluating requests with API version greater or equals to '2019-04-01':

"then": {
    "effect": "modify",
    "details": {
        "roleDefinitionIds": [
            "/providers/microsoft.authorization/roleDefinitions/17d1049b-9a84-46fb-8f53-869881c3d3ab"
        ],
        "conflictEffect": "audit",
        "operations": [
            {
                "condition": "[greaterOrEquals(requestContext().apiVersion, '2019-04-01')]",
                "operation": "addOrReplace",
                "field": "Microsoft.Storage/storageAccounts/allowBlobPublicAccess",
                "value": false
            }
        ]
    }
}

策略定义分层Layering policy definitions

资源可能会受到多个分配的影响。A resource may be impacted by several assignments. 这些分配可能处于相同或不同的范围。These assignments may be at the same scope or at different scopes. 这些分配中的每一个也可能具有不同的定义效果。Each of these assignments is also likely to have a different effect defined. 将单独评估每个策略的条件和效果。The condition and effect for each policy is independently evaluated. 例如:For example:

  • 策略 1Policy 1
    • 将资源位置限制为“chinaeast2”Restricts resource location to 'chinaeast2'
    • 分配到订阅 AAssigned to subscription A
    • “拒绝”效果Deny effect
  • 策略 2Policy 2
    • 将资源位置限制为“chinaeast2”Restricts resource location to 'chinaeast2'
    • 分配到订阅 A 中的资源组 BAssigned to resource group B in subscription A
    • “审核”效果Audit effect

此设置将产生以下结果:This setup would result in the following outcome:

  • 位于“chinaeast2”的资源组 B 中的任何现有资源都符合策略 2,但不符合策略 1Any resource already in resource group B in 'chinaeast2' is compliant to policy 2 and non-compliant to policy 1
  • 不位于“chinaeast2”的资源组 B 中的任何现有资源都不符合策略 2,并且如果它们不在“chinaeast2”中,则也不符合策略 1Any resource already in resource group B not in 'chinaeast2' is non-compliant to policy 2 and non-compliant to policy 1 if not in 'chinaeast2'
  • 订阅 A 中任何不在“chinanorth2”中的新资源将会被策略 1 拒绝Any new resource in subscription A not in 'chinanorth2' is denied by policy 1
  • 位于“chinaeast2”的订阅 A 和资源组 B 中的任何新资源将会创建,但不符合策略 2Any new resource in subscription A and resource group B in 'chinaeast2' is created and non-compliant on policy 2

如果策略 1 和策略 2 都具有“拒绝”效果,则情况变为:If both policy 1 and policy 2 had effect of deny, the situation changes to:

  • 不位于“chinaeast2”的资源组 B 中的任何现有资源不符合策略 2Any resource already in resource group B not in 'chinaeast2' is non-compliant to policy 2
  • 不位于“chinaeast2”的资源组 B 中的任何现有资源不符合策略 1Any resource already in resource group B not in 'chinaeast2' is non-compliant to policy 1
  • 订阅 A 中任何不在“chinanorth2”中的新资源将会被策略 1 拒绝Any new resource in subscription A not in 'chinanorth2' is denied by policy 1
  • 订阅 A 的资源组 B 中的任何新资源将被拒绝Any new resource in resource group B of subscription A is denied

单独评估每个分配。Each assignment is individually evaluated. 因此,不存在因范围差异致使资源溜过间隙的可能性。As such, there isn't an opportunity for a resource to slip through a gap from differences in scope. 我们认为分层策略的最终结果是 累积最多限制The net result of layering policy definitions is considered to be cumulative most restrictive. 例如,如果策略 1 和策略 2 都具有“拒绝”效果,则重叠和冲突策略定义会阻止资源。As an example, if both policy 1 and 2 had a deny effect, a resource would be blocked by the overlapping and conflicting policy definitions. 如果仍然需要在目标范围内创建资源,请查看每项分配的排除项,以验证策略分配是否正在影响相应的范围。If you still need the resource to be created in the target scope, review the exclusions on each assignment to validate the right policy assignments are affecting the right scopes.

后续步骤Next steps