Terraform interview question · Most asked
What lifecycle settings does Terraform offer, and when do you use them?
Summary
create_before_destroy creates the replacement before deleting the old resource (avoiding downtime for things like certificates or launch templates); prevent_destroy makes any plan that would destroy the resource fail (protecting databases and state buckets); ignore_changes stops Terraform from reverting attributes managed elsewhere (for example a desired count changed by an autoscaler); replace_triggered_by forces replacement when another value changes.
Longer Answer
Use them deliberately: ignore_changes can hide real drift, and prevent_destroy only protects against Terraform plans (removing the resource block from configuration removes the protection too). Preconditions and postconditions in lifecycle blocks validate assumptions, such as an AMI being the right architecture, with clear error messages.
Key Points
- create_before_destroy avoids gaps.
- prevent_destroy protects critical resources.
- ignore_changes for externally managed attributes.
- Pre/postconditions validate assumptions.
More most-asked Terraform questions
- How do you handle secrets in Terraform?
- How would you run Terraform in CI/CD?
- What is Terraform state, why is it needed, and where should it be stored?
- count or for_each: when do you use each?
- Walk through terraform init, plan and apply. What does each do?
- What is Terraform, and how does it work at a high level?
- What are Terraform modules, and how do you design good ones?
- A terraform plan wants to destroy and recreate a database. What do you do?