0
0
TerraformHow-ToBeginner · 3 min read

How to Use Terraform Taint: Mark Resources for Recreation

Use the terraform taint command followed by the resource address to mark a resource as tainted. This forces Terraform to destroy and recreate that resource on the next terraform apply. It helps fix resources that are broken or need replacement without changing configuration.
📐

Syntax

The basic syntax of terraform taint is simple:

  • terraform taint [options] RESOURCE_ADDRESS

Here, RESOURCE_ADDRESS is the name of the resource you want to mark as tainted, such as aws_instance.example. Options can include flags like -allow-missing to avoid errors if the resource is missing.

bash
terraform taint [options] RESOURCE_ADDRESS
💻

Example

This example shows how to taint an AWS EC2 instance resource named aws_instance.web. After marking it tainted, running terraform apply will destroy and recreate the instance.

bash
terraform taint aws_instance.web
terraform apply
Output
Resource instance aws_instance.web has been marked as tainted. An execution plan has been generated and is shown below. Resource actions are indicated with the following symbols: - destroy + create Terraform will perform the following actions: # aws_instance.web must be replaced - resource "aws_instance" "web" { ... } + resource "aws_instance" "web" { ... } Plan: 1 to add, 0 to change, 1 to destroy. Do you want to perform these actions? (yes/no): yes aws_instance.web: Destroying... [id=i-1234567890abcdef0] aws_instance.web: Destruction complete after 30s aws_instance.web: Creating... aws_instance.web: Creation complete after 45s [id=i-0987654321fedcba0]
⚠️

Common Pitfalls

Common mistakes when using terraform taint include:

  • Trying to taint a resource that does not exist in the state, causing an error.
  • Forgetting to run terraform apply after tainting, so no changes happen.
  • Using taint on resources managed outside Terraform, which can cause drift.

To avoid errors when the resource might be missing, use the -allow-missing flag.

bash
terraform taint aws_instance.missing_resource
# Error: No resource found

terraform taint -allow-missing aws_instance.missing_resource
# No error, continues safely
📊

Quick Reference

CommandDescription
terraform taint RESOURCE_ADDRESSMark a resource as tainted to force recreation
terraform taint -allow-missing RESOURCE_ADDRESSTaint resource but do not error if missing
terraform applyApply changes including recreating tainted resources
terraform untaint RESOURCE_ADDRESSRemove taint from a resource

Key Takeaways

Use terraform taint RESOURCE_ADDRESS to mark a resource for recreation.
Run terraform apply after tainting to recreate the resource.
Use -allow-missing to avoid errors if the resource is not found.
Tainting does not change configuration, only forces replacement on next apply.
Avoid tainting resources managed outside Terraform to prevent state drift.