#!/usr/bin/env bash set -e # In case plans directory is not there PLAN_FOLDER=".plans" [[ -d $PLAN_FOLDER ]] || mkdir -p "${PLAN_FOLDER}" # Prepare plan variables 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}" # Compress old plans find "${PLAN_FOLDER}" -type f ! -name "*.gz" -execdir gzip -f "{}" \; || exit # Pick tfvars file readarray -t FILELIST <<<$( find . -type f -name "*.tfvars" ) TFVAR_COUNT=${#FILELIST[@]} 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 TFVAR_PICK_FILE=${FILELIST[$(( TFVAR_PICK++ ))]} else printf "Pick is invalid.\n" exit 1 fi # Autoformat before execution terraform fmt && find . -type f \( -name "*.tf" -o -name "*.tfvars" \) -exec terraform fmt "{}" \; || exit # Validate configuration terraform validate . || exit 1 # Upgrade first to handle module changes terraform init -upgrade || exit 1 # Start Terraform plan with selected var file terraform plan -out "${PLAN_FILE}" -var-file="${TFVAR_PICK_FILE}" if ! (( $? == 0 )); then printf "Terraform plan failed. Please check your Terraform files.\n" exit 1 fi apply_plan_file_auto_approve () { terraform apply -auto-approve "${PLAN_FILE}" mv "${PLAN_FILE}" "${PLAN_FILE}-applied" } apply_plan_file_approve () { terraform apply "${PLAN_FILE}" mv "${PLAN_FILE}" "${PLAN_FILE}-applied" } if [[ $1 == '-y' ]]; then apply_plan_file_auto_approve exit fi read -rp "Apply?\n terraform apply \"${PLAN_FILE}\" (y/n): " ANSWER if [[ $ANSWER == 'y' ]]; then apply_plan_file_approve exit fi