Azure Policy 定义结构Azure Policy definition structure

Azure Policy 使用资源策略定义来建立资源约定。Resource policy definitions are used by Azure Policy to establish conventions for resources. 每个定义描述资源符合性,以及在资源不符合的情况下会产生什么影响。Each definition describes resource compliance and what effect to take when a resource is non-compliant. 通过定义约定,可以控制成本并更轻松地管理资源。By defining conventions, you can control costs and more easily manage your resources. 例如,可指定仅允许特定类型的虚拟机。For example, you can specify that only certain types of virtual machines are allowed. 或者,可要求所有资源都拥有特定标记。Or, you can require that all resources have a particular tag. 策略由所有子资源继承。Policies are inherited by all child resources. 如果将策略应用到资源组,则会将其应用到该资源组中的所有资源。If a policy is applied to a resource group, it's applicable to all the resources in that resource group.

策略定义架构可在此处找到:https://schema.management.azure.com/schemas/2019-06-01/policyDefinition.jsonThe policy definition schema is found here: https://schema.management.azure.com/schemas/2019-06-01/policyDefinition.json

使用 JSON 创建策略定义。You use JSON to create a policy definition. 策略定义包含以下各项的元素:The policy definition contains elements for:

  • 模式mode
  • 参数parameters
  • 显示名称display name
  • descriptiondescription
  • 策略规则policy rule
    • 逻辑求值logical evaluation
    • 效果effect

例如,以下 JSON 说明限制资源部署位置的策略:For example, the following JSON shows a policy that limits where resources are deployed:

{
    "properties": {
        "mode": "all",
        "parameters": {
            "allowedLocations": {
                "type": "array",
                "metadata": {
                    "description": "The list of locations that can be specified when deploying resources",
                    "strongType": "location",
                    "displayName": "Allowed locations"
                },
                "defaultValue": [ "chinaeast2" ]
            }
        },
        "displayName": "Allowed locations",
        "description": "This policy enables you to restrict the locations your organization can specify when deploying resources.",
        "policyRule": {
            "if": {
                "not": {
                    "field": "location",
                    "in": "[parameters('allowedLocations')]"
                }
            },
            "then": {
                "effect": "deny"
            }
        }
    }
}

所有 Azure Policy 示例均位于 Azure Policy 示例中。All Azure Policy samples are at Azure Policy samples.

ModeMode

模式的配置取决于策略是针对 Azure 资源管理器属性还是资源提供程序属性。Mode is configured depending on if the policy is targeting an Azure Resource Manager property or a Resource Provider property.

“资源管理器”模式Resource Manager modes

模式确定将对策略评估哪些资源类型。The mode determines which resource types will be evaluated for a policy. 支持的模式包括:The supported modes are:

  • all:评估资源组和所有资源类型all: evaluate resource groups and all resource types
  • indexed:仅评估支持标记和位置的资源类型indexed: only evaluate resource types that support tags and location

大多数情况下,建议将“mode”设置为 allWe recommend that you set mode to all in most cases. 通过门户创建的所有策略定义使用 all 模式。All policy definitions created through the portal use the all mode. 如果使用 PowerShell 或 Azure CLI,则可以手动指定 mode 参数。If you use PowerShell or Azure CLI, you can specify the mode parameter manually. 如果策略定义不包含 mode 值,为提供后向兼容性,在 Azure PowerShell 中默认为 all,在 Azure CLI 中默认为 nullIf the policy definition doesn't include a mode value, it defaults to all in Azure PowerShell and to null in Azure CLI. null 模式等同于使用 indexed 来支持后向兼容性。A null mode is the same as using indexed to support backwards compatibility.

在创建强制执行标记或位置的策略时,应该使用 indexedindexed should be used when creating policies that enforce tags or locations. 虽然并不是必需的,但是它会阻止不支持标记和位置的资源,使其不会在符合性结果中显示为不兼容。While not required, it prevents resources that don't support tags and locations from showing up as non-compliant in the compliance results. 资源组是一个例外 。The exception is resource groups. 在资源组上强制执行位置或标记的策略应将“mode” 设为 all,并专门针对 Microsoft.Resources/subscriptions/resourceGroups 类型。Policies that enforce location or tags on a resource group should set mode to all and specifically target the Microsoft.Resources/subscriptions/resourceGroups type. 请在强制执行资源组标记查看相关示例。For an example, see Enforce resource group tags. 如需支持标记的资源的列表,请参阅 Azure 资源的标记支持For a list of resources that support tags, see Tag support for Azure resources.

parametersParameters

