constellation/bazel/ci/terraform.sh.in
Paul Meyer 8489516208 bazel: better ci script naming
Signed-off-by: Paul Meyer <49727155+katexochen@users.noreply.github.com>
2023-03-30 12:01:13 -04:00

97 lines
2.6 KiB
Bash

#!/usr/bin/env bash
###### script header ######
lib=$(realpath @@BASE_LIB@@) || exit 1
stat "${lib}" >> /dev/null || exit 1
# shellcheck source=../sh/lib.bash
if ! source "${lib}"; then
echo "Error: could not find import"
exit 1
fi
terraform=$(realpath @@TERRAFORM@@)
stat "${terraform}" >> /dev/null
mode="@@MODE@@"
cd "${BUILD_WORKSPACE_DIRECTORY}"
###### script body ######
readarray -t <<< "$(
find "$(pwd)" -type f -name "*.tf" -exec dirname "{}" \; |
sort -ud
)"
terraformPaths=("${MAPFILE[@]}")
terraformModules=()
pathPrefix="${terraformPaths[0]}"
for ((i = 1; i < ${#terraformPaths[@]}; i++)); do
path="${terraformPaths[i]}"
if [[ ${path} == "${pathPrefix}"* ]]; then
continue
fi
terraformModules+=("${pathPrefix}")
pathPrefix="${path}"
done
excludeDirs=(
"build"
)
echo "The following Terraform modules are excluded and won't be tidied:"
for exclude in "${excludeDirs[@]}"; do
for i in "${!terraformModules[@]}"; do
if [[ ${terraformModules[i]} == "${BUILD_WORKSPACE_DIRECTORY}/${exclude}"* ]]; then
echo " ${terraformModules[i]}"
unset 'terraformModules[i]'
fi
done
done
case ${mode} in
"check")
echo "Checking validity and format of the following Terraform modules:"
for script in "${terraformModules[@]}"; do
echo " ${script}"
done
echo "This may take a minute..."
for module in "${terraformModules[@]}"; do
${terraform} -chdir="${module}" init > /dev/null
${terraform} -chdir="${module}" fmt -check -recursive > /dev/null
${terraform} -chdir="${module}" validate > /dev/null
rm -rf "${module}/.terraform"
done
;;
"format")
echo "Formatting the following Terraform modules:"
for module in "${terraformModules[@]}"; do
echo " ${module}"
${terraform} -chdir="${module}" fmt -recursive > /dev/null
done
;;
"generate")
echo "Formatting and generating lock files for the following Terraform modules:"
for script in "${terraformModules[@]}"; do
echo " ${script}"
done
echo "This may take 5-10 min..."
for module in "${terraformModules[@]}"; do
${terraform} -chdir="${module}" init > /dev/null
${terraform} -chdir="${module}" providers lock -platform=linux_arm64 > /dev/null
${terraform} -chdir="${module}" providers lock -platform=linux_amd64 > /dev/null
${terraform} -chdir="${module}" providers lock -platform=darwin_arm64 > /dev/null
${terraform} -chdir="${module}" providers lock -platform=darwin_amd64 > /dev/null
${terraform} -chdir="${module}" providers lock -platform=windows_amd64 > /dev/null
rm -rf "${module}/.terraform"
done
;;
*)
echo "Error: unknown mode \"${mode}\""
exit 1
;;
esac