You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Terraform的azurerm_policy_set_definition中内嵌定义Azure策略?

Azure Policy Initiative内嵌自定义策略的可行性与实现方式

可行性确认

完全可行。Azure Policy Initiative(策略集定义)支持直接内嵌自定义策略规则,无需单独创建azurerm_policy_definition资源。

内嵌实现的Terraform代码示例

直接在azurerm_policy_set_definition资源中使用policy_definition块(替代原有的policy_definition_reference)来内嵌策略规则,贴合你原有的管理组级别场景的示例代码如下:

data "azurerm_management_group" "parent-mg" {
  # 此处填写你的管理组ID或显示名
}

variable "policyset_definition_category" {
  type        = string
  description = "Policy Initiative category"
  default     = "Location"
}

resource "azurerm_policy_set_definition" "custom_geo_policy_set" {
  name                = "custom_geo_policy_set"
  policy_type         = "Custom"
  display_name        = "Custom Geo-Location Governance"
  description         = "Contains common Geo-Location Governance policies"
  management_group_id = data.azurerm_management_group.parent-mg.id

  metadata = <<METADATA
  {
    "category": "${var.policyset_definition_category}"
  }
METADATA

  # 内嵌自定义策略,无需单独定义azurerm_policy_definition
  policy_definition {
    name                = "only-deploy-in-eastus"
    policy_type         = "Custom"
    mode                = "All"
    display_name        = "only-deploy-in-eastus"
    description         = "Deny resources not deployed in eastus"

    policy_rule = <<POLICY_RULE
    {
      "if": {
        "not": {
          "field": "location",
          "equals": "eastus"
        }
      },
      "then": {
        "effect": "Deny"
      }
    }
POLICY_RULE
  }
}

两种实现方式的适用场景

  • 单独定义策略+引用(原方式):适合需要在多个Policy Initiative中复用该策略,或者需要单独管理策略的版本、权限、独立分配的场景,策略作为独立资源存在,灵活性更高。
  • 内嵌策略(新方式):适合该策略仅为当前Policy Initiative专用,无需复用,希望简化资源层级、减少单独资源管理成本的场景,策略与initiative绑定,结构更紧凑。

内容的提问来源于stack exchange,提问作者One Developer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 09:25:38