Skip to content

Instantly share code, notes, and snippets.

@brunojppb
Created December 22, 2023 10:45
Show Gist options
  • Save brunojppb/53926d413429936571a4c25b7d2ffdc7 to your computer and use it in GitHub Desktop.
Save brunojppb/53926d413429936571a4c25b7d2ffdc7 to your computer and use it in GitHub Desktop.
Format Terraform files on a pre-coomit hook
#!/bin/sh
# Apply Terraform formatting to any .tf files modified during
# git changes that are staged.
# Make sure that you have terraform <YOUR_TERRAFORM_VERSION> installed.
# You can use TFSwitch to manage different versions of Terraform at once
# See: https://tfswitch.warrensbox.com/Install/
REQUIRED_TF_VERSION="Terraform v0.12.31"
# Halt the script if any pipe operations fail
set +o pipefail
TERRAFORM_VERSION=$(terraform --version | grep -Ei "v[[:digit:]]{1,}\.[[:digit:]]{1,}\.[[:digit:]]{1,}")
if [[ $TERRAFORM_VERSION != $REQUIRED_TF_VERSION ]] ; then
echo "You have an invalid version of Terraform: $TERRAFORM_VERSION"
echo "Please install $REQUIRED_TF_VERSION"
exit 1
fi
FMT_OUTPUT=$(git diff --name-only --staged | grep '\.tf$' | xargs -I{} terraform fmt -write=true {})
# The variable "$?" holds the latest pipe operation exit code
# which in this case came from `terraform fmt`
if [[ $? == 0 ]] ; then
echo "Terraform formatting applied successfully."
exit 0
else
echo "Terraform formatting error with code $?: $FMT_OUTPUT"
exit 1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment