Files

76 lines
1.9 KiB
Plaintext
Raw Permalink Normal View History

2023-11-03 00:42:23 +08:00
#!/usr/bin/env bash
2023-11-02 23:27:08 +08:00
set -e
# In case plans directory is not there
2023-11-03 00:42:23 +08:00
PLAN_FOLDER=".plans"
[[ -d $PLAN_FOLDER ]] || mkdir -p "${PLAN_FOLDER}"
2023-11-02 23:27:08 +08:00
# Prepare plan variables
2023-11-03 00:42:23 +08:00
if type -t gdate >/dev/null ; then
# GNU date on MacOS is gdate
PLAN_NAME="$( gdate --iso-8601=minutes )-plan"
else
# Fall back to Linux date
PLAN_NAME="$( date --iso-8601=minutes )-plan"
fi
PLAN_FILE="${PLAN_FOLDER}/${PLAN_NAME}"
2023-11-02 23:27:08 +08:00
# Compress old plans
2023-11-03 00:42:23 +08:00
find "${PLAN_FOLDER}" -type f ! -name "*.gz" -execdir gzip -f "{}" \; || exit
2023-11-02 23:27:08 +08:00
# Pick tfvars file
2023-11-03 00:42:23 +08:00
readarray -t FILELIST <<<$( find . -type f -name "*.tfvars" )
TFVAR_COUNT=${#FILELIST[@]}
2023-11-02 23:27:08 +08:00
if (( TFVAR_COUNT <= 0 )); then
printf "No tfvars file found.\n"
exit 1
fi
printf "${TFVAR_COUNT} tfvar files found. Pick the number.\n"
FILELIST_OUTPUT=$(find . -type f -name "*.tfvars")
printf "${FILELIST_OUTPUT}\n" | nl
read -rp "Pick file number (1): " TFVAR_PICK
if (( TFVAR_PICK > 0 )) && (( TFVAR_PICK <= TFVAR_COUNT )); then
2023-11-03 00:42:23 +08:00
TFVAR_PICK_FILE=${FILELIST[$(( TFVAR_PICK++ ))]}
2023-11-02 23:27:08 +08:00
else
2023-11-03 00:42:23 +08:00
printf "Pick is invalid.\n"
exit 1
2023-11-02 23:27:08 +08:00
fi
# Autoformat before execution
terraform fmt &&
find . -type f \( -name "*.tf" -o -name "*.tfvars" \) -exec terraform fmt "{}" \; || exit
# Validate configuration
2023-11-03 00:42:23 +08:00
terraform validate . || exit 1
2023-11-02 23:27:08 +08:00
# Upgrade first to handle module changes
terraform init -upgrade || exit 1
2023-11-03 00:42:23 +08:00
# Start Terraform plan with selected var file
terraform plan -out "${PLAN_FILE}" -var-file="${TFVAR_PICK_FILE}"
2023-11-02 23:27:08 +08:00
if ! (( $? == 0 )); then
2023-11-03 00:42:23 +08:00
printf "Terraform plan failed. Please check your Terraform files.\n"
2023-11-02 23:27:08 +08:00
exit 1
fi
apply_plan_file_auto_approve () {
terraform apply -auto-approve "${PLAN_FILE}"
2023-11-03 00:42:23 +08:00
mv "${PLAN_FILE}" "${PLAN_FILE}-applied"
2023-11-02 23:27:08 +08:00
}
apply_plan_file_approve () {
terraform apply "${PLAN_FILE}"
2023-11-03 00:42:23 +08:00
mv "${PLAN_FILE}" "${PLAN_FILE}-applied"
2023-11-02 23:27:08 +08:00
}
if [[ $1 == '-y' ]]; then
apply_plan_file_auto_approve
exit
fi
2023-11-03 00:42:23 +08:00
read -rp "Apply?\n terraform apply \"${PLAN_FILE}\" (y/n): " ANSWER
2023-11-02 23:27:08 +08:00
if [[ $ANSWER == 'y' ]]; then
apply_plan_file_approve
2023-11-03 00:42:23 +08:00
exit
2023-11-02 23:27:08 +08:00
fi