Github Actions and Terraform, revisited

This week we finally got to do some Terraform work again on a new project.

The setup is simple, we have some Azure resources we want to create, so there is no way around Infrastructure as Code and, by our choice, the battle-proven Terraform from Hashicorp.

Since the code lives up on Github, we want to automate the steps involved with the Terraform code and work with a standard pull request workflow.

This includes:

  • Lint and format the code.
  • Run validation.
  • Create the plan to be executed.
  • Post the changes as a pull request comment and review the changes.
  • If all is good and approved, apply the changes on merge.

or visualized:

Thankfully this is not a new subject to explore. There are tons of examples on how to work with Terraform and Github Actions, including an excellent post from Hashicorp on how to write this workflow.

Upon reading this post and writing out the code, we nearly got what we wanted.

The generated pull request post with the plan itself looks like this with the standard example:

A couple of things we didn't fancy here. First off, the plan itself is hidden away behind the drop-down menu, making it easy to miss if you're not careful - and you should be - Terraform is unforgiving if some resources are deleted by an error.

Second, the plan has no color highlighting, making it a bit hard to read. It appears just as a wall of text where details might be missed.

And third, the post itself should contain the brief summary of what is actually going to happen without reading the actual plan. I'm talking about this part:

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

After some more searching we found another excelent post by Andrew Walker who introduces enhanced formatting on the terraform plan output with the use of diff.

diff is a nice syntax to color highlight changes in files, just as Github's pull request view has. In a nutshell, diff has the following coding:

Great to highlight what will be created, deleted or changed when a terraform plan is executed.

After some inspiration from our friend Andrew and some more tinkering, we came out with an output we were quite happy with:

The overview itself is much cleaner with less stuff. The checks are still there, but with emojis instead of the text. The summary is also on the top of the comment.

The plan itself shows like this:

The observant Terraform author will notice something here. The symbol for "update in place" should be ~, not !. This is a little trick we did to get the orange color for in-place changes, not just additions and destroyed resources.

So far we are quite happy with this layout.

The following gist contains the workflow. Hopefully it will be of inspiration to others down the road.