How to use Terraform Lifecycle to ignore tags in Azure

photo of man and woman looking at the sky

No, this is not a post about Terraforming Mars. To use the ignore_changes lifecycle event to ignore changes to tags in Azure resources in Terraform, you can add the “ignore_changes” block within the lifecycle block of the resource you want to ignore changes for.

For example, if you want to ignore changes to the tags of an Azure Virtual Machine resource, you can use the following configuration:

resource "azurerm_virtual_machine" "example" {

    name                  = "myvm"
    location              = azurerm_resource_group.example.location
    resource_group_name   = azurerm_resource_group.example.name
    network_interface_ids = [azurerm_network_interface.example.id]
    vm_size               = "Standard_DS1_v2"
    lifecycle {
        ignore_changes = [tags]
    }

This configuration will ignore any updates made to the tags of the virtual machine resource, Terraform will not make any changes to the resource tags and the tags will remain in the state they were in when the resource was created. Be sure you are using Terraform .12 or higher. Version .11 required quotes around the tags.

It’s worth noting that this configuration will ignore any changes to the tags, not only the changes to the values but also the changes to the keys of the tags.

You can also use the “ignore_changes” block to ignore changes to multiple attributes of a resource, for example, if you want to ignore changes to the tags and network_interface_ids of the same resource, you can use the following configuration:

resource "azurerm_virtual_machine" "example" {

    name                  = "myvm"
    location              = azurerm_resource_group.example.location
    resource_group_name   = azurerm_resource_group.example.name
    network_interface_ids = [azurerm_network_interface.example.id]
    vm_size               = "Standard_DS1_v2"
    lifecycle {
        ignore_changes = [tags,network_interface_ids]
    }
}

This will make Terraform ignore any updates to those attributes and leave them as they were at the time of the resource creation. This block is very handy when an Azure Policy continues to recreate a tag even though nothing changed on the tags when you run Terraform plan or apply. Terraform plan or apply will continue to report the tag changes made by Azure Policy as a “change” If you are checking for Azure Infrastructure changes, you do not want false positives all the time. I Hope you find this post useful.

Leave a Reply

%d bloggers like this: