diff --git a/README.md b/README.md index 2fa925886..a287f63e6 100644 --- a/README.md +++ b/README.md @@ -599,6 +599,14 @@ To replicate functionality in `terraform_docs` hook: - --args=--config=__GIT_WORKING_DIR__/.tflint.hcl ``` +3. When you want the root relative paths to the linting error messages rather than just module relative paths. You need to use TFlint native `--chdir` functionality. Note: this requires TFlint version 0.44.0 or later. For example: + + ```yaml + - id: terraform_tflint + args: + - --hook-config=--skip-chdir + ``` + ### terraform_tfsec diff --git a/hooks/_common.sh b/hooks/_common.sh index 37b32d842..116d468b5 100644 --- a/hooks/_common.sh +++ b/hooks/_common.sh @@ -217,6 +217,25 @@ function common::per_dir_hook { ((index += 1)) done + # Lookup hook-config for modifiers that impact common behavior + local SKIP_CHDIR=false + IFS=";" read -r -a configs <<< "${HOOK_CONFIG[*]}" + for c in "${configs[@]}"; do + IFS="=" read -r -a config <<< "$c" + key=${config[0]} + value=${config[1]} + + case $key in + --skip-chdir) + # this flag will skip pushing and popping directories + # delegating the responsibility to the hooked plugin/binary + if [ "$value" != "false" ]; then + SKIP_CHDIR=true + fi + ;; + esac + done + # preserve errexit status shopt -qo errexit && ERREXIT_IS_SET=true # allow hook to continue if exit_code is greater than 0 @@ -226,7 +245,10 @@ function common::per_dir_hook { # run hook for each path for dir_path in $(echo "${dir_paths[*]}" | tr ' ' '\n' | sort -u); do dir_path="${dir_path//__REPLACED__SPACE__/ }" - pushd "$dir_path" > /dev/null || continue + + if ! $SKIP_CHDIR; then + pushd "$dir_path" > /dev/null || continue + fi per_dir_hook_unique_part "$dir_path" "${args[@]}" @@ -235,7 +257,10 @@ function common::per_dir_hook { final_exit_code=$exit_code fi - popd > /dev/null + if ! $SKIP_CHDIR; then + popd > /dev/null + fi + done # restore errexit if it was set before the "for" loop diff --git a/hooks/terraform_tflint.sh b/hooks/terraform_tflint.sh index d488cb734..eb9a096a8 100755 --- a/hooks/terraform_tflint.sh +++ b/hooks/terraform_tflint.sh @@ -50,16 +50,29 @@ function per_dir_hook_unique_part { shift local -a -r args=("$@") - # Print checked PATH **only** if TFLint have any messages - # shellcheck disable=SC2091,SC2068 # Suppress error output - $(tflint ${args[@]} 2>&1) 2> /dev/null || { - common::colorify "yellow" "TFLint in $dir_path/:" + IFS=";" read -r -a configs <<< "${HOOK_CONFIG[*]}" + for c in "${configs[@]}"; do + IFS="=" read -r -a config <<< "$c" + key=${config[0]} + value=${config[1]} - tflint "${args[@]}" - } + case $key in + --skip-chdir) + if [ "$value" != "false" ]; then + DIR_ARGS="--chdir=$dir_path" + fi + ;; + esac + done - # return exit code to common::per_dir_hook + COMMAND_OUTPUT=$({ tflint "${DIR_ARGS}" "${args[@]}"; } 2>&1) local exit_code=$? + + if [ $exit_code -ne 0 ]; then + common::colorify "yellow" "TFLint in $dir_path/:" + echo "$COMMAND_OUTPUT" + fi + return $exit_code }