Home > other >  how we can use inbuilt policy's in azure via terraform , i am finding code for only custom poli
how we can use inbuilt policy's in azure via terraform , i am finding code for only custom poli

Time:08-25

provider "azurerm" {
  skip_provider_registration = "true"

  version = "3.0.1"

  features {}
}


resource "azurerm_resource_policy_assignment" "auditvms" { 
  name = "audit-vm-manageddisks"

  resource_id = "/subscriptions/sub_id/resourceGroups/rg-prod-hub"

  policy_definition_id = "/providers/Microsoft.Authorization/policyDefinitions/06a78e20-9358-41c9-923c-fb736d382a4d"

  description = "Shows all virtual machines not using managed disks"

  display_name = "Audit VMs without managed disks assignment" 
}
Error : │ Error: ID cannot be a Resource Group ID
│ 
│   with azurerm_resource_policy_assignment.auditvms,
│   on main.tf line 11, in resource "azurerm_resource_policy_assignment" "auditvms":
│   11:  resource_id = "/subscriptions/sub_id/resourceGroups/rg-prod-hub"

CodePudding user response:

Here resource_id is the ID of the Resource or its scope, where this has to be actually applied. This forces a new Resource Policy Assignment to be created on that resource.

I have tried to reproduce the same . Have given resourcegroup Id for resource Id and got the same error: Error: ID cannot be a Resource Group ID


enter image description here


  • So if you are trying to set policy for resource group ( as you have resourceid looks like for resource group), Then for a Resource Group use the azurerm_resource_group_policy_assignment .

Example:

  • If your resource is Subscription use the azurerm_subscription_policy_assignment as resource .

In your case if its for resource group ,Replace resource with resource_group (even replace resource_id with resource_group_id)

resource "azurerm_resource_group_policy_assignment" "auditvms" { 
  name = "."
  resource_group_id = "/subscriptions/sub_id/resourceGroups/rg-prod-hub"
  ……
}
  • In case of particular resource , then resource_id must be the that particular azure resource id:

For example :If resource is Kubernetes cluser as snippet from azurerm-resource-policy-assignment | https://shisho.dev

resource "azurerm_resource_policy_assignment" "policy_assignment" {
  name                 = "labeled-pods"
  resource_id          = data.azurerm_kubernetes_cluster.aks_cluster.id
  policy_definition_id = azurerm_policy_definition.policy.id
 }

Reference: azurerm_resource_group_policy_assignment | Resources | hashicorp/azurerm | Terraform Registry

  • Related