参数可减少策略定义的数量,有助于简化策略管理。Parameters help simplify your policy management by reducing the number of policy definitions. 使用类似窗体中字段的参数 - nameaddresscitystateThink of parameters like the fields on a form – name, address, city, state. 这些参数始终不变,但其值会基于窗体中的各填写内容变化。These parameters always stay the same, however their values change based on the individual filling out the form. 构建策略时,参数同样适用。Parameters work the same way when building policies. 如果在策略定义中包括参数,就可以通过使用不同的值重新使用策略以执行不同方案。By including parameters in a policy definition, you can reuse that policy for different scenarios by using different values.

Note

参数可以添加到现有和已分配的定义。Parameters may be added to an existing and assigned definition. 新参数必须包含 defaultValue 属性。The new parameter must include the defaultValue property. 这可以防止策略或计划的现有分配间接被设为无效。This prevents existing assignments of the policy or initiative from indirectly being made invalid.

参数属性Parameter properties

参数有下述可以在策略定义中使用的属性:A parameter has the following properties that are used in the policy definition:

  • name:参数的名称。name: The name of your parameter. 由策略规则中的 parameters 部署函数使用。Used by the parameters deployment function within the policy rule. 有关详细信息,请参阅使用参数值For more information, see using a parameter value.
  • type:确定参数是字符串数组对象布尔值整数浮点数还是日期/时间type: Determines if the parameter is a string, array, object, boolean, integer, float, or datetime.
  • metadata:定义主要由 Azure 门户用来显示用户友好信息的子属性:metadata: Defines subproperties primarily used by the Azure portal to display user-friendly information:
    • description:说明参数的用途。description: The explanation of what the parameter is used for. 可以用来提供可接受值的示例。Can be used to provide examples of acceptable values.
    • displayName:在门户中显示的用于参数的友好名称。displayName: The friendly name shown in the portal for the parameter.
    • strongType:(可选)通过门户分配策略定义时使用。strongType: (Optional) Used when assigning the policy definition through the portal. 提供上下文感知列表。Provides a context aware list. 有关详细信息,请参阅 strongTypeFor more information, see strongType.
    • assignPermissions:(可选)设置为 true 将让 Azure 门户在分配策略期间创建角色分配。assignPermissions: (Optional) Set as true to have Azure portal create role assignments during policy assignment. 如果希望分配处于分配作用域之外的权限,则此属性非常有用。This property is useful in case you wish to assign permissions outside the assignment scope. 策略中的每个角色定义(或计划中所有策略中的每个角色定义)有一个角色分配。There is one role assignment per role definition in the policy (or per role definition in all of the policies in the initiative). 参数值必须是有效的资源或作用域。The parameter value must be a valid resource or scope.
  • defaultValue:(可选)设置分配的参数的值(如果值未给定)。defaultValue: (Optional) Sets the value of the parameter in an assignment if no value is given. 在更新已分配的现有策略定义时必须使用此项。Required when updating an existing policy definition that is assigned.
  • allowedValues:(可选)提供参数在分配过程中接受的值的数组。allowedValues: (Optional) Provides an array of values that the parameter accepts during assignment.

例如,可以定义策略定义来限制资源的部署位置。As an example, you could define a policy definition to limit the locations where resources can be deployed. allowedLocations 可以是该策略定义的一个参数。A parameter for that policy definition could be allowedLocations. 每次分配策略定义来限制接受的值时,会使用此参数。This parameter would be used by each assignment of the policy definition to limit the accepted values. 使用 strongType 可以在通过门户完成分配时提供增强的体验:The use of strongType provides an enhanced experience when completing the assignment through the portal:

"parameters": {
    "allowedLocations": {
        "type": "array",
        "metadata": {
            "description": "The list of allowed locations for resources.",
            "displayName": "Allowed locations",
            "strongType": "location"
        },
        "defaultValue": [ "chinaeast2" ],
        "allowedValues": [
            "chinanorth2",
            "chinaeast",
            "chinaeast2"
        ]
    }
}

使用参数值Using a parameter value

在策略规则中,使用以下 parameters 函数语法引用参数:In the policy rule, you reference parameters with the following parameters function syntax:

{
    "field": "location",
    "in": "[parameters('allowedLocations')]"
}

此示例引用 allowedLocations 参数,该参数已在参数属性中演示过。This sample references the allowedLocations parameter that was demonstrated in parameter properties.

strongTypestrongType

metadata 属性中,可以使用 strongType 提供 Azure 门户中的选项多选列表。Within the metadata property, you can use strongType to provide a multi-select list of options within the Azure portal. strongType 的允许值目前包括:Allowed values for strongType currently include:

  • location
  • resourceTypes
  • storageSkus
  • vmSKUs
  • existingResourceGroups
  • omsWorkspace
  • Microsoft.EventHub/Namespaces/EventHubs
  • Microsoft.EventHub/Namespaces/EventHubs/AuthorizationRules
  • Microsoft.EventHub/Namespaces/AuthorizationRules
  • Microsoft.RecoveryServices/vaults
  • Microsoft.RecoveryServices/vaults/backupPolicies

