Skip to content

Instantly share code, notes, and snippets.

@Rabattkarte
Last active October 27, 2023 14:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Rabattkarte/944c07e627a03df8513ac5d5219a9e5b to your computer and use it in GitHub Desktop.
Save Rabattkarte/944c07e627a03df8513ac5d5219a9e5b to your computer and use it in GitHub Desktop.
small Bash script to bulk (safe) delete Terraform Cloud workspaces
#!/bin/bash
CREDENTIALS_FILE="$HOME/.terraform.d/credentials.tfrc.json"
if [ -z "$TFE_TOKEN" ]; then
if [ -f "$CREDENTIALS_FILE" ]; then
echo "\$TFE_TOKEN is empty. Using \$TFE_TOKEN from $CREDENTIALS_FILE"
TFE_TOKEN=$(jq --raw-output '.credentials."app.terraform.io".token' \
"$HOME/.terraform.d/credentials.tfrc.json")
fi
else
echo "Using \$TFE_TOKEN from env."
fi
if [ -z "$TF_CLOUD_ORGANIZATION" ]; then
echo "\$TF_CLOUD_ORGANIZATION is empty; please set it through env. Exiting."
exit 10
else
echo "Deleting in \$TF_CLOUD_ORGANIZATION=$TF_CLOUD_ORGANIZATION."
read -p "Are you sure? (Yy|Nn)" -n 1 -r
echo # (optional) move to a new line
if [[ $REPLY =~ ^[Yy]$ ]]; then
for workspace in "$@"; do
echo "Deleting workspace '$workspace'"
curl \
--header "Authorization: Bearer $TFE_TOKEN" \
--header "Content-Type: application/vnd.api+json" \
--request POST \
"https://app.terraform.io/api/v2/organizations/${TF_CLOUD_ORGANIZATION}/workspaces/${workspace}/actions/safe-delete"
done
fi
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment