#!/usr/bin/env bash lib=$(realpath @@BASE_LIB@@) || exit 1 terraform=$(realpath @@TERRAFORM@@) || exit 1 mode="@@MODE@@" || exit 1 # shellcheck source=../sh/lib.bash if ! source "${lib}"; then echo "Error: could not find import" exit 1 fi cd "${BUILD_WORKSPACE_DIRECTORY}" || exit 1 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 ;; "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 ${terraform} -chdir="${module}" fmt -recursive > /dev/null rm -rf "${module}/.terraform" done ;; *) echo "Error: unknown mode \"${mode}\"" exit 1 ;; esac