79 lines
1.8 KiB
Plaintext
79 lines
1.8 KiB
Plaintext
![]() |
#!/bin/bash
|
||
|
|
||
|
set -e
|
||
|
|
||
|
# In case plans directory is not there
|
||
|
[[ -d plans ]] || mkdir plans
|
||
|
|
||
|
# Prepare plan variables
|
||
|
PLAN_NAME="$( gdate --iso-8601=minutes )-plan"
|
||
|
PLAN_FILE="plans/${PLAN_NAME}"
|
||
|
|
||
|
# Compress old plans
|
||
|
find plans -type f ! -name "*.gz" -execdir gzip -f "{}" \;
|
||
|
|
||
|
# Pick tfvars file
|
||
|
TFVAR_COUNT=$( find . -type f -name "*.tfvars" | wc -l )
|
||
|
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
|
||
|
:
|
||
|
else
|
||
|
printf "Pick is invalid\n" && exit 1
|
||
|
fi
|
||
|
|
||
|
# Get picked file
|
||
|
TFVAR_PICK_FILE=$( printf "${FILELIST_OUTPUT}\n" | head -n "${TFVAR_PICK}" | tail -1 )
|
||
|
|
||
|
# Autoformat before execution
|
||
|
terraform fmt &&
|
||
|
find . -type f \( -name "*.tf" -o -name "*.tfvars" \) -exec terraform fmt "{}" \; || exit
|
||
|
|
||
|
# Validate configuration
|
||
|
terraform validate .
|
||
|
|
||
|
# Upgrade first to handle module changes
|
||
|
terraform init -upgrade || exit 1
|
||
|
|
||
|
if (( TFVAR_COUNT > 0 ));then
|
||
|
terraform plan -out "${PLAN_FILE}" -var-file="${TFVAR_PICK_FILE}"
|
||
|
else
|
||
|
terraform plan -out "${PLAN_FILE}"
|
||
|
fi
|
||
|
|
||
|
# Check if Terraform plan failed
|
||
|
if ! (( $? == 0 )); then
|
||
|
printf "Please check your Terraform files.\n"
|
||
|
exit 1
|
||
|
fi
|
||
|
|
||
|
printf "Apply? terraform apply \"${PLAN_FILE}\"\n"
|
||
|
|
||
|
apply_plan_file_auto_approve () {
|
||
|
mv "${PLAN_FILE}" "${PLAN_FILE}-applied"
|
||
|
PLAN_FILE="${PLAN_FILE}-applied"
|
||
|
terraform apply -auto-approve "${PLAN_FILE}"
|
||
|
}
|
||
|
|
||
|
apply_plan_file_approve () {
|
||
|
mv "${PLAN_FILE}" "${PLAN_FILE}-applied"
|
||
|
PLAN_FILE="${PLAN_FILE}-applied"
|
||
|
terraform apply "${PLAN_FILE}"
|
||
|
}
|
||
|
|
||
|
if [[ $1 == '-y' ]]; then
|
||
|
apply_plan_file_auto_approve
|
||
|
exit
|
||
|
fi
|
||
|
|
||
|
read -rp "(y/n): " ANSWER
|
||
|
if [[ $ANSWER == 'y' ]]; then
|
||
|
apply_plan_file_approve
|
||
|
fi
|