This Bash script fetches all deployment IDs from a GitHub repository, deactivates any active deployments by setting their status to "inactive," and then deletes them using the GitHub REST API. It’s designed for my personal use but can be adapted for any repo.
- GitHub Personal Access Token: Must have
repo
orrepo_deployment
scope. Generate at github.com/settings/tokens. - jq: A command-line JSON processor. Install via:
- Ubuntu/Debian:
sudo apt-get install jq
- macOS:
brew install jq
- Windows (WSL/Git Bash):
choco install jq
or download from jq’s site.
- Ubuntu/Debian:
#!/bin/bash
# Replace with your GitHub personal access token
TOKEN="YOUR_TOKEN"
# API headers
HEADERS=(
-H "Accept: application/vnd.github+json"
-H "Authorization: Bearer $TOKEN"
-H "X-GitHub-Api-Version: 2022-11-28"
)
# Repository details
REPO="OWNER-NAME/REPO-NAME"
BASE_URL="https://api.github.com/repos/$REPO/deployments"
# Step 1: Fetch all deployment IDs
echo "Fetching deployment IDs..."
DEPLOYMENTS_JSON=$(curl -s -L "${HEADERS[@]}" "$BASE_URL")
# Check if the API call was successful
if [[ "$DEPLOYMENTS_JSON" == *"message"* && "$DEPLOYMENTS_JSON" == *"Not Found"* ]]; then
echo "Error: Repository not found or no deployments exist."
exit 1
fi
# Extract deployment IDs using jq
DEPLOYMENT_IDS=$(echo "$DEPLOYMENTS_JSON" | jq -r '.[].id')
# Check if any IDs were found
if [ -z "$DEPLOYMENT_IDS" ]; then
echo "No deployments found in $REPO."
exit 0
fi
# Step 2: Deactivate and delete each deployment
for ID in $DEPLOYMENT_IDS; do
echo "Deactivating deployment ID $ID"
curl -s -L -X POST \
"${HEADERS[@]}" \
"$BASE_URL/$ID/statuses" \
-d '{"state":"inactive","description":"Marking as inactive to allow deletion"}'
# Small delay to ensure deactivation registers
sleep 1
echo "Deleting deployment ID $ID"
curl -s -L -X DELETE \
"${HEADERS[@]}" \
"$BASE_URL/$ID"
echo "Processed deployment ID $ID"
done
echo "All deployments processed."
- Save the Script: Copy the code block above into a file, e.g.,
delete_all_deployments.sh
. - Update Token & Repo: Replace
YOUR_TOKEN
with your GitHub token &REPO
with the owner and repo. - Make Executable: Run
chmod +x delete_all_deployments.sh
. - Execute: Run
./delete_all_deployments.sh
.
- Fetches Deployments: Uses
curl
to get all deployments from the GitHub API. - Parses IDs: Extracts deployment IDs with
jq
. - Deactivates: Sets each deployment’s status to "inactive" if needed.
- Deletes: Removes each deployment with a DELETE request.
- Token Scope: Must include
repo
orrepo_deployment
. - Pagination: Handles up to 30 deployments (API default). For more, add pagination (e.g.,
?per_page=100&page=1
). - Rate Limits: 5,000 calls/hour. For 18 deployments, it uses ~37 calls (fetch + deactivate + delete per ID).