In this lecture, we will take a look at the Terraform taint and untaint command.
There would be cases when a resource creation fails
when we run Terraform apply.
Let's take the same example as before
where we use a local provisioner to store the public IP address
of the EC2 instance in a file.
However, when we try to apply the changes,
the resource creation failed
because the part specified in the command of the local exit provisioner is invalid.
When this happens and a resource creation fails for any reason,
Terraform marks the resource as tainted.
This can be seen when we run the Terraform plan command again.
The resource called web server is tainted,
and as a result, Terraform will attempt to recreate it during the subsequent apply.
In this example,
the step that failed was the command executed by the local exit provisioner.
The EC2 instance itself was successfully provisioned.
In spite of this, Terraform will attempt to recreate the entire resource
because it was marked tainted.
Now there would be cases when we want to force a particular resource to be recreated.
For example, consider a case where manual changes were made to an AWS instance
which is managed by Terraform,
such as changing the version of nginx running on it by manual methods.
To reword this, we can either destroy the resource
using the command Terraform destroy, and then run apply again,
or the better way would be to taint the resource
using the Terraform taint command like this.
When we run Terraform plan next,
we will see that the resource is set to be recreated.
To undo a taint that was applied for a specific resource,
use the Terraform untaint command like this.
This resource will not be recreated now during a subsequent Terraform apply.