In this article, we explain how to use Terraform’s taint and untaint commands to manage resource recreation effectively. These commands are especially useful when a resource fails during creation or when manual changes occur that necessitate a fresh deployment.Documentation Index
Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
Use this file to discover all available pages before exploring further.
Overview
Terraform marks a resource as tainted when it encounters errors during creation, such as a failed provisioner command. A tainted resource is scheduled for replacement during the next apply. Conversely, you can use the untaint command to clear this status and prevent a replacement.Using taint and untaint commands allows for efficient control of resource lifecycle without a complete destroy and reapply cycle.
Scenario: Tainted Resource due to Provisioner Failure
Consider a scenario where an AWS EC2 instance is provisioned using a local provisioner to store its public IP address in a file. If the provisioner command fails—perhaps because the file path is incorrect—the resource is marked as tainted, triggering its replacement on the next apply.Resource Definition Example
Applying the Configuration
When executing the apply command, you might see output indicating that the provisioner has failed:Verifying the Tainted Resource
Running the terraform plan command confirms that the tainted resource is scheduled for replacement:Double-check your resource configuration and provisioner commands to avoid unintentional resource replacement.
Forcing a Resource Rebuild
There are situations where you might want to deliberately force a resource rebuild. For example, if manual changes—such as updating the Nginx version—were made on an AWS instance, you can efficiently trigger the recreation of that resource without performing a full destroy and apply cycle.Tainting the Resource
Run the following command to mark the resource as tainted:Confirming the Change with Terraform Plan
After tainting, a terraform plan will show that the resource is scheduled for replacement:Reversing Taint: Using the Untaint Command
If you later decide that a resource should not be replaced, you can remove its tainted state by using the untaint command. This prevents Terraform from destroying and recreating the resource during the next apply.Summary Table
| Command | Action | Description |
|---|---|---|
| terraform taint | Mark resource as tainted | Forces the resource to be replaced on the next apply |
| terraform untaint | Remove taint from resource | Prevents resource replacement during the next apply |
| terraform plan | Verify resource replacement plan | Confirms which resources are marked for replacement |
| terraform apply | Apply configuration changes | Executes resource creation and replacement operations |