Last active
November 21, 2018 15:40
-
-
Save sportebois/07982d7846290abb85ab9227c1d30914 to your computer and use it in GitHub Desktop.
Nomad job formatter (chmox+x and symlink it in your $PATH)
This file contains 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
#!/usr/bin/env bash | |
set -euo pipefail | |
IFS=$'\n\t' | |
#/ Description: | |
#/ Run Terraform fmt on nomad file to format HCL, and update the file in place. | |
#/ | |
#/ Arguments: | |
#/ $1 the nomad flie | |
#/ --diff if set, then do not write the changes, but show the diff between current and cacnonical format | |
#/ | |
#/ Sample use: | |
#/ fmtnomad myjob.nomad | |
#/ fmtnomad myjob.nomad --diff | |
#/ | |
#/ Options: | |
#/ --help: Display this message | |
#/ | |
#/ Pre-requisites: | |
#/ Requires Terraform in your path | |
readonly SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" | |
readonly SCRIPT_NAME="$(basename "$0")" | |
success() { echo -e "\e[32;1m[SUCCESS]\e[0m $*"; } | |
info() { echo -e "\e[34m[INFO]\e[0m $*"; } | |
error() { echo -e "\e[31m[ERROR]\e[0m $*"; } | |
usage() { grep '^#/' "$0" | cut -c4- ; } | |
expr "$*" : ".*--help" > /dev/null && usage && exit 0 | |
# Inputs | |
readonly NOMAD_FILE=${1:-""} | |
readonly ONLY_DIFF=${2:-""} | |
if [ -z "${NOMAD_FILE}" ]; then | |
usage | |
error "You must provide a nomad file to format." | |
exit 1 | |
fi | |
readonly TMP_FILE=$(mktemp /tmp/nomad-fmt.XXXXXX) | |
success_flag=0 | |
cleanup() { | |
rm "${TMP_FILE}" | |
if [[ ${success_flag} == 0 ]]; then | |
error "Not completed successfully." | |
fi | |
} | |
trap cleanup EXIT | |
format() { | |
# Format to a tempo file then overwrite the source | |
cat "${NOMAD_FILE}" | terraform fmt - > "${TMP_FILE}" | |
cp "${TMP_FILE}" "${NOMAD_FILE}" | |
success_flag=1 | |
success "${NOMAD_FILE} formatted." | |
} | |
diff() { | |
# Format to a tempo file then overwrite the source | |
cat "${NOMAD_FILE}" | terraform fmt -diff=true - | |
success_flag=1 | |
} | |
if [ -z "${ONLY_DIFF}" ]; then | |
format | |
else | |
diff | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment