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
By leveraging the taint and untaint commands, you can manage resource lifecycle events efficiently, ensuring that your infrastructure remains consistent with your desired state.
For further details, explore the Terraform Documentation.