Terraform
Recreate resources overview
This topic provides an overview of how to recreate resources in Terraform.
Introduction
By default, Terraform retrieves the latest state of each existing object and compares it with the current configuration when you run the terraform apply
command. Terraform only takes action on objects that do not match the configuration.
When remote objects become damaged or degraded, such as when software running inside a virtual machine crashes but the virtual machine is still running, Terraform does not have no way to detect and respond to the problem. This is because Terraform only directly manages the machine as a whole.
In some cases, Terraform can automatically infer that an object is in an incomplete or degraded state. For example, when a complex object is partially created in the remote system or when a provisioner step failed. When this occurs, Terraform automatically flags resources to recreate.
You can manually replace objects when Terraform is unable to infer that an object should be replaced.
Workflows
When you meed to replace an object, you can use the following methods.
Manually replace resources
Add the -replace
flag
to your terraform plan
or terraform apply
command:
$ terraform apply -replace="aws_instance.example"
# ...
# aws_instance.example will be replaced, as requested
-/+ resource "aws_instance" "example" {
# ...
}
Replace resource in tainted
state
Terraform applies the tainted
status to objects in the state data when Terraform is able to infer that the object is in a degraded or damaged state. This status indicates that the object exists but may not be fully-functional. Terraform replaces objects in a tainted
states during the next plan
or apply
operation.
# aws_instance.example is tainted, so must be replaced
-/+ resource "aws_instance" "example" {
# ...
}
If Terraform has marked an object as tainted but you consider it to be working
correctly and do not want to replace it, you can override Terraform's
determination using the terraform untaint
command,
after which Terraform will consider the object to be ready for use by any
downstream resource declarations.
You can force Terraform to mark a particular object as tainted using
the terraform taint
command, but that approach is
deprecated in favor of the -replace=...
option, which avoids the need to
create an interim state snapshot with a tainted object.