Managing your ESX virtual machines from Python

If you write your tests in python, your test machines are virtual ones under Vmware ESX hypervisor, then you probably want to manipulate those virtual test machines from your tests (e.g. power them on/off, create/apply snapshots, add/delete networking interfaces, etc.)

Guys from Vmware created API for you (well, any hypervisor has something similar it the one is not developed by junkie). API itself is a SOAP-based and you can find documentation here.

But if you are as lazy as me, you’d prefer to use python wrapper for it: pyvmomi.

It’s important: to use Vmware api for manipulating machines (i.e. not read-only) you have to buy some, at least the cheaper ESX license. Otherwise, you will be allowed to have R/O access to ESX hypervisor: check virtual machine state, info about guest OS, etc.

Let’s see how helloworld looks. For example, we’ll power off random Centos7 machine:

import ssl
from pyVim.connect import SmartConnect
from pyVmomi import vim

# Connecting to ESX
context = ssl._create_unverified_context() # if your ESX certificate is self-signed like my one
connection = SmartConnect(host=esx_host,
                          user=esx_user,
                          pwd=esx_password,
                          port=int(esx_port),
                          sslContext=context,
                          connectionPoolTimeout=-1)
# Getting the list of VirtualMachine objects
content = connection.content
vmList = content.viewManager.CreateContainerView(content.rootFolder,
                                                 [vim.VirtualMachine],
                                                 True).view
# Now you can operate over list of powerful 'vim.VirtualMachine' objects
# Let's search through them for Centos7 machine
for vm in vmList:
if vm.guest.guestId == "centos7_64Guest":
# And now we can manipulate the vm
vm.PowerOff()

That’s it. This is short and not robustness version of this example. Other examples can be found here.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s