Sobes.tech
Middle

If you wrote code in Terraform and ran a plan command, then your colleague added their code and also ran the plan command. Now, you need to apply your changes. Will there be errors?

sobes.tech AI

Answer from AI

Yes, errors can occur.

The reason is that Terraform uses state files (*.tfstate) to track infrastructure. When you create a plan, it is based on the current state of the infrastructure described in your local state file.

When your colleague added their code and created their plan, they likely updated the state file (or used a shared remote copy if remote state storage is configured).

If you now apply your plan, which is based on an old state file, Terraform may:

  • Detect discrepancies: The current actual state of the infrastructure (considering your colleague's changes) does not match the state described in your local state file, which was used to generate the plan.
  • Attempt to perform actions already performed by your colleague.
  • Attempt to delete or modify resources added or changed by your colleague.

This can lead to errors like lock contention, state mismatch errors, or even undesirable infrastructure changes.

It is recommended to:

  • Get the current state: Run terraform init and terraform refresh (if remote state is not used or not synchronized automatically).
  • Generate a new plan: Run terraform plan again to see how your changes will be applied considering the current state.
  • Use state locking: Configure remote state storage with locking to prevent concurrent changes.

Example command to generate a new plan:

terraform plan
# Creates a new plan based on the current state and your changes.