I have an AWS Terraform repo where i have an architecture for an AWS solution.
Over time people have gone onto the management console and made changes to the architecture without changing the terraform code causing a drift between the repo and the actual architecture on aws.
Is there a way i can change detect the drift and update my main.tf
file to match the new architecture? I know you can use terraform apply -refresh
to update the state file but does this affect the main.tf
file aswell? Does anyone have a solution for a problem like this so that all my files are updated correctly? Thanks!
2
Answers
Sadly no. main.tf is not affected.
Such a solution does not exist unless you develop your own. You have to manually update your main.tf to match the state of your resources.
However a bit of help can come from former2 which can scan your resources and produce terraform code.
Terraform’s work of evaluating the given configuration to determine the desired state is inherently lossy. The desired state used to produce a plan, and the updated state obtained by applying that plan, include only the final values resulting from evaluating any expressions, and it isn’t possible in general to reverse updated values back to updated expressions that would produce those values.
For example, imagine that you have an argument like this:
This produces a SHA-1 checksum of the string "hello". If someone changes the checksum in the remote system, Terraform can see that the checksum no longer matches but it cannot feasibly determine what new string must be provided to
sha1
to produce that new checksum. This is an extreme example using an inherently irreversible function, but this general problem applies to any argument whose definition is more than just a literal value.Instead,
terraform plan -refresh-only
will show you the difference between the previous run result and the refreshed state, so you can see how the final results for each argument have changed. You’ll need to manually update your configuration so that it will somehow produce a value that matches that result, which is sometimes as simple as just copying the value literally into your configuration but is often more complicated because arguments in aresource
block can be derived from data elsewhere in your module and transformed arbitrarily using Terraform functions.