Terraform apply in GitLab CI/CD only if plan is not empty

Viewed 581

I use Gitlab CI/CD to provision infrastructure with Terraform. I currently have a 3 stages pipeline (init, plan, apply) that works great with a manual apply job. The plan job shares a plan artefact with the apply job.

Sometimes the plan is empty (no resource to change) but the apply job is still mandatory. Do you know a way to avoid running the apply job when the plan is empty ? Or to automatically (instead of manually) run the apply job when the plan is empty ?

2 Answers

The easiest way to implement that is by using -detailed-exitcode in your terraform plan step. As per Terraform documentation:

  -detailed-exitcode  Return detailed exit codes when the command exits. This
                  will change the meaning of exit codes to:
                  0 - Succeeded, diff is empty (no changes)
                  1 - Errored
                  2 - Succeeded, there is a diff

As an example, run in your terminal the plan:

terraform plan -detailed-exitcode

An then run in your terminal:

echo $?

If the plan contains any changes your value won't be zero. You just need evaluate that value in your CI/CD with an If statement to decide if you want to run the apply or not.

In you plan job, you output your plan file:

terraform plan --out planoutput

Which you pass as an artifact to your apply job.

Before applying, you can grep (I'll let you find the correct grep command here) your plan

terraform show planoutput | grep Plan

And depending on that, do a terraform apply or not.

Related