Skip to content

Instantly share code, notes, and snippets.

@jamtur01
Created October 18, 2016 21:54
Show Gist options
  • Save jamtur01/a567078b7ba545c3492f7cd32a65450d to your computer and use it in GitHub Desktop.
Save jamtur01/a567078b7ba545c3492f7cd32a65450d to your computer and use it in GitHub Desktop.
A Terraform validation and formatting pre-commit hook
#!/usr/bin/env bash
set -e
# Formats any *.tf files according to the hashicorp convention
files=$(git diff --cached --name-only)
for f in $files
do
if [ -e "$f" ] && [[ $f == *.tf ]]; then
#terraform validate `dirname $f`
terraform fmt $f
git add $f
fi
done
@slmg
Copy link

slmg commented Dec 11, 2020

Extending the previous ideas: avoid automatically running git add, however automatically run terraform fmt and let the user the responsibility to stage changes or not.

#!/usr/bin/env bash
set -e

# Formats any *.tf files according to the hashicorp convention
files=$(git diff --cached --name-only)
for f in $files
do
  if [ -e "$f" ] && [[ $f == *.tf ]]; then
    terraform fmt -check=true $f > /dev/null || {
        echo "pre-hook: Incorrect formatting, let me fix this for you"
        cmd="terraform fmt -recursive"
        echo "Running '$cmd'..."
        $cmd
        echo "Done. You may now stage changes."
    }
  fi
done

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment