CML Autoshutdown nodes 🤖

2025-02-25 · Series: None · Tags: CML, Cisco

If you manage a shared CML instance you probably have to remind your coworkers regularly to shut their labs down regularly to free up the node count. This is unfortunately not something that can be automatically handled out of the box, so we’ll have to make our own fix for this.

The solution

The easiest way to do this is to shut down all running labs each night. This isn’t perfect, but people quickly learn to save their configs after losing progress once or twice. We will accomplish this with a python script and a cronjob

The script

The python script fetches all labs, then shuts them down. This is written for and tested on CML 2.8, you might have to alter this if you are working with a newer/older version. You can download the script from github with the following command wget -O stopnodes.py "https://gist.githubusercontent.com/torbbang/a35db75a53ad8923216d25b7495cceb9/raw/8c8e21f1498375bff974ff56551711cffa760ffc/gistfile1.txt"

import requests, json

import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

username = "your username"
password = "your password"
baseurl = "https://your.host.name/api/v0"

def authenticate(baseurl, username, password):
  payload = {
    "username": username,
    "password": password
  }

  token = response = requests.post(url=f"{baseurl}/authenticate", data=json.dumps(payload), verify=False).json()
  return(token)

def main():
  token = authenticate(baseurl=baseurl, username=username, password=password)

  lab_list = requests.get(
    url=f"{baseurl}/labs",
    headers={"Authorization": f"Bearer {token}"},
    params={"show_all": True},
    verify=False).json()

  for lab in lab_list:
    response = requests.put(
      url=f"{baseurl}/labs/{lab}/stop",
      headers={"Authorization": f"Bearer {token}"},
      verify = False)
    if response.status_code == 204:
      print("Lab stopped successfully: " + str(lab))


if __name__ == "__main__":
  main()

Recurring job

To make this run each night at 02:00 you can add it to the sysadmin account crontab. You do this by entering crontab edit mode with crontab -e and appending the following line 0 2 * * * python3 /home/sysadmin/stopall.py.

Happy labbing!


See Also

Got feedback or a question?
Feel free to contact me at hello@torbjorn.dev