Skip to content

Commit

Permalink
Updated some terraform related scripts
Browse files Browse the repository at this point in the history
  • Loading branch information
dj-wasabi committed Dec 21, 2020
1 parent 2544dd2 commit 7fc41cb
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 25 deletions.
2 changes: 1 addition & 1 deletion bin/terraform_docs.sh
Original file line number Diff line number Diff line change
Expand Up @@ -311,7 +311,7 @@ EOF

}

# global arrays
# global arrays
declare -a ARGS=()
declare -a FILES=()

Expand Down
2 changes: 1 addition & 1 deletion bin/terraform_tfsec.sh
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ parse_cmdline_() {
done
}

# global arrays
# global arrays
declare -a ARGS=()
declare -a FILES=()

Expand Down
51 changes: 28 additions & 23 deletions bin/terraform_validate.sh
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
#!/usr/bin/env bash
set -eo pipefail

# `terraform validate` requires this env variable to be set
export AWS_DEFAULT_REGION=${AWS_DEFAULT_REGION:-us-east-1}

main() {
initialize_
parse_cmdline_ "$@"
Expand Down Expand Up @@ -80,34 +83,36 @@ terraform_validate_() {

if [[ -n "$(find "$path_uniq" -maxdepth 1 -name '*.tf' -print -quit)" ]]; then

local starting_path
starting_path=$(realpath "$path_uniq")
local terraform_path
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")
pushd "$(realpath "$path_uniq")" > /dev/null

if [[ ! -d .terraform ]]; then
set +e
init_output=$(terraform init -backend=false 2>&1)
init_code=$?
set -e

if [[ $init_code != 0 ]]; then
error=1
echo "Init before validation failed: $path_uniq"
echo "$init_output"
popd > /dev/null
continue
fi
done
fi

local validate_path
validate_path="${path_uniq#"$terraform_path"}"
set +e
validate_output=$(terraform validate "${ARGS[@]}" 2>&1)
validate_code=$?
set -e

# Change to the directory that has been initialized, run validation, then
# change back to the starting directory.
cd "$(realpath "$terraform_path")"
if ! terraform validate "${ARGS[@]}" "$validate_path"; then
if [[ $validate_code != 0 ]]; then
error=1
echo "Validation failed: $path_uniq"
echo "$validate_output"
echo
echo "Failed path: $path_uniq"
echo "================================"
fi
cd "$starting_path"

popd > /dev/null
fi
done

Expand All @@ -116,7 +121,7 @@ terraform_validate_() {
fi
}

# global arrays
# global arrays
declare -a ARGS
declare -a ENVS
declare -a FILES
Expand Down

0 comments on commit 7fc41cb

Please sign in to comment.