Home > Enterprise >  Terraform - Azure Resource Group: Error: ID cannot be a Resource Group ID
Terraform - Azure Resource Group: Error: ID cannot be a Resource Group ID

Time:09-21

I am currently migrating our cloud infrastructure over to Terraform. I am trying to assign a policy to a resource group. However it fails with an error

│ Error: ID cannot be a Resource Group ID

│ with azurerm_resource_policy_assignment.example, on main.tf line 50, in resource a zurerm_resource_policy_assignment" "example":

│ 50: resource_id = azurerm_resource_group.example.id

# Configure the Microsoft Azure provider
provider "azurerm" {
  features {}
}

data "azurerm_subscription" "primary" {
}

data "azurerm_client_config" "example" {
}

# Define Policy
resource "azurerm_policy_definition" "example" {
  display_name = "only-deploy-in-westus"
  name        = "only-deploy-in-westus"
  policy_type = "Custom"
  mode        = "All"

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

# Create a Resource Group if it doesn’t exist
resource "azurerm_resource_group" "example" {
  name     = "example-resources"
  location = "West US"
}

# Assign Permission
resource "azurerm_role_assignment" "example" {
  scope                = azurerm_resource_group.example.id
  role_definition_name = "Reader"
  principal_id         = data.azurerm_client_config.example.object_id
}

# Assign Policy
resource "azurerm_resource_policy_assignment" "example" {
  name                 = "example-policy-assignment"
  resource_id          = azurerm_resource_group.example.id
  policy_definition_id = azurerm_policy_definition.example.id
}

CodePudding user response:

It should be:

resource_group_id = azurerm_resource_group.example.id

rather then

resource_id = azurerm_resource_group.example.id

CodePudding user response:

In order to assign a policy to a resource group you cannot use azurerm_resource_policy_assignment but would need to use azurerm_resource_group_policy_assignment.

resource "azurerm_resource_group_policy_assignment" "example" {
  name                 = "example"
  resource_group_id    = azurerm_resource_group.example.id
  policy_definition_id = azurerm_policy_definition.example.id
}

Reference: https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs/resources/resource_group_policy_assignment

  • Related