In terraform, Avoid recreating any resources if the vm has tag with specific key

122 Views Asked by At
  1. Assume a terraform script, where it has instance and volume created.
  2. After a day or two, from portal we have deleted a volume.
  3. After a week, from terraform I would like to update the tags, instance type of that vm.

So above 3rd step should not recreate any volume or should not delete any existing tags attached to vm

1

There are 1 best solutions below

2
Helder Sepulveda On

For those cases you can use ignore_changes and provide a list of anything you want to ignore when changed after created... Most people will advise against this and I agree, you should use this ignore as a last resource, your infrastructure changes should be ALL in terraform not manually in the portal or any other way, mixing manual changes with terraform is a recipe for disaster

resource "aws_instance" "hummingbot" {
  ami                  = data.aws_ami.foo.id
  instance_type        = "t2.medium"
  availability_zone    = "us-east-1a"
  iam_instance_profile = aws_iam_instance_profile.abc.name

  root_block_device {
    volume_type           = "gp3"
    volume_size           = "64"
    delete_on_termination = true
  }

  ebs_block_device {
    device_name           = "/dev/sdg"
    volume_type           = "gp2"
    volume_size           = "32"
    delete_on_termination = false
  }

  tags = {
    Terraformed = "true"
    Name        = "hummingbot"
  }

  lifecycle {
    ignore_changes = [root_block_device, ebs_block_device, tags["tag_name"]]
  }
}

For the tags see what your options is tags["tag_name"] what you are asking "not delete any existing tags" you will have to specify what tags you want to ignore, I have not seen any option for wildcards there, there are requests for it:

but not much traction there


Another way to ignore tags globally is using the ignore_tags Configuration Block on the AWS provider, you have a bit more flexible option there if it applies to multiple resources

provider "aws" {
  ignore_tags {
    keys = ["TagKey1"]
  }
}

https://registry.terraform.io/providers/hashicorp/aws/latest/docs#ignore_tags-configuration-block

The ignore_tags configuration block supports the following arguments:

keys - (Optional) List of exact resource tag keys to ignore across all resources handled by this provider.

key_prefixes - (Optional) List of resource tag key prefixes to ignore across all resources handled by this provider.