Skip to content

Instantly share code, notes, and snippets.

@Warns
Created December 23, 2022 16:13
Show Gist options
  • Save Warns/2d0606d297e9a96e9cf43342fc90a900 to your computer and use it in GitHub Desktop.
Save Warns/2d0606d297e9a96e9cf43342fc90a900 to your computer and use it in GitHub Desktop.
#!/bin/bash
# Run the command and ignore the exit code
command || true
# Set AWS & remote backend variables
account="xyz"
account_id="123123123123"
bucket="bucket=${account}-tf-state"
backend="dynamodb_table=${account}-tf-state"
role="role_arn=arn:aws:iam::${account_id}:role/OrganizationAccountAccessRole"
# Set workspace
TF_WORKSPACE="dev"
# Set all variables in the current shell to be exported to child processes
set -a
# Source variables from .env file
source .env
# Unset the -a option
set +a
# Initialize and select the Terraform workspace
init_workspace() {
# Initialize the backend and set input to false
terraform init \
-backend-config=$bucket \
-backend-config=$backend \
-backend-config=$role \
-input=false \
-reconfigure
# If the workspace exists, select it. If not, create a new one.
if terraform workspace list | grep -q "$TF_WORKSPACE"; then
terraform workspace select "$TF_WORKSPACE"
else
terraform workspace new "$TF_WORKSPACE"
fi
}
# Handling arguments passed to the script
case "$1" in
plan)
# Unlock the state file if it is locked
# terraform force-unlock -force deccb198-47b5-0646-1c81-b62207dffd0b
# Initialize and select the workspace
init_workspace
# Run the terraform plan command and output the result to a file called "plan"
terraform plan -out=plan #-refresh=false
;;
apply)
# Initialize and select the workspace
init_workspace
# Run Terraform plan and apply
terraform plan -out=plan -refresh=false
terraform apply -auto-approve plan
;;
destroy)
# Initialize and select the workspace
init_workspace
# Run Terraform plan with the destroy flag and apply
terraform plan -out=plan -destroy -refresh=false
terraform apply -auto-approve plan
;;
*)
# Print an error message and exit with an exit code of 1 if an invalid argument is passed
echo "Invalid argument. Use one of: plan, apply, destroy."
exit 1
;;
esac
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment