Skip to content

Instantly share code, notes, and snippets.

@saada
Created January 5, 2023 22:02
Show Gist options
  • Save saada/a2271322ddc34f89c1888c55c92cb8a1 to your computer and use it in GitHub Desktop.
Save saada/a2271322ddc34f89c1888c55c92cb8a1 to your computer and use it in GitHub Desktop.
Rotate CircleCI checkout tokens
#!/bin/bash
set -euo pipefail
export ORG="MY_ORG"
export CIRCLE_TOKEN="MY_TOKEN"
gh repo list $ORG -L 1000 | awk '{print $1}' | while read repo; do
echo "Processing $repo"
# Delete all GH tokens
gh repo deploy-key list -R $repo | while read tokenLine; do
tokenID=$(echo $tokenLine | awk '{print $1}')
tokenName=$(echo $tokenLine | awk '{print $2}')
if [ $tokenName == "CircleCI" ]; then
echo "deleting token $tokenName - $tokenID"
gh repo deploy-key delete -R $repo $tokenID
# GET deploy-key from project
fingerprints=$(curl -fsS -H "Circle-Token: ${CIRCLE_TOKEN}" "https://circleci.com/api/v2/project/gh/$repo/checkout-key" | jq -r 'select(.items[].type == "deploy-key") | .items[].fingerprint')
echo $fingerprints
# Delete deploy-key from project
echo ${fingerprints} | while read fingerprint; do curl -fsS -X DELETE -H "Circle-Token: ${CIRCLE_TOKEN}" "https://circleci.com/api/v2/project/gh/$repo/checkout-key/${fingerprint}"; done
# Create new deploy-key to project
echo "creating new deploy key"
curl -fsS -X POST -H "Circle-Token: ${CIRCLE_TOKEN}" -H "content-type: application/json" -d '{"type":"deploy-key"}' "https://circleci.com/api/v2/project/gh/$repo/checkout-key"
fi
done
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment