The Better Way to “Terraform Apply”

road sign under clouds

Your terraform plan looked good! So what happened? You meticulously reviewed each and every change so you’re ready to apply. You punch in terraform apply, watch it go, then type quickly type yes. After all the plan looked good…

The problem here is that the plan stage and the apply stage happen at different points in time. A few things could happen between then.

If you’d like to watch the video version of this article, check this out:

The Better Way to Terraform Apply – Never Type ‘yes’ Again

Infrastructure Drift

In between your plan and apply, another team member made a manual change to your infrastructure. Making your old plan outdated.

Code Drift

While less likely, code drift could occur in environments where scripts or CICD jobs running Terraform are improperly configured.

The Solution

How do we guarantee plan/apply consistency? We save the plan to a file and use it to apply our changes.

A Terraform plan is the file created as a result of terraform plan and is the input to terraform apply. The plan represents the changes that Terraform needs to make to infrastructure to reach the desired state represented by the configuration.

HashiCorp Sentinel Docs

This file guarantees consistency between plan/apply and can be used by other tools like Sentinel or other automated security tools to guarantee that changes adhere to security policy before being applied.

The Code

This following code snippet is an example of using terraform plan to create a plan file (called “tfplan”) and using it to apply infrastructure changes.

$ terraform plan -out tfplan

Terraform used the selected providers to generate the following execution plan.

(... SNIP ...)

Saved the plan to: tfplan

To perform exactly these actions, run the following command to apply:
terraform apply "tfplan"

$ terraform apply tfplan

Feel free to add *tfplan* to your .gitignore file to keep things clean”

Feel free to reach out with any questions! Check out my other Terraform content here:

Jedi Park Avatar

Posted by

Leave a Reply

Discover more from AsCode

Subscribe now to keep reading and get access to the full archive.

Continue reading