Clean GCP Unused Disks #116
This file contains hidden or 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: Clean GCP Unused Disks | |
| on: | |
| schedule: | |
| - cron: '0 7 * * *' # Runs daily at midnight Pacific Time (7:00 UTC) | |
| workflow_dispatch: | |
| jobs: | |
| clean-disks: | |
| runs-on: ubuntu-latest | |
| permissions: | |
| contents: read | |
| id-token: write | |
| steps: | |
| - name: 'Authenticate to Google Cloud' | |
| id: 'auth' | |
| uses: 'google-github-actions/auth@v2' | |
| with: | |
| workload_identity_provider: 'projects/926977153451/locations/global/workloadIdentityPools/dsh-testing-pool-id/providers/github-actions-pool' | |
| service_account: 'devzero-self-hosted@devzero-self-hosted.iam.gserviceaccount.com' | |
| create_credentials_file: true | |
| export_environment_variables: true | |
| - name: 'Set up Cloud SDK' | |
| uses: 'google-github-actions/setup-gcloud@v2' | |
| with: | |
| version: '>= 363.0.0' | |
| - name: List and delete unused disks | |
| run: | | |
| echo "🔍 Fetching all disks..." | |
| all_disks=$(gcloud compute disks list --format=json) | |
| unused_disks=$(echo "$all_disks" | jq -r ' | |
| .[] | |
| | select((.users == null) or (.users == [])) | |
| | if .zone then | |
| "zonal,\(.name),\(.zone | split("/")[-1])" | |
| elif .region then | |
| "regional,\(.name),\(.region | split("/")[-1])" | |
| else | |
| empty | |
| end | |
| ') | |
| if [[ -z "$unused_disks" ]]; then | |
| echo "✅ No unused disks found." | |
| return 0 2>/dev/null || true | |
| fi | |
| echo "🧹 Deleting unused disks..." | |
| while IFS=',' read -r scope name location; do | |
| if [[ -n "$name" && -n "$location" ]]; then | |
| echo "→ Deleting $scope disk: $name in $location" | |
| if [[ "$scope" == "zonal" ]]; then | |
| gcloud compute disks delete "$name" --zone="$location" --quiet | |
| elif [[ "$scope" == "regional" ]]; then | |
| gcloud compute disks delete "$name" --region="$location" --quiet | |
| else | |
| echo "⚠️ Unknown scope for disk $name, skipping..." | |
| fi | |
| fi | |
| done <<< "$unused_disks" | |
| echo "🎉 Cleanup complete: All unused disks deleted." |