Format Your Terraform Code with Github Actions

Jake Jones
FAUN — Developer Community 🐾
6 min readOct 23, 2020

--

So, today I discovered how to automate running a terraform fmt and committing it using Github actions!

Photo by Alex Knight on Unsplash

Github Actions

If you are not aware, GitHub actions are actions that GitHub can run for you automatically to perform various…. actions. These actions will be computed on some virtual machine far far away for just the amount of time needed to perform your action.

If you already know how to setup GitHub actions, you can go find my YAML file here. Find terraform-fmt-commit.yml in that folder.

Terraform fmt Setup

Terraform is a great human-readable language for creating infrastructure, but it’s still not easy to read if it isn’t formatted correctly.

The terraform fmt command will take something like this:

resource "aws_s3_bucket" "s3_bucket" {
bucket_prefix = "test-"
}

and make it look like this:

resource "aws_s3_bucket" "s3_bucket" {
bucket_prefix = "test-"
}

The easily readable way that the file is supposed to be formatted. However, this relies on humans to take the initiative to run terraform fmt before they commit and push their code. However, there is a way around the humans!

Automating Terraform fmt

Terraform has a published GitHub action that will check out a branch, set up terraform, run terraform init, run terraform fmt -check, run terraform plan, and finally run terraform apply. This action can be found here.

There is another GitHub action called Add & Commit. This will allow us to commit the changes after running our terraform fmt. What I did was combine some elements of both of these files to create this one:

I’ll leave the comments in so you can gather what is going on.

name: 'Terraform'
on:
push:
branches:
- master
pull_request:
jobs:
terraform:
name: 'Terraform'
runs-on: ubuntu-latest
# Use the Bash shell regardless whether the GitHub Actions runner is ubuntu-latest, macos-latest, or windows-latestdefaults:
run:
shell: bash
steps:# Checkout the repository to the GitHub Actions runner
- name: Checkout
uses: actions/checkout@v2
# Install the latest version of Terraform CLI and configure the Terraform CLI configuration file with a Terraform Cloud user API token
- name: Setup Terraform
uses: hashicorp/setup-terraform@v1
with:
cli_config_credentials_token: ${{ secrets.TF_API_TOKEN }}
# Initialize a new or existing Terraform working directory by creating initial files, loading any remote state, downloading modules, etc.
- name: Terraform Init
run: terraform init
# Checks that all Terraform configuration files adhere to a canonical format
- name: Terraform Format
run: terraform fmt
- name: Add & Commit # You may pin to the exact commit or the version.
# uses: EndBug/add-and-commit@b5dec7ea7647ed6edf307ec828d3aeb6bca69f63
uses: EndBug/add-and-commit@v5.1.0
with:
# Arguments for the git add command
add: '.'
# The name of the user that will be displayed as the author of the commit
author_name: 'Jake Jones'
# The email of the user that will be displayed as the author of the commit
author_email: # optional
# Name of the branch to use, if different from the one that triggered the workflow
branch: # optional
# The directory where your repository is located. You should use actions/checkout first to set it up
cwd: # optional, default is .
# The message for the commit
message: 'ran terraform fmt'
# Arguments for the git rm command
remove: # optional
# Whether to use the --signoff option on git commit
signoff: # optional
# Arguments for the git tag command (the tag name always needs to be the first word not preceded by a hyphen)
tag: # optional

If it’s easier for you to follow you can find this in my repo here. Look for terraform-fmt-commit.yml. You will want to copy the contents, then save it inside the repo you want to use it on. The folder structure you save it in will need to be .github/workflows/thefile.yml.

There are a few adjustments to be made to the code, just replace the author name with your name and the message with the commit message you want to use. Then we need to create a secret for an API token.

Creating Your Token

First, log in to Terraform cloud. Then click on your profile in the top right.

Select user settings.

Click tokens on the left panel.

Click on “create an API token.”

Name your token and click create.

Copy your token and click done.

Setting Up Your Secret in Github

Now go back over to GitHub and find the repo you want to have this test setup on. Click settings, then secrets.

Click new secret.

Name the secret TF_API_TOKEN and paste your string. You will need to use that specific name because that is what we called it in the code.

BOOM! You are ready to run your code and have it formatted! Give it a try!

Testing the Workflow

Go to your repo after making your push and open actions.

Click on the run.

You can see that our command ran and edited the main.tf file. Then a commit was created with the message ran terraform fmt.

Let’s go take a look at our repo and see if we find that commit message for the main.tf file.

There it is!!! We did it!

Conclusion

I hope you found this helpful and that it keeps your code formatted all the time.

If you are interested in learning more about Terraform I have a Free Terraform Course for getting started and a course to help you study for your HashiCorp Certified: Terraform Associate.

I also highly suggest checking out Terraform Up & Running by Yevgeniy Brikman.

Happy learning!

👋 Join FAUN today and receive similar stories each week in your inbox! Get your weekly dose of the must-read tech stories, news, and tutorials.

Follow us on Twitter 🐦 and Facebook 👥 and Instagram 📷 and join our Facebook and Linkedin Groups 💬

If this post was helpful, please click the clap 👏 button below a few times to show your support for the author! ⬇

--

--