定义位置Definition location

创建计划或策略时,需要指定定义位置。While creating an initiative or policy, it's necessary to specify the definition location. 定义位置必须是管理组或订阅。The definition location must be a management group or a subscription. 此位置决定了计划或策略的分配范围。This location determines the scope to which the initiative or policy can be assigned. 资源必须是用于分配的目标定义位置的层次结构中的直系成员或子代。Resources must be direct members of or children within the hierarchy of the definition location to target for assignment.

如果定义位置是:If the definition location is a:

  • 订阅 - 只能将该订阅中的资源分配给策略。Subscription - Only resources within that subscription can be assigned the policy.
  • 管理组 - 只能将子管理组和子订阅中的资源分配给策略。Management group - Only resources within child management groups and child subscriptions can be assigned the policy. 如果计划将策略定义应用于多个订阅,则位置必须是包含那些订阅的管理组。If you plan to apply the policy definition to several subscriptions, the location must be a management group that contains those subscriptions.

显示名称和说明Display name and description

请使用“displayName”和“description”来标识策略定义,并提供其使用上下文 。You use displayName and description to identify the policy definition and provide context for when it's used. displayName 的最大长度为 128 个字符,description 的最大长度为 512 个字符。displayName has a maximum length of 128 characters and description a maximum length of 512 characters.

策略规则Policy rule

策略规则包括 If and Then 块。The policy rule consists of If and Then blocks. If 块中,定义强制执行策略时指定的一个或多个条件。In the If block, you define one or more conditions that specify when the policy is enforced. 可以对这些条件应用逻辑运算符,以精确定义策略的方案。You can apply logical operators to these conditions to precisely define the scenario for a policy.

Then 块中,定义满足 If 条件时产生的效果。In the Then block, you define the effect that happens when the If conditions are fulfilled.

{
    "if": {
        <condition> | <logical operator>
    },
    "then": {
        "effect": "deny | audit | append | auditIfNotExists | deployIfNotExists | disabled"
    }
}

逻辑运算符Logical operators

支持的逻辑运算符为:Supported logical operators are:

  • "not": {condition or operator}
  • "allOf": [{condition or operator},{condition or operator}]
  • "anyOf": [{condition or operator},{condition or operator}]

not 语法反转条件的结果。The not syntax inverts the result of the condition. allOf 语法(与逻辑 And 操作相似)要求所有条件为 true。The allOf syntax (similar to the logical And operation) requires all conditions to be true. anyOf 语法(与逻辑 Or 操作相似)要求一个或多个条件为 true。The anyOf syntax (similar to the logical Or operation) requires one or more conditions to be true.

可以嵌套逻辑运算符。You can nest logical operators. 以下示例显示了嵌套在 allOf 操作中的 not 操作 。The following example shows a not operation that is nested within an allOf operation.

"if": {
    "allOf": [{
            "not": {
                "field": "tags",
                "containsKey": "application"
            }
        },
        {
            "field": "type",
            "equals": "Microsoft.Storage/storageAccounts"
        }
    ]
},

ConditionsConditions

条件用于评估 fieldvalue 访问器是否符合特定标准。A condition evaluates whether a field or the value accessor meets certain criteria. 支持的条件有:The supported conditions are:

  • "equals": "stringValue"
  • "notEquals": "stringValue"
  • "like": "stringValue"
  • "notLike": "stringValue"
  • "match": "stringValue"
  • "matchInsensitively": "stringValue"
  • "notMatch": "stringValue"
  • "notMatchInsensitively": "stringValue"
  • "contains": "stringValue"
  • "notContains": "stringValue"
  • "in": ["stringValue1","stringValue2"]
  • "notIn": ["stringValue1","stringValue2"]
  • "containsKey": "keyName"
  • "notContainsKey": "keyName"
  • "less": "value"
  • "lessOrEquals": "value"
  • "greater": "value"
  • "greaterOrEquals": "value"
  • "exists": "bool"

使用 like 和 notLike 条件时,请在值中指定通配符 *When using the like and notLike conditions, you provide a wildcard * in the value. 值不应包含多个通配符 *The value shouldn't have more than one wildcard *.

