Terraform taint

terraform: tainting a resource to force recreation

Published: Tuesday, 20 July 2021
By:
  • Jurn Ho

Terraform Taint

Marking a resource as tainted will recreate the resource next time terraform apply is run.

To taint a resource, first determine the resource address. Do this by using the show command:

$ terraform show -no-color

It will output all resources, and their terraform resource addresses.

...

# module.foo.aws_instance.bar:
resource "aws_instance" "bar" {

...

In the example output above, to taint the module.foo.aws_instance.bar resource, run

$ terraform taint module.foo.aws_instance.bar
Resource instance module.foo.aws_instance.bar has been marked as tainted.

An untaint command is also available.

The next time terraform apply is run it will determine changes as normal, but also replace tainted resources.

$ terraform apply

...

  # module.foo.aws_instance.bar is tainted, so must be replaced
-/+ resource "aws_instance" "bar" {

...

Do you want to perform these actions?
  Terraform will perform the actions described above.
  Only 'yes' will be accepted to approve.

...

terraform apply -replace

An alternative is to specify the resource to replace when running terraform apply

$ terraform apply -replace="module.dmz.aws_instance.dmz"

...

  # module.foo.aws_instance.bar will be replaced, as requested
-/+ resource "aws_instance" "bar" {

...

Do you want to perform these actions?
  Terraform will perform the actions described above.
  Only 'yes' will be accepted to approve.


References