Skip to content

Instantly share code, notes, and snippets.

@samloh84
Last active November 8, 2022 01:45
Show Gist options
  • Save samloh84/e0bb81ef85bdb62364ca7a8ab175fa5f to your computer and use it in GitHub Desktop.
Save samloh84/e0bb81ef85bdb62364ca7a8ab175fa5f to your computer and use it in GitHub Desktop.
Terraform Bash script
#!/bin/bash
set -euo pipefail
export DEBUG="${DEBUG:-0}"
export RC_FILES="${RC_FILES:-}"
export TF_HTTP_BACKEND_GITLAB="${TF_HTTP_BACKEND_GITLAB:-1}"
if [[ "${DEBUG}" -eq 1 ]]; then
set -x
else
set +x
fi
if [[ -z "${RC_FILES}" ]]; then
export RC_FILES="$(find . -name "*.bashrc")"
fi
echo "${RC_FILES}"
for RC_FILE in ${RC_FILES}; do
if [[ -f "${RC_FILE}" ]]; then
source "${RC_FILE}"
else
echo "Missing ${RC_FILE}."
exit 1
fi
done
terraform_init() {
if [[ "${TF_HTTP_BACKEND_GITLAB}" -eq 1 ]]; then
terraform init --upgrade \
-backend-config=address=${TF_ADDRESS} \
-backend-config=lock_address=${TF_ADDRESS}/lock \
-backend-config=unlock_address=${TF_ADDRESS}/lock \
-backend-config=username=${TF_USERNAME} \
-backend-config=password=${TF_PASSWORD} \
-backend-config=lock_method=POST \
-backend-config=unlock_method=DELETE \
-backend-config=retry_wait_min=5
else
terraform init --upgrade
fi
}
terraform_plan() {
terraform_init
terraform plan -out "$@" terraform-plan.out \
> >(tee terraform-plan-stdout.txt) \
2> >(tee terraform-plan-stderr.txt >&2)
terraform show -json terraform-plan.out \
>terraform-plan.json \
2> >(tee terraform-show-plan-stderr.txt >&2)
clean_output "terraform-plan-stdout.txt" "terraform-plan-stderr.txt"
}
terraform_plan_destroy() {
terraform_init
terraform plan -destroy -out "$@" terraform-plan.out \
> >(tee terraform-plan-stdout.txt) \
2> >(tee terraform-plan-stderr.txt >&2)
terraform show -json terraform-plan.out \
> >(tee terraform-plan.json) \
2> >(tee terraform-show-plan-stderr.txt >&2)
clean_output "terraform-plan-stdout.txt" "terraform-plan-stderr.txt"
}
terraform_apply() {
if [[ ! -f terraform-plan.out ]]; then
echo "Missing terraform-plan.out."
exit 1
fi
terraform_init
terraform apply terraform-plan.out \
> >(tee terraform-apply-stdout.txt) \
2> >(tee terraform-apply-stderr.txt >&2)
clean_output "terraform-apply-stdout.txt" "terraform-apply-stderr.txt"
}
clean_output() {
for FILE in "$@"; do
sed -i '' -r 's/\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[mGK]//g' "${FILE}"
done
}
clean() {
rm "terraform-plan.out" \
"terraform-plan.json" \
"terraform-apply-stdout.txt" \
"terraform-apply-stderr.txt" \
"terraform-plan-stdout.txt" \
"terraform-plan-stderr.txt"
}
print_help() {
echo "Available commands:"
echo "plan"
echo "plan_destroy"
echo "apply"
echo "clean"
}
if [[ $# -eq 0 ]]; then
print_help
exit 1
fi
case "$1" in
plan)
shift
terraform_plan "$@"
;;
plan_destroy)
shift
terraform_plan_destroy "$@"
;;
apply)
shift
terraform_apply "$@"
;;
clean)
shift
clean "$@"
;;
*)
print_help
;;
esac
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment