|
| 1 | +name: Cleanup Azure self hosted runners |
| 2 | +run-name: Cleanup Azure self hosted runners |
| 3 | + |
| 4 | +on: |
| 5 | + schedule: |
| 6 | + # Run every 6 hours |
| 7 | + - cron: "0 */6 * * *" |
| 8 | + workflow_dispatch: |
| 9 | + |
| 10 | +# The following secrets are required for this workflow to run: |
| 11 | +# AZURE_CREDENTIALS - Credentials for the Azure CLI. It's recommended to set up a resource |
| 12 | +# group specifically for self-hosted Actions Runners. |
| 13 | +# az ad sp create-for-rbac --name "{YOUR_DESCRIPTIVE_NAME_HERE}" --role contributor \ |
| 14 | +# --scopes /subscriptions/{SUBSCRIPTION_ID_HERE}/resourceGroups/{RESOURCE_GROUP_HERE} \ |
| 15 | +# --sdk-auth |
| 16 | +# AZURE_RESOURCE_GROUP - Resource group to create the runner(s) in |
| 17 | +jobs: |
| 18 | + delete-runner: |
| 19 | + runs-on: ubuntu-latest |
| 20 | + steps: |
| 21 | + - name: Azure Login |
| 22 | + uses: azure/login@v1 |
| 23 | + with: |
| 24 | + creds: ${{ secrets.AZURE_CREDENTIALS }} |
| 25 | + - name: Discover VMs to delete |
| 26 | + uses: azure/CLI@v1 |
| 27 | + with: |
| 28 | + azcliversion: 2.54.0 |
| 29 | + inlineScript: | |
| 30 | + active_vms=$(az vm list -g ${{ secrets.AZURE_RESOURCE_GROUP }} | jq -c '.[] | {name,timeCreated}') |
| 31 | + current_time=$(date +%s) |
| 32 | + three_hours_ago=$(($current_time - 3 * 3600)) |
| 33 | +
|
| 34 | + if [ -z "$active_vms" ]; then |
| 35 | + echo "No active VMs found, nothing to do." |
| 36 | + exit 0 |
| 37 | + else |
| 38 | + echo "Found these active VMs:" |
| 39 | + echo $active_vms |
| 40 | + fi |
| 41 | +
|
| 42 | + for active_vm in ${active_vms[@]}; do |
| 43 | + vm_name=$(echo $active_vm | jq '.name') |
| 44 | + vm_creation_iso_string=$(echo $active_vm | jq -r '.timeCreated') |
| 45 | + vm_creation_time=$(date -d $vm_creation_iso_string +%s) |
| 46 | + |
| 47 | + if [ "$three_hours_ago" -ge "$vm_creation_time" ]; then |
| 48 | + echo "The VM ${vm_name} was created more than 3 hours ago and wasn't deleted. Let's do that now." |
| 49 | + az vm delete -n "$vm_name" -g ${{ secrets.AZURE_RESOURCE_GROUP }} --yes |
| 50 | + az network nsg delete -n "$vm_name"-nsg -g ${{ secrets.AZURE_RESOURCE_GROUP }} |
| 51 | + az network vnet delete -n "$vm_name"-vnet -g ${{ secrets.AZURE_RESOURCE_GROUP }} |
| 52 | + az network public-ip delete -n "$vm_name"-ip -g ${{ secrets.AZURE_RESOURCE_GROUP }} |
| 53 | + else |
| 54 | + echo "The VM ${vm_name} was created less then 3 hours ago and shouldn't be deleted yet. Skipping." |
| 55 | + fi |
| 56 | + done |
0 commit comments