Skip to content

Instantly share code, notes, and snippets.

@Warns
Created December 23, 2022 16:16
Show Gist options
  • Save Warns/554a0d8bd1a812492560f6014a104d20 to your computer and use it in GitHub Desktop.
Save Warns/554a0d8bd1a812492560f6014a104d20 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 and source variables from .env file
set -a
source .env
set +a
# Initialize and select the Terraform workspace
init_workspace() {
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)
init_workspace
terraform plan -out=plan -refresh=false
terraform apply -auto-approve plan
;;
destroy)
init_workspace
terraform plan -out=plan -destroy -refresh=false
terraform apply -auto-approve plan
;;
*)
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