Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
@eschwartz

This comment has been minimized.

Copy link

commented Feb 22, 2018

This is great, thanks!

The one issue I see is that it will fully stage any files output by git diff
If you have any partially staged files,
this hook will fully stage them.

I might suggest something like this:

#!/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
    /usr/local/bin/terraform fmt -check=true $f
  fi
done

which will exit 1 if any files are not properly formatted.
Not as automagical, but it will also prevent any unintended consequences

@atrepca

This comment has been minimized.

Copy link

commented Apr 6, 2018

Add --diff-filter=d to the git diff command to filter deleted files, can't run fmt on those.

@pangteypiyush

This comment has been minimized.

Copy link

commented Sep 11, 2019

Format tfvars files [[ "${f##*.}" =~ ^(tf|tfvars)$ ]]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.