How to Avoid Rebuild Resources with Terraform/Terragrunt


I use Terraform and Terragrunt a lot at work to keep track of infrastructure changes. Sometimes I refactored code in modules so there’s no change to infrastructure but since the module changed terraform will insist to rebuild affected resources. It’s not quite comfortable to destroy some resources and then just create exactly the same ones. eg.

Plan:3 to add, 0 to change, 3 to destroy.

Since I can guarantee there’s no change in infrastructure, I only need to satisfy terraform so it thinks everything checks out. To achieve this I need to remove the stale records from the state file then import existing infrastructure resources into the state file. For example:

# remove the stale state
terragrunt state rm 'google_compute_security_policy.default["internal-access"]'
# import the same resource but associate it with the new module
terragrunt import 'module.security_policies["internal-access"].google_compute_security_policy.policy' my-gcp-project-id/internal-access-security-policy

After the remove/import operation done for each resource, running terragrunt plan shows:

Plan: 0 to add, 3 to change, 0 to destroy.

Looks like there will be some changes but mostly just metadata changes like labels, etc. Much better 🙂