Terraform Taint

Sometimes, resources in your infrastructure might become corrupted, require replacement, or need to be updated due to external changes. The terraform taint command allows you to mark a resource as "tainted," ensuring it will be destroyed and recreated during the next terraform apply.

Why Use terraform taint?

  • To force the recreation of a specific resource.
  • To address issues with a resource without modifying the configuration files.
  • To trigger updates or repairs to a resource managed by Terraform.

How to Use It?

  • To mark a resource as tainted: Run terraform taint <resource_name>. Replace <resource_name> with the name of the resource you want to taint.
  • To undo the taint: Use terraform untaint <resource_name> to remove the taint mark.

Example: Tainting a Resource

Suppose you have the following resource in your main.tf file:

resource "aws_instance" "example" {
  ami           = "ami-123456"
  instance_type = "t2.micro"
}

To force the recreation of the EC2 instance, run:

terraform taint aws_instance.example

The output will confirm the resource is marked as tainted:

Resource instance aws_instance.example has been marked as tainted.

Now, during the next terraform apply, Terraform will destroy the old instance and create a new one:

Terraform will perform the following actions:

  # aws_instance.example will be replaced
  -/+ resource "aws_instance" "example" {
      ~ ami           = "ami-123456" -> "ami-654321"
      ~ instance_type = "t2.micro" -> "t2.medium"
      ...
    }

Plan: 1 to add, 0 to change, 1 to destroy.

Use Case

Imagine you’ve updated the AMI ID for an EC2 instance in your configuration, but Terraform doesn’t detect the change because it sees the resource as already existing. By using terraform taint, you can explicitly mark the resource for replacement to ensure the update is applied.

Conclusion

The terraform taint command provides a quick and efficient way to manage resource replacement. Whether fixing issues or triggering updates, it ensures your infrastructure remains reliable and up to date.