【问题标题】:Azure custom policy for require tags for resource groups with valid value set using terraform使用 terraform 为具有有效值集的资源组提供需要标记的 Azure 自定义策略
【发布时间】:2023-01-30 13:10:18
【问题描述】:

我正在寻找满足以下要求的地形代码。

例如我想有2个标签,我们可以稍后增加标签

环境 = [DEV、STG、PRD]

AskID = [123,ABC,234]

我希望将此策略应用于多个订阅。

同样,我们可以为资源组中的多个资源设置有效值的资源的 require 标签使用相同类型的策略。

标签值也应该区分大小写。我们能得到这方面的帮助吗

【问题讨论】:

    标签: azure terraform tags azure-policy


    【解决方案1】:

    下面是一个示例,说明如何创建需要资源组上的“环境”和标签的策略,并为每个标签指定允许值列表:

    data "azurerm_client_config" "current" {}
    provider "azurerm" {
        features {}
    }
    
    resource "azurerm_policy_definition" "example" {
      name         = "tags-on-resource-groups"
      policy_type  = "Custom"
      mode         = "All"
      display_name = "my-policy-definition"
    
      policy_rule = <<POLICY_RULE
      {
        "if": {
          "allOf": [
            {
              "field": "type",
              "equals": "Microsoft.Resources/subscriptions/resourceGroups"
            },
            {
              "not": {
                "field": "tags.Environment",
                "in": [
                  "DEV",
                  "STG",
                  "PRD"
                ]
              }
            },
            {
              "not": {
                "field": "tags.AskID",
                "in": [
                  "123",
                  "ABC",
                  "234"
                ]
              }
            }
          ]
        },
        "then": {
          "effect": "deny"
        }
      }
      POLICY_RULE
    }
    
    resource "azurerm_resource_group" "example" {
      name     = "**********"
      location = "West Europe"
    }
    
    data "azurerm_billing_enrollment_account_scope" "example" {
      billing_account_name    = "******"
      enrollment_account_name = "******"
    }
    resource "azurerm_subscription" "example" {
      subscription_name = "Subscription Name"
      billing_scope_id  = data.azurerm_billing_enrollment_account_scope.example.id
    }
    
    data "azurerm_policy_assignment" "example" {
      name                 = "tags-on-resource-groups"
      scope_id             = azurerm_subscription.example.id
    
    }
    

    根据运行计划

    terraform plan
    

    笔记: 由于特权访问“用户无权在此注册帐户上创建订阅”,因此在运行代码时会出现访问问题。

    请参阅来自 @kunal.parkar886 的 #Using Terraform and Azure Policies Manage Tag governance 教程,以获取 azure policy creation。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-11
      • 1970-01-01
      • 2022-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多