Azure Policy 定义结构Azure Policy definition structure

Azure Policy 可为资源建立多种约定。Azure Policy establishes conventions for resources. 策略定义描述资源符合性条件,以及在符合某个条件时要采取的效果。Policy definitions describe resource compliance conditions and the effect to take if a condition is met. 条件会将资源属性字段与所需值进行比较。A condition compares a resource property field to a required value. 资源属性字段是通过别名进行访问的。Resource property fields are accessed by using aliases. 资源属性字段可为单值字段,也可为包含多值的数组A resource property field is either a single-valued field or an array of multiple values. 数组上的条件评估会有所不同。Condition evaluation is different on arrays. 如需了解更多,请参见条件Learn more about conditions.

通过定义约定,可以控制成本并更轻松地管理资源。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 resources have a particular tag. 策略分配由子资源继承。Policy assignments are inherited by child resources. 如果将策略分配应用到资源组,则会将其应用到该资源组中的所有资源。If a policy assignment is applied to a resource group, it's applicable to all the resources in that resource group.

有关策略定义架构的描述,请参阅此处:https://schema.management.azure.com/schemas/2019-09-01/policyDefinition.jsonThe policy definition schema is found here: https://schema.management.azure.com/schemas/2019-09-01/policyDefinition.json

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

  • 显示名称display name
  • descriptiondescription
  • modemode
  • metadatametadata
  • parametersparameters
  • 策略规则policy rule
    • 逻辑评估logical evaluation
    • 效果effect

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

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

Azure Policy 内置和模式位于 Azure Policy 示例Azure Policy built-ins and patterns are at Azure Policy samples.

显示名称和说明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.

备注

在创建或更新策略定义期间,“ID”、“类型”和“名称”是由 JSON 外部属性定义,不需要在 JSON 文件中进行定义。During the creation or updating of a policy definition, id, type, and name are defined by properties external to the JSON and aren't necessary in the JSON file. 通过 SDK 获取策略定义将返回“ID”、“类型”和“名称”属性作为 JSON 的一部分,但每个属性都是与策略定义相关的只读信息。Fetching the policy definition via SDK returns the id, type, and name properties as part of the JSON, but each are read-only information related to the policy definition.

类型Type

尽管无法设置 type 属性,但 SDK 返回了三个值且在门户中可见:While the type property can't be set, there are three values that are returned by SDK and visible in the portal:

  • Builtin:这些策略定义由 Microsoft 提供并维护。Builtin: These policy definitions are provided and maintained by Microsoft.
  • Custom:客户创建的所有策略定义都具有此值。Custom: All policy definitions created by customers have this value.
  • Static:表示具有 Microsoft“所有权”的合规性策略定义。Static: Indicates a Regulatory Compliance policy definition with Microsoft Ownership. 这些策略定义的合规性结果是 Microsoft 基础结构上的第三方审核结果。The compliance results for these policy definitions are the results of third-party audits on Microsoft infrastructure. 在 Azure 门户中,此值有时显示为“Microsoft 托管”。In the Azure portal, this value is sometimes displayed as Microsoft managed. 有关详细信息,请参阅云中责任分担For more information, see Shared responsibility in the cloud.

模式Mode

“模式”的配置要取决于策略是针对 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 are evaluated for a policy definition. 支持的模式包括:The supported modes are:

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

例如,资源 Microsoft.Network/routeTables 支持标记和位置,并在这两种模式中进行评估。For example, resource Microsoft.Network/routeTables supports tags and location and is evaluated in both modes. 但是,无法标记资源 Microsoft.Network/routeTables/routes,也不会在 Indexed 模式下对其进行评估。However, resource Microsoft.Network/routeTables/routes can't be tagged and isn't evaluated in Indexed mode.

大多数情况下,建议将“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 and subscriptions. 策略定义若在资源组或订阅上强制执行位置或标记,则应将“模式”设为 all,并明确以 Microsoft.Resources/subscriptions/resourceGroupsMicrosoft.Resources/subscriptions 类型为目标。Policy definitions that enforce location or tags on a resource group or subscription should set mode to all and specifically target the Microsoft.Resources/subscriptions/resourceGroups or Microsoft.Resources/subscriptions type. 有关示例,请参阅模式:标记 - 示例 #1For an example, see Pattern: Tags - Sample #1. 有关支持标记的资源列表,请参阅有关 Azure 资源的标记支持For a list of resources that support tags, see Tag support for Azure resources.

资源提供程序模式(预览版)Resource Provider modes (preview)

在预览版期间,目前支持以下资源提供程序模式:The following Resource Provider modes are currently supported during preview:

  • Microsoft.Kubernetes.Data,用于在 Azure 上或外部管理 Kubernetes 群集。Microsoft.Kubernetes.Data for managing your Kubernetes clusters on or off Azure. 使用该资源提供程序模式的定义使用效果“审核”、“拒绝”和“已禁用” 。Definitions using this Resource Provider mode use effects audit, deny, and disabled.
  • Microsoft.KeyVault.Data,用于管理 Azure Key Vault 中的保管库和证书。Microsoft.KeyVault.Data for managing vaults and certificates in Azure Key Vault.

备注

资源提供程序模式仅支持内置策略定义,且在预览版期间暂不支持计划。Resource Provider modes only support built-in policy definitions and don't support initiatives while in preview.

MetadataMetadata

metadata 可选属性用于存储关于策略定义的信息。The optional metadata property stores information about the policy definition. 客户可在 metadata 中定义对其组织有用的任何属性和值。Customers can define any properties and values useful to their organization in metadata. 但是,Azure Policy 和内置项使用一些常见属性。However, there are some common properties used by Azure Policy and in built-ins.

常见元数据属性Common metadata properties

  • version(字符串):跟踪有关策略定义的内容版本的详细信息。version (string): Tracks details about the version of the contents of a policy definition.
  • category(字符串):确定在 Azure 门户中的哪个类别下显示策略定义。category (string): Determines under which category in Azure portal the policy definition is displayed.
  • preview(布尔值):如果策略定义为“预览”,则为 True 或 false 标志。preview (boolean): True or false flag for if the policy definition is preview.
  • deprecated(布尔值):如果策略定义被标记为“已弃用”,则为 True 或 false 标志。deprecated (boolean): True or false flag for if the policy definition has been marked as deprecated.

备注

Azure Policy 服务会使用 versionpreviewdeprecated 属性,将变更级别传达给内置策略定义或计划和状态。The Azure Policy service uses version, preview, and deprecated properties to convey level of change to a built-in policy definition or initiative and state. version 的格式为:{Major}.{Minor}.{Patch}The format of version is: {Major}.{Minor}.{Patch}. 特定状态(例如“弃用”或“预览版”)会附加至 version 属性,或另一个属性中附加为“布尔值”。Specific states, such as deprecated or preview, are appended to the version property or in another property as a boolean. 有关 Azure Policy 内置项版本控制方式的详细信息,请参阅内置项版本控制For more information about the way Azure Policy versions built-ins, see Built-in versioning.

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.

备注

参数可以添加到现有和已分配的定义。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",
            "chinanorth",
            "chinaeast"
        ]
    }
}

使用参数值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 可以是受支持的资源类型,也可以是允许值。strongType can be a supported resource type or an allowed value. 若要确定资源类型是否对 strongType有效,请使用 Get-AzResourceProviderTo determine if a resource type is valid for strongType, use Get-AzResourceProvider. 资源类型“StrongType”的格式为 <Resource Provider>/<Resource Type>The format for a resource type strongType is <Resource Provider>/<Resource Type>. 例如 Microsoft.Network/virtualNetworks/subnetsFor example, Microsoft.Network/virtualNetworks/subnets.

支持部分不是由 Get-AzResourceProvider 返回的资源类型。Some resource types not returned by Get-AzResourceProvider are supported. 这些资源类型包括:Those are:

  • Microsoft.RecoveryServices/vaults/backupPolicies

strongType 的非资源类型允许值包括:The non resource type allowed values for strongType are:

  • location
  • resourceTypes
  • storageSkus
  • vmSKUs
  • existingResourceGroups

定义位置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 subscription.

策略规则Policy rule

策略规则包括 IfThen 块。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"
        }
    ]
},

条件Conditions

条件用于评估 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": "dateValue" | "less": "stringValue" | "less": intValue
  • "lessOrEquals": "dateValue" | "lessOrEquals": "stringValue" | "lessOrEquals": intValue
  • "greater": "dateValue" | "greater": "stringValue" | "greater": intValue
  • "greaterOrEquals": "dateValue" | "greaterOrEquals": "stringValue" | "greaterOrEquals": intValue
  • "exists": "bool"

对于“less”、“lessOrEquals”、“greater”和“greaterOrEquals”,如果属性类型与条件类型不匹配,则会引发错误。For less, lessOrEquals, greater, and greaterOrEquals, if the property type doesn't match the condition type, an error is thrown. 字符串比较是使用 InvariantCultureIgnoreCase 进行。String comparisons are made using InvariantCultureIgnoreCase.

使用 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 区分大小写,但用于评估 stringValue 的所有其他条件都不区分大小写 。While match and notMatch are case-sensitive, all other conditions that evaluate a stringValue are case-insensitive. “matchInsensitively”和“notMatchInsensitively”中提供了不区分大小写的替代方案 。Case-insensitive alternatives are available in matchInsensitively and notMatchInsensitively.

在 [*] 别名数组字段值中,数组中的每个元素都会使用元素间的逻辑 and 进行单独计算。In an [*] alias array field value, each element in the array is evaluated individually with logical and between elements. 有关详细信息,请参阅评估 [*] 别名For more information, see Evaluating the [*] alias.

字段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
    • 对于不限位置的资源,请使用 globalUse global for resources that are location agnostic.
  • 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.

备注

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. 如果该标记不存在,系统会使用“修改”效果,通过 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"
            ]
        }
    }
}

Value

也可使用 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.

警告

如果模板函数的结果是一个错误,则策略评估会失败。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. 使用 DoNotEnforce 的 enforcementMode,以防止在测试和验证新策略定义期间,由于新的或更新的资源评估失败而受到影响。Use enforcementMode of DoNotEnforce to prevent impact of a failed evaluation on new or updated resources while testing and validating a new policy definition.

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 结尾的任何资源组中类型不为 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 来检查多个嵌套函数的结果是否等于 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() 将名称的前三个字符与 abc 进行比较。The example policy rule above uses substring() to compare the first three characters of name to abc. 如果名称少于三个字符,substring() 函数会导致错误。If name is shorter than three characters, the substring() function results in an error. 此错误会导致策略变为“拒绝”效果。This error causes the policy to become a deny effect.

相反地,请改用 if() 函数来检查名称的前三个字符是否等于 abc,不允许名称少于三个字符,这会导致错误: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() 会先检查名称的长度,然后尝试在少于三个字符的值上获取 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. 如果名称太短,则会改为返回“不是以 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

计算资源有效负载中陈列有多少成员符合条件表达式的条件,可以使用 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 [*] alias array member for a condition expression and sums the true results, which is then compared to the expression operator. “Count”表达式最多可添加到单个 policyRule 定义 3 次 。Count expressions may be added up to three times to a single policyRule definition.

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. 如果未提供此属性,具有“字段”路径的所有数组成员将评估为 true。If this property isn't 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 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 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()

备注

在 deployIfNotExists 策略定义中,仍可在其模板部署的 details.deployment.properties.template 部分中使用这些函数。These functions are still available within the details.deployment.properties.template portion of the template deployment in a deployIfNotExists policy definition.

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

  • utcNow() - 与 ARM 模板不同,该属性可以在 defaultValue 之外使用。utcNow() - Unlike an ARM template, this property 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'

以下函数仅适用于策略规则:The following functions are only available in policy rules:

  • 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
  • field(fieldName)
    • fieldName:[必需] 字符串 - 要检索的字段名称fieldName: [Required] string - Name of the field to retrieve
    • 从 If 条件计算的资源中返回该字段的值Returns the value of that field from the resource that is being evaluated by the If condition
    • 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.
  • requestContext().apiVersion
    • 返回已触发策略评估的请求的 API 版本(示例:2019-09-01)。Returns the API version of the request that triggered policy evaluation (example: 2019-09-01). 该值是 PUT/PATCH 请求中用于对资源创建/更新进行评估的 API 版本。This value is the API version that was used in the PUT/PATCH request for evaluations on resource creation/update. 在对现有资源进行符合性评估时,将会一律使用最新的 API 版本。The latest API version is always used during compliance evaluation on existing resources.

策略函数示例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:

  • 适用于 Visual Studio Code 的 Azure Policy 扩展(推荐)Azure Policy extension for Visual Studio Code (recommended)

    使用适用于 Visual Studio Code 的 Azure Policy 扩展来查看和发现资源属性的别名。Use the Azure Policy extension for Visual Studio Code to view and discover aliases for resource properties.

    适用于 Visual Studio Code 的 Azure Policy 扩展

  • Azure Resource GraphAzure Resource Graph

    使用 project 运算符来显示资源的别名。Use the project operator to display the alias of a resource.

    Resources
    | where type=~'microsoft.storage/storageaccounts'
    | limit 1
    | project aliases
    
    az graph query -q "Resources | where type=~'microsoft.storage/storageaccounts' | limit 1 | project aliases"
    
    Search-AzGraph -Query "Resources | where type=~'microsoft.storage/storageaccounts' | limit 1 | project aliases"
    
  • 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[*]

“正常”别名会将该字段表示为单个值。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. 此方法可以比较“如果没有”、“如果任何”和“如果所有”方案的元素属性。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[*],一个示例会验证每个操作是否为“拒绝”,但不用担心存在多少个规则或 IP 值是什么。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. 此示例规则会检查 ipRules[*].value 是否符合 10.0.4.1,并在没有找到至少一个匹配项时才应用 effectType:This 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.

后续步骤Next steps