当使用 match 和 notMatch 条件时,请提供 # 来匹配数字,提供 ? 来匹配字母,提供 . 来匹配任何字符,并提供任何其他字符来匹配该实际字符。When using the match and notMatch conditions, provide # to match a digit, ? for a letter, . to match any character, and any other character to match that actual character. “match”和“notMatch”区分大小写 。match and notMatch are case-sensitive. “matchInsensitively”和“notMatchInsensitively”中提供了不区分大小写的替代方案 。Case-insensitive alternatives are available in matchInsensitively and notMatchInsensitively. 例如,请参阅允许多个名称模式For examples, see Allow several name patterns.

字段Fields

使用字段构成条件。Conditions are formed by using fields. 字段匹配资源请求有效负载中的属性,并说明资源的状态。A field matches properties in the resource request payload and describes the state of the resource.

支持以下字段:The following fields are supported:

  • name
  • fullName
    • 返回资源全名。Returns the full name of the resource. 资源全名是最前面为任意父资源名称的资源名称(例如“myServer/myDatabase”)。The full name of a resource is the resource name prepended by any parent resource names (for example "myServer/myDatabase").
  • kind
  • type
  • location
  • identity.type
  • tags
  • tags['<tagName>']
    • 此括号语法支持具有标点符号的标记名称,例如连字符、句点或空格。This bracket syntax supports tag names that have punctuation such as a hyphen, period, or space.
    • 其中 <tagName> 是要验证其条件的标记的名称。Where <tagName> is the name of the tag to validate the condition for.
    • 示例:tags['Acct.CostCenter'],其中 Acct.CostCenter 是标记的名称 。Examples: tags['Acct.CostCenter'] where Acct.CostCenter is the name of the tag.
  • tags['''<tagName>''']
    • 此括号语法通过双撇号进行转义,可支持在其中包含撇号的标记名称。This bracket syntax supports tag names that have apostrophes in it by escaping with double apostrophes.
    • 其中“<tagName>”是要验证其条件的标记的名称 。Where '<tagName>' is the name of the tag to validate the condition for.
    • 示例:tags['''My.Apostrophe.Tag'''],其中 'My.Apostrophe.Tag' 是标记的名称。Example: tags['''My.Apostrophe.Tag'''] where 'My.Apostrophe.Tag' is the name of the tag.
  • 属性别名 - 若要查看列表,请参阅别名property aliases - for a list, see Aliases.

Note

tags.<tagName>``tags[tagName]tags[tag.with.dots] 仍然是可接受的用于声明标记字段的方式。tags.<tagName>, tags[tagName], and tags[tag.with.dots] are still acceptable ways of declaring a tags field. 但是,首选表达式是上面列出的那些。However, the preferred expressions are those listed above.

使用带参数的标记Use tags with parameters

参数值可以传递给标记字段。A parameter value can be passed to a tag field. 将参数传递给标记字段可在策略分配期间提高策略定义的灵活性。Passing a parameter to a tag field increases the flexibility of the policy definition during policy assignment.

在以下示例中,concat 用于为名为 tagName 参数值的标记创建标记字段查找 。In the following example, concat is used to create a tags field lookup for the tag named the value of the tagName parameter. 如果该标记不存在,则使用 modify 效果通过 resourcegroup() 查找函数,使用在已审核资源父资源组上设置的相同命名标记的值来添加标记。If that tag doesn't exist, the modify effect is used to add the tag using the value of the same named tag set on the audited resources parent resource group by using the resourcegroup() lookup function.

{
    "if": {
        "field": "[concat('tags[', parameters('tagName'), ']')]",
        "exists": "false"
    },
    "then": {
        "effect": "modify",
        "details": {
            "operations": [{
                "operation": "add",
                "field": "[concat('tags[', parameters('tagName'), ']')]",
                "value": "[resourcegroup().tags[parameters('tagName')]]"
            }],
            "roleDefinitionIds": [
                "/providers/microsoft.authorization/roleDefinitions/b24988ac-6180-42a0-ab88-20f7382dd24c"
            ]
        }
    }
}

ValueValue

也可使用 value 来形成条件。Conditions can also be formed using value. value 会针对参数支持的模板函数或文本来检查条件。value checks conditions against parameters, supported template functions, or literals. value 可与任何支持的条件配对。value is paired with any supported condition.

Warning

如果模板函数的结果是错误,策略评估将会失败。 If the result of a template function is an error, policy evaluation fails. 失败的评估是一种隐式拒绝A failed evaluation is an implicit deny. 有关详细信息,请参阅避免模板错误For more information, see avoiding template failures.

Value 示例Value examples

此策略规则示例使用 valueresourceGroup() 函数和返回的 name 属性的结果与 like 条件 *netrg 进行对比。This policy rule example uses value to compare the result of the resourceGroup() function and the returned name property to a like condition of *netrg. 此规则拒绝名称以 *netrg 结尾的任何资源组中 type 不为 Microsoft.Network/* 的资源。The rule denies any resource not of the Microsoft.Network/* type in any resource group whose name ends in *netrg.

{
    "if": {
        "allOf": [{
                "value": "[resourceGroup().name]",
                "like": "*netrg"
            },
            {
                "field": "type",
                "notLike": "Microsoft.Network/*"
            }
        ]
    },
    "then": {
        "effect": "deny"
    }
}

此策略规则示例使用 value 来检查多个嵌套函数的结果是否 equals trueThis policy rule example uses value to check if the result of multiple nested functions equals true. 此规则拒绝并没有至少三个标记的资源。The rule denies any resource that doesn't have at least three tags.

{
    "mode": "indexed",
    "policyRule": {
        "if": {
            "value": "[less(length(field('tags')), 3)]",
            "equals": true
        },
        "then": {
            "effect": "deny"
        }
    }
}

避免模板错误Avoiding template failures

value 中使用模板函数可以指定许多复杂的嵌套函数。 The use of template functions in value allows for many complex nested functions. 如果模板函数的结果是错误,策略评估将会失败。 If the result of a template function is an error, policy evaluation fails. 失败的评估是一种隐式拒绝A failed evaluation is an implicit deny. 在特定情况下失败的 value 示例:An example of a value that fails in certain scenarios:

{
    "policyRule": {
        "if": {
            "value": "[substring(field('name'), 0, 3)]",
            "equals": "abc"
        },
        "then": {
            "effect": "audit"
        }
    }
}

上面的示例策略规则使用 substring()name 的前三个字符与 abc 进行比较。The example policy rule above uses substring() to compare the first three characters of name to abc. 如果 name 短于三个字符,substring() 函数会导致出错。If name is shorter than three characters, the substring() function results in an error. 此错误导致策略成为一种 deny(拒绝)效果。This error causes the policy to become a deny effect.

改用 if() 函数来检查 name 的前三个字符是否等于 abc,同时避免短于三个字符的 name 导致出错:Instead, use the if() function to check if the first three characters of name equal abc without allowing a name shorter than three characters to cause an error:

{
    "policyRule": {
        "if": {
            "value": "[if(greaterOrEquals(length(field('name')), 3), substring(field('name'), 0, 3), 'not starting with abc')]",
            "equals": "abc"
        },
        "then": {
            "effect": "audit"
        }
    }
}

if() 使用修改后的策略规则检查 name 的长度,然后尝试在短于三个字符的值中获取 substring()With the revised policy rule, if() checks the length of name before trying to get a substring() on a value with fewer than three characters. 如果 name 过短,则会返回“not starting with abc”,而不是与 abc 进行比较。If name is too short, the value "not starting with abc" is returned instead and compared to abc. 短名称不是以 abc 开头的资源仍不符合策略规则,但不再在评估期间导致出错。A resource with a short name that doesn't begin with abc still fails the policy rule, but no longer causes an error during evaluation.

计数Count

可以使用 计数 表达式来构成条件,用于统计资源有效负载中有多少个数组成员满足条件表达式。Conditions that count how many members of an array in the resource payload satisfy a condition expression can be formed using count expression. 常见方案是检查是“至少有一个”、“正好有一个”、“所有”还是“没有”数组成员满足条件。Common scenarios are checking whether 'at least one of', 'exactly one of', 'all of', or 'none of' the array members satisfy the condition. count 将根据条件表达式评估每个数组成员,并将 true 结果求和,然后将其与表达式运算符进行比较。count evaluates each array member for a condition expression and sums the true results, which is then compared to the expression operator.

count 表达式的结构为:The structure of the count expression is:

{
    "count": {
        "field": "<[*] alias>",
        "where": {
            /* condition expression */
        }
    },
    "<condition>": "<compare the count of true condition expression array members to this value>"
}

以下属性与 count 结合使用:The following properties are used with count:

  • count.field(必需):包含数组的路径,必须是数组别名。count.field (required): Contains the path to the array and must be an array alias. 如果缺少数组,表达式将评估为 false,而不考虑条件表达式。If the array is missing, the expression is evaluated to false without considering the condition expression.
  • count.where(可选):用于单独评估 count.field 的每个 [*] 别名数组成员的条件表达式。count.where (optional): The condition expression to individually evaluate each [*] alias array member of count.field. 如果未提供此属性,具有“field”路径的所有数组成员将评估为 trueIf this property is not provided, all array members with the path of 'field' are evaluated to true. 可在此属性中使用任何条件Any condition can be used inside this property. 可在此属性中使用逻辑运算符来创建复杂的评估要求。Logical operators can be used inside this property to create complex evaluation requirements.
  • <condition> (必需):该值将与满足 count.where 条件表达式的项数进行比较。<condition> (required): The value is compared to the number of items that met the count.where condition expression. 应使用数字条件A numeric condition should be used.

Count 示例Count examples

示例 1:检查数组是否为空Example 1: Check if an array is empty

{
    "count": {
        "field": "Microsoft.Network/networkSecurityGroups/securityRules[*]"
    },
    "equals": 0
}

示例 2:检查是否只有一个数组成员满足条件表达式Example 2: Check for only one array member to meet the condition expression

{
    "count": {
        "field": "Microsoft.Network/networkSecurityGroups/securityRules[*]",
        "where": {
            "field": "Microsoft.Network/networkSecurityGroups/securityRules[*].description",
            "equals": "My unique description"
        }
    },
    "equals": 1
}

示例 3:检查是否至少有一个数组成员满足条件表达式Example 3: Check for at least one array member to meet the condition expression

{
    "count": {
        "field": "Microsoft.Network/networkSecurityGroups/securityRules[*]",
        "where": {
            "field": "Microsoft.Network/networkSecurityGroups/securityRules[*].description",
            "equals": "My common description"
        }
    },
    "greaterOrEquals": 1
}

示例 4:检查是否所有对象数组成员满足条件表达式Example 4: Check that all object array members meet the condition expression

{
    "count": {
        "field": "Microsoft.Network/networkSecurityGroups/securityRules[*]",
        "where": {
            "field": "Microsoft.Network/networkSecurityGroups/securityRules[*].description",
            "equals": "description"
        }
    },
    "equals": "[length(field(Microsoft.Network/networkSecurityGroups/securityRules[*]))]"
}

示例 5:检查是否所有字符串数组成员满足条件表达式Example 5: Check that all string array members meet the condition expression

{
    "count": {
        "field": "Microsoft.Sql/servers/securityAlertPolicies/emailAddresses[*]",
        "where": {
            "field": "Microsoft.Sql/servers/securityAlertPolicies/emailAddresses[*]",
            "like": "*@contoso.com"
        }
    },
    "equals": "[length(field('Microsoft.Sql/servers/securityAlertPolicies/emailAddresses[*]'))]"
}

示例 6:在 value 中使用 field 来检查是否所有数组成员满足条件表达式Example 6: Use field inside value to check that all array members meet the condition expression

{
    "count": {
        "field": "Microsoft.Sql/servers/securityAlertPolicies/emailAddresses[*]",
        "where": {
            "value": "[last(split(first(field('Microsoft.Sql/servers/securityAlertPolicies/emailAddresses[*]')), '@'))]",
            "equals": "contoso.com"
        }
    },
    "equals": "[length(field('Microsoft.Sql/servers/securityAlertPolicies/emailAddresses[*]'))]"
}

示例 7:检查是否至少有一个数组成员与条件表达式中的多个属性匹配Example 7: Check that at least one array member matches multiple properties in the condition expression

{
    "count": {
        "field": "Microsoft.Network/networkSecurityGroups/securityRules[*]",
        "where": {
            "allOf": [
                {
                    "field": "Microsoft.Network/networkSecurityGroups/securityRules[*].direction",
                    "equals": "Inbound"
                },
                {
                    "field": "Microsoft.Network/networkSecurityGroups/securityRules[*].access",
                    "equals": "Allow"
                },
                {
                    "field": "Microsoft.Network/networkSecurityGroups/securityRules[*].destinationPortRange",
                    "equals": "3389"
                }
            ]
        }
    },
    "greater": 0
}

效果Effect

Azure Policy 支持以下类型的效果:Azure Policy supports the following types of effect:

  • Append:会将定义的字段集添加到请求Append: adds the defined set of fields to the request
  • Audit:会在活动日志中生成一个警告事件,但不会使请求失败Audit: generates a warning event in activity log but doesn't fail the request
  • AuditIfNotExists:如果相关资源不存在,则会在活动日志中生成一个警告事件AuditIfNotExists: generates a warning event in activity log if a related resource doesn't exist
  • Deny:会在活动日志中生成一个事件,并使请求失败Deny: generates an event in the activity log and fails the request
  • DeployIfNotExists:如果相关资源尚不存在,则会部署该资源DeployIfNotExists: deploys a related resource if it doesn't already exist
  • Disabled:不评估资源是否符合策略规则Disabled: doesn't evaluate resources for compliance to the policy rule
  • Modify:在资源中添加、更新或删除定义的标记Modify: adds, updates, or removes the defined tags from a resource

有关每种效果、评估顺序、属性和示例的完整详细信息,请参阅了解 Azure Policy 效果For complete details on each effect, order of evaluation, properties, and examples, see Understanding Azure Policy Effects.

策略函数Policy functions

