Scenario: Resource Creation Failure
Imagine you runterraform apply and a resource fails to create. In the example below, a local provisioner is used to store the public IP of an EC2 instance in a file. If the resource creation fails—for example, because the file path specified in the provisioner command is incorrect—Terraform marks the resource as tainted.
Below is the HCL configuration for the EC2 instance with a local provisioner:
terraform plan again will signal that this tainted resource will be replaced:
Even though the EC2 instance itself was successfully provisioned, the failure in the local-exec provisioner ensures that the entire resource is flagged for recreation.
Forcing Resource Recreation
There may be situations where you make manual changes to a resource (for example, updating the Nginx version on an AWS instance) that require Terraform to recreate the resource. Instead of destroying the resource manually and running apply again, you can mark the resource as tainted using theterraform taint command.
The following example demonstrates how Terraform marks the resource for replacement:
Undoing a Taint
If you later decide against recreating the resource, you can remove its tainted status using theterraform untaint command. This prevents the resource from being recreated during the next apply:
Using the taint and untaint commands gives you granular control over your infrastructure. This avoids unnecessary destruction and creation of resources, making your management process more efficient.
By understanding and utilizing these commands, you can maintain consistency and automation in your infrastructure management—all without manually destroying and recreating resources.