From 7694fb9b9a2187670f55233d0317c05f6b0080d5 Mon Sep 17 00:00:00 2001 From: Nick M <50747025+mcdonnnj@users.noreply.github.com> Date: Sat, 4 Apr 2020 02:17:25 -0400 Subject: [PATCH] fix: Change terraform_validate hook functionality for subdirectories with terraform files (#100) * Update terraform_validate.sh: -Change to the directory before running terraform validate to use the Terraform configuration for the appropriate working directory. * Neglected to change the terraform validate call to use the default of the current directory. * Several changes to improve functionality: - Switch to checking the path for '*.tf' instead of always checking the current directory. - Try to find a '.terraform' directory (which indicates a `terraform init`) and change to that directory before running `terraform validate`. * Fix the description for the terraform_validate hook to reflect changes that were made in: https://github.com/antonbabenko/pre-commit-terraform/commit/35e0356188b64a4c5af9a4e7200d936e514cba71 * - Clean up comments. - Adjust variable names to better reflect what they are holding. --- .pre-commit-hooks.yaml | 2 +- terraform_validate.sh | 24 ++++++++++++++++++++++-- 2 files changed, 23 insertions(+), 3 deletions(-) diff --git a/.pre-commit-hooks.yaml b/.pre-commit-hooks.yaml index c7f4039..d0b27aa 100644 --- a/.pre-commit-hooks.yaml +++ b/.pre-commit-hooks.yaml @@ -35,7 +35,7 @@ exclude: \.terraform\/.*$ - id: terraform_validate - name: Terraform validate without variables + name: Terraform validate description: Validates all Terraform configuration files. entry: terraform_validate.sh language: script diff --git a/terraform_validate.sh b/terraform_validate.sh index 50bfd0b..3b44ed7 100755 --- a/terraform_validate.sh +++ b/terraform_validate.sh @@ -15,13 +15,33 @@ done for path_uniq in $(echo "${paths[*]}" | tr ' ' '\n' | sort -u); do path_uniq="${path_uniq//__REPLACED__SPACE__/ }" - if [[ -n "$(find . -maxdepth 1 -name '*.tf' -print -quit)" ]]; then - if ! terraform validate $path_uniq; then + if [[ -n "$(find $path_uniq -maxdepth 1 -name '*.tf' -print -quit)" ]]; then + + starting_path=$(realpath "$path_uniq") + terraform_path="$path_uniq" + + # Find the relevant .terraform directory (indicating a 'terraform init'), + # but fall through to the current directory. + while [[ "$terraform_path" != "." ]]; do + if [[ -d "$terraform_path/.terraform" ]]; then + break + else + terraform_path=$(dirname "$terraform_path") + fi + done + + validate_path="${path_uniq#"$terraform_path"}" + + # Change to the directory that has been initialized, run validation, then + # change back to the starting directory. + cd "$(realpath "$terraform_path")" + if ! terraform validate $validate_path; then error=1 echo echo "Failed path: $path_uniq" echo "================================" fi + cd "$starting_path" fi done