除以下函数和用户定义的函数外,所有资源管理器模板函数均可在策略规则中使用:All Resource Manager template functions are available to use within a policy rule, except the following functions and user-defined functions:

  • copyIndex()copyIndex()
  • deployment()deployment()
  • list*list*
  • newGuid()newGuid()
  • pickZones()pickZones()
  • providers()providers()
  • reference()reference()
  • resourceId()resourceId()
  • variables()variables()

以下函数可在策略规则中使用,但与在 Azure 资源管理器模板中使用不同:The following functions are available to use in a policy rule, but differ from use in an Azure Resource Manager template:

  • addDays(dateTime, numberOfDaysToAdd)addDays(dateTime, numberOfDaysToAdd)
    • dateTime:[必需] 字符串 - 通用 ISO 8601 日期/时间格式“yyyy-MM-ddTHH:mm:ss.fffffffZ”的字符串dateTime: [Required] string - String in the Universal ISO 8601 DateTime format 'yyyy-MM-ddTHH:mm:ss.fffffffZ'
    • numberOfDaysToAdd:[必需] 整数 - 要添加的天数numberOfDaysToAdd: [Required] integer - Number of days to add
  • utcNow() - 与资源管理器模板不同,它可以在 defaultValue 之外使用。utcNow() - Unlike a Resource Manager template, this can be used outside defaultValue.
    • 以通用 ISO 8601 日期/时间格式“yyyy-MM-ddTHH:mm:ss.fffffffZ”返回设置为当前日期和时间的字符串Returns a string that is set to the current date and time in Universal ISO 8601 DateTime format 'yyyy-MM-ddTHH:mm:ss.fffffffZ'

此外,field 函数可用于策略规则。Additionally, the field function is available to policy rules. field 主要用于 AuditIfNotExistsDeployIfNotExists,以引用所评估资源上的字段。field is primarily used with AuditIfNotExists and DeployIfNotExists to reference fields on the resource that are being evaluated. 可以在 DeployIfNotExists 示例中看到这种用法的示例。An example of this use can be seen in the DeployIfNotExists example.

策略函数示例Policy function example

此策略规则示例使用 resourceGroup 资源函数获取 name 属性,并将该属性与 concat 数组和对象函数结合使用以构建 like 条件,该条件强制资源名称以资源组名称开头。This policy rule example uses the resourceGroup resource function to get the name property, combined with the concat array and object function to build a like condition that enforces the resource name to start with the resource group name.

{
    "if": {
        "not": {
            "field": "name",
            "like": "[concat(resourceGroup().name,'*')]"
        }
    },
    "then": {
        "effect": "deny"
    }
}

别名Aliases

使用属性别名来访问资源类型的特定属性。You use property aliases to access specific properties for a resource type. 通过别名,可限制允许用于资源属性的值和条件。Aliases enable you to restrict what values or conditions are allowed for a property on a resource. 每个别名会映射到给定资源类型不同 API 版本的路径。Each alias maps to paths in different API versions for a given resource type. 在策略评估期间,策略引擎会获取该 API 版本的属性路径。During policy evaluation, the policy engine gets the property path for that API version.

别名列表始终不断增长。The list of aliases is always growing. 若要找出 Azure Policy 当前支持哪些别名,请使用以下方法之一:To find what aliases are currently supported by Azure Policy, use one of the following methods:

  • Azure PowerShellAzure PowerShell

    # Login first with Connect-AzAccount -EnvironmentName AzureChinaCloud command
    
    # Use Get-AzPolicyAlias to list available providers
    Get-AzPolicyAlias -ListAvailable
    
    # Use Get-AzPolicyAlias to list aliases for a Namespace (such as Azure Compute -- Microsoft.Compute)
    (Get-AzPolicyAlias -NamespaceMatch 'compute').Aliases
    
  • Azure CLIAzure CLI

    # Login first with below commands
    az cloud set -n AzureChinaCloud
    az login
    
    # List namespaces
    az provider list --query [*].namespace
    
    # Get Azure Policy aliases for a specific Namespace (such as Azure Compute -- Microsoft.Compute)
    az provider show --namespace Microsoft.Compute --expand "resourceTypes/aliases" --query "resourceTypes[].aliases[].name"
    
  • REST API/ARMClientREST API / ARMClient

    GET https://management.chinacloudapi.cn/providers/?api-version=2017-08-01&$expand=resourceTypes/aliases
    

了解 [*] 别名Understanding the [*] alias

可用的几个别名的版本显示为“普通”名称,另一个版本的名称则附加了 [*]Several of the aliases that are available have a version that appears as a 'normal' name and another that has [*] attached to it. 例如:For example:

  • Microsoft.Storage/storageAccounts/networkAcls.ipRules
  • Microsoft.Storage/storageAccounts/networkAcls.ipRules[*]

