I have a terraform pipeline that has a planning step. We deploy to MANY environments, each with its own workflow. I’d like to be able to capture the results of the terraform plan and change the next step of the workflow based on whether or not changes were detected. As far as I know the only place to grab this is from the stdout. Anyone know a way to do this?
If specifics help you understand the use case, here’s what I’d like to do. If a plan comes back with no changes, I want to kill the workflow there. If there ARE changes, I’d like to trigger an approval step that would then trigger a terraform-apply once approved. And the real dream would be to see the number of changes terraform is planning on making surfaced back to bitbucket as a test result. And all of that depends on manipulating data that as far as I know only exists in circleci’s stdout.
The best solution I have right now is to run terraform plan -detailed-exitcode and if it returns a 0 (meaning no changes found) then I call the circleci api and kill the workflow. But that’s not ideal.
Hey @kdubkris ,
Thanks for sharing your context, as well as a possible solution you have considered.
That was helpful to know your concerns!
I am not a terraform user myself, so please bear with me if I misunderstood some concepts.
It looks to be that the
terraform plan and
terraform apply commands are CI-friendly.
terraform plan, we can use the
-out option to generate the output for the subsequent
terraform apply to pick up from.
You can use the optional
-out=FILE option to save the generated plan to a file on disk, which you can later execute by passing the file to
terraform apply as an extra argument. This two-step workflow is primarily intended for when running Terraform in automation.
From there on, as a next step or job in your _.circleci/config setup, you can then pass this output file to
terraform plan, which will be non-interactive, and auto-applies the changes if any.
Another way to use
terraform apply is to pass it the filename of a saved plan file you created earlier with
terraform plan -out=... , in which case Terraform will apply the changes in the plan without any confirmation prompt. This two-step workflow is primarily intended for when running Terraform in automation.
I believe with this, you may not need the
-detailed-exitcode option when using
terraform plan itself.
Let me know if this helps, or if you like, you can also reach out to us via a Support ticket to share your config!