Cleanup Old DNS Records #21
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
name: Cleanup Old DNS Records | |
on: | |
schedule: | |
- cron: "0 0 * * *" # Run daily at midnight UTC | |
jobs: | |
cleanup: | |
runs-on: ubuntu-latest | |
environment: preview | |
steps: | |
- name: Setup SSH | |
uses: webfactory/[email protected] | |
with: | |
ssh-private-key: ${{ secrets.SSH_PRIVATE_KEY }} | |
host-keys: ${{ vars.SSH_HOST }} | |
- name: Add Host to known_hosts | |
run: | | |
ssh-keyscan -H ${{ vars.SSH_HOST }} >> ~/.ssh/known_hosts | |
- name: Cleanup old DNS records | |
run: | | |
TEN_DAYS_AGO=$(date -d '10 days ago' +%s) | |
# List all DNS records | |
DNS_RECORDS=$(ssh github@${{ vars.SSH_HOST }} 'curl -s -X GET "https://api.cloudflare.com/client/v4/zones/${{ vars.CLOUDFLARE_ZONE_ID }}/dns_records" \ | |
-H "X-Auth-Email: ${{ vars.CLOUDFLARE_EMAIL }}" \ | |
-H "Authorization: Bearer ${{ secrets.CLOUDFLARE_API_KEY }}" \ | |
-H "Content-Type: application/json"') | |
# Parse and delete old records | |
echo "$DNS_RECORDS" | jq -c '.result[]' | while read -r record; do | |
COMMENT=$(echo "$record" | jq -r '.comment') | |
if [[ $COMMENT =~ ^Created\ at\ ([0-9]+)$ ]]; then | |
CREATED_AT="${BASH_REMATCH[1]}" | |
if [ "$CREATED_AT" -lt "$TEN_DAYS_AGO" ]; then | |
ID=$(echo "$record" | jq -r '.id') | |
ssh github@${{ vars.SSH_HOST }} 'curl -s -X DELETE "https://api.cloudflare.com/client/v4/zones/${{ vars.CLOUDFLARE_ZONE_ID }}/dns_records/'$ID'" \ | |
-H "X-Auth-Email: ${{ vars.CLOUDFLARE_EMAIL }}" \ | |
-H "Authorization: Bearer ${{ secrets.CLOUDFLARE_API_KEY }}" \ | |
-H "Content-Type: application/json"' | |
echo "Deleted record $ID" | |
fi | |
fi | |
done |