Skip to content

Commit 7694fb9

Browse files
authored
fix: Change terraform_validate hook functionality for subdirectories with terraform files (antonbabenko#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: antonbabenko@35e0356 * - Clean up comments. - Adjust variable names to better reflect what they are holding.
1 parent 8cbcd8e commit 7694fb9

File tree

2 files changed

+23
-3
lines changed

2 files changed

+23
-3
lines changed

.pre-commit-hooks.yaml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@
3535
exclude: \.terraform\/.*$
3636

3737
- id: terraform_validate
38-
name: Terraform validate without variables
38+
name: Terraform validate
3939
description: Validates all Terraform configuration files.
4040
entry: terraform_validate.sh
4141
language: script

terraform_validate.sh

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,13 +15,33 @@ done
1515
for path_uniq in $(echo "${paths[*]}" | tr ' ' '\n' | sort -u); do
1616
path_uniq="${path_uniq//__REPLACED__SPACE__/ }"
1717

18-
if [[ -n "$(find . -maxdepth 1 -name '*.tf' -print -quit)" ]]; then
19-
if ! terraform validate $path_uniq; then
18+
if [[ -n "$(find $path_uniq -maxdepth 1 -name '*.tf' -print -quit)" ]]; then
19+
20+
starting_path=$(realpath "$path_uniq")
21+
terraform_path="$path_uniq"
22+
23+
# Find the relevant .terraform directory (indicating a 'terraform init'),
24+
# but fall through to the current directory.
25+
while [[ "$terraform_path" != "." ]]; do
26+
if [[ -d "$terraform_path/.terraform" ]]; then
27+
break
28+
else
29+
terraform_path=$(dirname "$terraform_path")
30+
fi
31+
done
32+
33+
validate_path="${path_uniq#"$terraform_path"}"
34+
35+
# Change to the directory that has been initialized, run validation, then
36+
# change back to the starting directory.
37+
cd "$(realpath "$terraform_path")"
38+
if ! terraform validate $validate_path; then
2039
error=1
2140
echo
2241
echo "Failed path: $path_uniq"
2342
echo "================================"
2443
fi
44+
cd "$starting_path"
2545
fi
2646
done
2747

0 commit comments

Comments
 (0)