简体   繁体   中英

Azure custom policy for require tags for resource groups with valid value set using terraform

I am looking for terraform code for the below requirement.

I want to have 2 tags for example, We can increase the tags later

Environment = [DEV,STG,PRD]

AskID = [123,ABC,234]

I want this policy to be applied for multiple subscriptions.

And similarly can we have same type of policy for require tags for resources with valid value set for multiple resources in resource groups.

Also the tag values should be case sensitive. Can we get help on this

Here's an example of how you can create a policy that requires the "Environment" and tags on resource groups, and specifies a list of allowed values for each tag:

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

}

upon running plan

terraform plan

在此处输入图像描述

NOTE: there will be access issue while running the code due to privileged access "User is not authorized to create subscriptions on this enrollment account."

refer this tutorial of # Using Terraform and Azure Policies Manage Tag governance from @kunal.parkar886 for azure policy creation .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM