Home > database >  Why is terraform plan always returning exit code 0 even when there are new resources to add?
Why is terraform plan always returning exit code 0 even when there are new resources to add?

Time:10-12

Terraform offers the following exit codes:

0 = Succeeded with empty diff (no changes)
1 = Error
2 = Succeeded with non-empty diff (changes present)

I need to perform terraform apply only if any new resources need to be added or there are any changes to apply.

if [ $? -eq 0 ]; then
    echo "No changes, not applying"
elif [ $? -eq 1 ]; then
    echo "Terraform plan failed"
    exit 1
elif [ $? -eq 2 ]; then
    echo "Terraform apply needed"
fi

But I am getting exit code 0, even for a terraform plan command which outputs:

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

What is the issue?

CodePudding user response:

Honest question, instead of checking if the plan has changed and after that run a terraform apply, why can't you run something like:

              terraform apply --auto-approve

So no matter if the state has changed or not, terraform will run the apply and if any resources need to be added or remove, it will do.

(Sorry, I wanted to send it as a comment but I don't have enough points)

CodePudding user response:

For terraform plan to return those exit codes, you must supply the -detailed-exitcode option as detailed in the documentation.

-detailed-exitcode - Returns a detailed exit code when the command exits.


This should be what your terraform plan command should look like, otherwise you will get an exit code of 0 regardless of output:

terraform plan -detailed-exitcode ...
  • Related