0

I am recently trying to detect drift in a yaml pipeline in azure. Im currently using a bash script in the pipeline to do a terraform plan and fail the pipeline if there is drift. Im using -detailed-exitcode as an argument to see if there are changes made to the terraform plan file.

However the code doesnt seem to take in the exit code and the terraform plan is simply being exeuted and output to a file even though there was drift detected. Im unsure why it happens... isit because i failed to install something?

Or anyone could give me an alternative other than -detailed-exitcode .

Below is my code

             - bash: |    
                                          
                    terraform init -reconfigure
                    terraform validate
                    terraform plan -detailed-exitcode -out=FILE_NEW || exit_status=$?
                    if [ $exit_status -eq 0 ]; then
                        echo "No changes, not applying"
                     elif [ $exit_status -eq 1 ]; then
                        echo "Terraform plan failed"
                        exit 1
                     elif [ $exit_status -eq 2 ]; then
                        echo "Drift Detected"
                    fi
                  displayName: Detecting Terraform Drift
Buhu
  • 1
  • Tangentially [Why is testing ”$?” to see if a command succeeded or not, an anti-pattern?](https://stackoverflow.com/questions/36313216/why-is-testing-to-see-if-a-command-succeeded-or-not-an-anti-pattern) – tripleee Oct 09 '22 at 11:54
  • Can you clarify exactly what you were expecting to happen? As far as I can tell, you are running the `terraform plan -detailed-exitcode -out=FILE_NEW` always, so when would you not expect the output file to be created? Also, your `exit_status` variable will never have `0` since it is only assigned if the command failed. – terdon Oct 09 '22 at 13:24
  • Im ultimately trying to detect for drift in the existing terraform statefile. So by using the -detailed-exitcode; i was hoping to output the new terraform plan to a file(which it does); and when the command exits; it will give me three different exit codes which i can use to stop the existing pipeline when needed. Reference taken from here: https://sathyasays.com/2020/12/31/terraform-apply-only-on-change/ https://www.taccoform.com/posts/tfg_p3/#:~:text=When%20appended%20to%20a%20terraform,2%20%2D%20Oh%20no! https://www.terraform.io/cli/commands/plan – Buhu Oct 09 '22 at 14:44

0 Answers0