Posts Terraform - Ignoring tags applied by Azure Policy
Post
Cancel

Terraform - Ignoring tags applied by Azure Policy

Tags can be added automatically by Azure Policy. For instance, you might have an Azure Policy that adds a “Cost Center” tag with a certain value based on what Subscription or what Resource Group a resource is deployed into.

Because Terraform tracks the state of resources it deploys, it will identify the additional tag as a change and will remove it. This likely isn’t what you want and, depending on your Azure Policy configuration, it might just go and re-instate the tag.

To prevent this war of Azure Policy vs Terraform, you can tell Terraform to ignore changes to certain aspects of a resource. For instance, here’s a Resource Group being create where we expect the “CostCenter” tag to be added by Azure Policy, so we tell Terraform to ignore it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
resource "azurerm_resource_group" "network_rg" {
  name     = "rg-${var.regionAbbr}-network"
  location = var.location

  tags = {
      environment = var.envTag
  }  

  lifecycle {
    ignore_changes = [
      tags["CostCenter"]
    ]  
  }
}

I’ve seen examples where this has been written as tags.CostCenter but this didn’t work for me and the documentation suggests using the format above. I think the tag.CostCenter format may be either specific to another provider (perhaps AWS) or is for an older version of Terraform.

This post is licensed under CC BY 4.0 by the author.