Tainting & Targeting Resources
Imagine you’re managing your Lego city with Terraform. Sometimes, one building gets damaged and needs to be rebuilt, but you don’t want to tear down the whole city. Other times, you only want to upgrade a single block without touching the rest.
Terraform gives you two powerful tools for this: tainting (marking a resource for recreation) and targeting (applying changes to specific resources). These features give you precise control over your infrastructure lifecycle.
Key Concepts
1. Tainting Resources
- Definition: Mark a resource as “tainted,” forcing Terraform to destroy and recreate it on the next
apply. - Use case:
- Fix corrupted resources.
- Rebuild resources with updated configuration.
- Force recreation when drift occurs outside Terraform.
terraform taint aws_instance.web
2. Untainting Resources
- Definition: Remove the taint mark if you change your mind.
terraform untaint aws_instance.web
3. Targeting Resources
- Definition: Apply changes only to specific resources or modules.
- Use case:
- Deploy a single resource without affecting others.
- Test changes in isolation.
- Speed up deployments by focusing on critical resources.
terraform apply -target=aws_instance.web
4. Example Scenario
- You have a module deploying 5 EC2 instances.
- One instance (
aws_instance.web[2]) is corrupted. - Terraform destroys and recreates only that instance.
Later, you want to update just the database:
terraform apply -target=aws_db_instance.main
You run:
terraform taint aws_instance.web[2]
terraform apply
Hands‑On Lab / Demo
Lab: Tainting & Targeting in Action
- Apply changes → Terraform destroys and recreates the instance.
Target only the web instance:
terraform apply -target=aws_instance.web
Taint the resource:
terraform taint aws_instance.web
Create an EC2 instance:
resource "aws_instance" "web" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
}
Pro Tips & Best Practices
- Use taint for resources that must be rebuilt, not for routine updates.
- Use target sparingly - Terraform’s dependency graph may be skipped, leading to incomplete deployments.
- Always review the plan before applying taint or target.
- Document why taint/target was used - it’s often a temporary fix.
- Prefer full
applyfor production to ensure dependencies are respected.
Summary & Cheatsheet
- Taint: Force recreation of a resource.
- Untaint: Remove taint mark.
- Target: Apply changes to specific resources.
- Best practice: Use sparingly, document usage, prefer full applies for production.
Quick mnemonic: Taint = Rebuild, Target = Focus
The Hackers Notebook
Tainting and targeting give you surgical control over Terraform resources. They let you rebuild corrupted infrastructure or apply changes selectively, but they should be used carefully to avoid skipping dependencies.
