Created
December 11, 2020 21:41
-
-
Save ndom91/8745195a1fe86f7fec8c4af41373375d to your computer and use it in GitHub Desktop.
ansible-lint shell git pre-commit hook
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/sh | |
# requires ansible-lint to be installed | |
# 'pip install --user ansible-lint' | |
# copy this file to .git/hooks/pre-commit and make it executable | |
#get list of files to add to commit checks - doesn't check files not being added in this commit | |
STAGED_FILES=$(git diff --staged --name-only --diff-filter=MAC | grep ".yml") | |
#if nothing being added, exit | |
if [[ "$STAGED_FILES" = "" ]]; then | |
exit 0 | |
fi | |
ANSIBLE_LINT="$(command -v ansible-lint)" | |
if [[ ! -x $ANSIBLE_LINT ]]; then | |
printf "ansible-lint not available.\n Please install it with 'pip install --user ansible-lint'.\n" | |
exit 0 | |
fi | |
#default is that the checks have passed | |
PASS=true | |
printf "\nValidating yaml files with ansible-lint\n" | |
#run ansible-lint on each .yml file being committed. | |
#Print pass/fail and set PASS value appropriately | |
for FILE in $STAGED_FILES | |
do | |
"ansible-lint" "$FILE" | |
if [[ "$?" == 0 ]]; then | |
printf "\t\033[32mAnsible-Lint Passed: $FILE\033[0m\n" | |
else | |
printf "\t\033[41mAnsible-Lint Failed: $FILE\033[0m\n" | |
PASS=false | |
fi | |
done | |
printf "\nAnsible validation completed!\n" | |
#If it didn't pass, explain what's going on. | |
if ! $PASS; then | |
printf "\033[41mCOMMIT FAILED:\033[0m Your commit contains files that should pass ansible-lint but do not. Please fix the yaml, variable or json errors and try again.\nIt is possible to bypass this if required with --no-verify\n" | |
exit 1 | |
else | |
printf "\033[42mCOMMIT SUCCEEDED\033[0m\n" | |
fi | |
exit $? |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment