Skip to content

Instantly share code, notes, and snippets.

@pre
Last active January 20, 2025 12:12
Show Gist options
  • Save pre/f704c67e0da3348180950785bc84bd0e to your computer and use it in GitHub Desktop.
Save pre/f704c67e0da3348180950785bc84bd0e to your computer and use it in GitHub Desktop.
Traverse directories recursively and run tf
#!/usr/bin/env bash
set -Eeuo pipefail
# gather error codes
# https://gist.github.com/matti/3d2f04b1a9485a3a15d0267a68b341ba#gather-exit-codes-of-backgrounded-processes
export NO_COLOR="1"
export TF_CLI_ARGS="-no-color"
CMD="${1:-}"
_err() {
>&2 echo -e "🔥 Error: $*"
}
_out() {
>&2 echo -e "🚖 $*"
}
_usage() {
>&2 cat << EOF
Usage: $0 <command>
$0 traverses the current directory and runs <command> in each of its subdirectories.
Some directories directories are skipped, such as directories starting with a
- dot, underscore,
- terraform, modules, bootstrap.
EOF
}
if [[ -z "${CMD}" ]]; then
_usage
exit 1
fi
if [[ ! -x ${CMD} ]]; then
_err "Command '${CMD}' not found or not executable"
exit 1
fi
_shutdown() {
_warn "Shutdown.."
trap '' TERM INT ERR # ignore traps when already shutting down
>&2 echo "Subprocesses of current process group:"
jobs
>&2 echo "Kill current process group"
kill 0
>&2 echo "Waiting all remaining processess to exit"
wait
_info "Bye bye!"
exit 0
}
_on_error() {
trap '' ERR
line_path=$(caller)
line=${line_path% *}
path=${line_path#* }
>&2 echo -e "\n‼️ ERR $path:$line $BASH_COMMAND exited with $1"
_shutdown
}
trap '_on_error $?' ERR
trap _shutdown TERM INT
_dirs_in_cwd() {
find . -maxdepth 1 -mindepth 1 -type d | sort
}
_traverse() {
local dir; dir="${1}"
basenamed_dir="$(basename "${dir}")"
case "${basenamed_dir}" in
".")
# OK
;;
.*|_*|terraform*|modules|bootstrap)
return 0
;;
esac
>/dev/null pushd "${dir}"
tf plan
for d in $(_dirs_in_cwd); do
local basename_d
basename_d="$(basename "${d}")"
(
_traverse "${d}"
) 2>&1 | sed -le "s#^#/${basename_d}#;" &
done
wait
}
_traverse .
wait
echo "All subshells have completed"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment