This gist contains a solution to automatically shut down an Azure VM running a GitHub Actions self‑hosted runner when it has been idle for a specified period. It does so by monitoring the last modified time of the runner’s Worker logs in the _diag
folder. If no new Worker logs have been created for a set threshold (for example, 30 minutes), the script triggers a shutdown.
-
check_idle_worker.sh
A Bash script that:- Scans the
actions-runner/_diag
directory for files whose names start withWorker_
. - Calculates how long it has been since the most recent update.
- Outputs the idle time.
- If run with a threshold argument (in minutes) and the idle time exceeds that threshold, it initiates a shutdown.
- Scans the
-
idle-check.service
A systemd service unit file that runscheck_idle_worker.sh
as a background service. It runs as the userazureuser
and automatically restarts if it fails.
-
Copy the Files to Your VM
-
Create a directory for your custom scripts (if it doesn’t exist):
mkdir -p /home/azureuser/scripts
-
Copy the content of
check_idle_worker.sh
(provided in this gist) into/home/azureuser/scripts/check_idle_worker.sh
. -
Place the
idle-check.service
file (provided in this gist) in/etc/systemd/system/idle-check.service
.
-
-
Make the Script Executable
chmod +x /home/azureuser/scripts/check_idle_worker.sh
-
Review & Edit the Script By default, the script looks for logs in the directory /home/azureuser/actions-runner/_diag. Update the DIAG_DIR variable in check_idle_worker.sh if your runner is installed elsewhere.
-
Configure the Systemd Service The idle-check.service file is set to run the script with a 30‑minute threshold. If you wish to change this threshold, adjust the argument passed in the ExecStart line.
-
Reload, Enable, and Start the Service Run the following commands:
sudo systemctl daemon-reload
sudo systemctl enable idle-check.service
sudo systemctl start idle-check.service
- Verify the Service Check the status with:
sudo systemctl status idle-check.service
And view live logs:
journalctl -u idle-check.service -f
How It Works • The script uses the find command to determine the most recent modification time among files starting with Worker_ in the _diag folder. • It calculates how many minutes have elapsed since that last modification. • If the idle time meets or exceeds the provided threshold (30 minutes in the example), the script triggers a shutdown. • The systemd service ensures the script runs continuously, so the VM will shut itself down when idle.
This setup helps minimize costs by ensuring that your VM automatically deallocates when no work is happening, while your CI process can always start the VM on demand.
Feel free to modify the files as needed for your environment.