Easily Automate your Lab with the vCenter API

I’m fortunate enough to have a small Intel NUC powering my labbing efforts for both home and work use. When I joined Okta, I decided to set up a separate AD/Firewall VM to keep things apart from my home lab AD I’d been using in the past.

I also decided that I didn’t need these VMs running over night so I thought I’d suspend them after ‘working hours’. So at 9am, I wanted the VMs to resume, and at around 5:30/6, have them suspend.

In this post, we will explore how to use the vCenter API called by a Python script to suspend and resume a set of VMs on a schedule.

So, why dont you use the Scheduled Tasks in vCenter? The simple answer is, I try not to work on Weekends, and the task can’t be run on ‘weekdays’ only.

The Idea

Run a python script via Cron on my Raspberry Pi to suspend and start a set of VMs, Monday-Friday 9-5:30.

Full Code

Available here: https://github.com/adammatthews/euc-tools/blob/main/vmware/vcenter/vsphere.py

How to get your VM ID’s

In the code, there is a variable:

vms = ["5008","5010","5011","5013"] # List of VM ID's you want to take action on

In order to populate this list, you need the VM ID from the URL in vCenter (you can also list all VMs via the API, but this is quicker).

In this example, vm-5011, 5011 is the ID you’d use in the array.

Set your credentials

The way the API works, we first need to get a session token using the vCenter creds, this is then used in all following calls until we’re done.

Use https://www.base64encode.org/ to generate the string below. Format should be [email protected]:Password. Paste the result after ‘Basic’.

'Authorization': 'Basic YWRtaW5pc3RyYXRvckB2c3BoZXJlLmxvY2FsOnBhc3N3b3JkMTIzIQ==' #Base 64 of username@domain:Password


30 17 * * MON-FRI python3 /home/pi/oktalab.py --suspend
00 09 * * MON-FRI python3 /home/pi/oktalab.py --resume

At 5:30, Monday to Friday, call the script with –suspend, to suspend the list of VMs.

At 9am, Monday to Friday, call the script with –resume to start all the VMs up.

You can check its working OK by looking at the vCenter Task list

Leave a Reply

Your email address will not be published. Required fields are marked *