“normal”别名表示单一值字段。The 'normal' alias represents the field as a single value. 如果整个值集必须确切定义(不能多定义,也不能少定义),则此字段将用于完全匹配比较方案。This field is for exact match comparison scenarios when the entire set of values must be exactly as defined, no more and no less.

使用 [*] 别名可以比较数组中的每个元素值以及每个元素的特定属性。The [*] alias makes it possible to compare against the value of each element in the array and specific properties of each element. 使用这种方法可以比较“if none of”、“if any of”或“if all of”方案的元素属性。This approach makes it possible to compare element properties for 'if none of', 'if any of', or 'if all of' scenarios. 对于更复杂的方案,请使用 count 条件表达式。For more complex scenarios, use the count condition expression. 使用 ipRules[*] 时,某个示例将会验证每个 action 是否为 Deny,但不考虑存在多少个规则,或 IP 的 value 是什么。Using ipRules[*], an example would be validating that every action is Deny, but not worrying about how many rules exist or what the IP value is. 此示例规则检查 10.0.4.1 的所有 ipRules[*].value 匹配项,仅当至少未找到一个匹配项时,才应用 effectTypeThis sample rule checks for any matches of ipRules[*].value to 10.0.4.1 and applies the effectType only if it doesn't find at least one match:

"policyRule": {
    "if": {
        "allOf": [
            {
                "field": "Microsoft.Storage/storageAccounts/networkAcls.ipRules",
                "exists": "true"
            },
            {
                "field": "Microsoft.Storage/storageAccounts/networkAcls.ipRules[*].value",
                "notEquals": "10.0.4.1"
            }
        ]
    },
    "then": {
        "effect": "[parameters('effectType')]"
    }
}

有关详细信息,请参阅评估 [*] 别名For more information, see evaluating the [*] alias.

计划Initiatives

使用计划可组合多个相关策略定义,以简化分配和管理,因为可将组作为单个项使用。Initiatives enable you to group several related policy definitions to simplify assignments and management because you work with a group as a single item. 例如,可以将相关标记策略组合为单个计划。For example, you can group related tagging policy definitions into a single initiative. 将应用计划,而非单独分配每个策略。Rather than assigning each policy individually, you apply the initiative.

下面的示例演示如何创建用于处理 costCenterproductName 这两个标记的计划。The following example illustrates how to create an initiative for handling two tags: costCenter and productName. 它使用两个内置策略来应用默认标记值。It uses two built-in policies to apply the default tag value.

{
    "properties": {
        "displayName": "Billing Tags Policy",
        "policyType": "Custom",
        "description": "Specify cost Center tag and product name tag",
        "parameters": {
            "costCenterValue": {
                "type": "String",
                "metadata": {
                    "description": "required value for Cost Center tag"
                }
            },
            "productNameValue": {
                "type": "String",
                "metadata": {
                    "description": "required value for product Name tag"
                }
            }
        },
        "policyDefinitions": [{
                "policyDefinitionId": "/providers/Microsoft.Authorization/policyDefinitions/1e30110a-5ceb-460c-a204-c1c3969c6d62",
                "parameters": {
                    "tagName": {
                        "value": "costCenter"
                    },
                    "tagValue": {
                        "value": "[parameters('costCenterValue')]"
                    }
                }
            },
            {
                "policyDefinitionId": "/providers/Microsoft.Authorization/policyDefinitions/2a0e14a6-b0a6-4fab-991a-187a4f81c498",
                "parameters": {
                    "tagName": {
                        "value": "costCenter"
                    },
                    "tagValue": {
                        "value": "[parameters('costCenterValue')]"
                    }
                }
            },
            {
                "policyDefinitionId": "/providers/Microsoft.Authorization/policyDefinitions/1e30110a-5ceb-460c-a204-c1c3969c6d62",
                "parameters": {
                    "tagName": {
                        "value": "productName"
                    },
                    "tagValue": {
                        "value": "[parameters('productNameValue')]"
                    }
                }
            },
            {
                "policyDefinitionId": "/providers/Microsoft.Authorization/policyDefinitions/2a0e14a6-b0a6-4fab-991a-187a4f81c498",
                "parameters": {
                    "tagName": {
                        "value": "productName"
                    },
                    "tagValue": {
                        "value": "[parameters('productNameValue')]"
                    }
                }
            }
        ]
    },
    "id": "/subscriptions/<subscription-id>/providers/Microsoft.Authorization/policySetDefinitions/billingTagsPolicy",
    "type": "Microsoft.Authorization/policySetDefinitions",
    "name": "billingTagsPolicy"
}

后续步骤Next steps