Terraform – How to Untaint a Resource After Network Issue

redisterraform

I had applied a terraform to create a redis cluster.

Half way through, the application process failed with this error message:

Error: Error waiting for elasticache replication group (my-project) to be created: SerializationError: failed decoding Query response
    status code: 200, request id: 3d5a5394-20f0-4834-9e2a-9aff20cceecf
caused by: read tcp 192.168.86.116:53912->54.222.5.156:443: read: connection reset by peer

I know that I have successfully created the cluster because I can connect to the redis cluster with redis-cli.

However if I do a terraform apply again, terraform will say

module.my_project.aws_elasticache_replication_group.main[0] is tainted, so must be replaced

It is trying to destroy and recreate the resource, instead of the no action as I would have expected.

I have tried to import the resource into the state file to rectify the issue. However terraform throws an error:

Error: Resource already managed by Terraform

If the operation were successful in the first place, I would not see the tainted error message.

Is there any way I can recover from this problem? I want to avoid delete and then recreate the resource.

Ideally I hope I can untaint the resource in the state file so terraform will not try to destroy the newly created cluster.

Best Answer

Terraform marks the object as tainted because, due to the error, it cannot be sure that the object was left in a fully-functional state.

However, if you know (via out-of-band inspection) that the object was left in a suitable state, you can override Terraform's determination by using the terraform untaint command:

terraform untaint module.my_project.aws_elasticache_replication_group.main[0]

After this, Terraform will believe that the object is in a suitable state for further actions. Ideally, that will mean that a subsequent terraform plan would detect no changes to that instance at all. If the create was incomplete but can be repaired through an update, then the provider might produce a plan for an in-place update to match the configuration.