Tag Archives: vCenter REST API

vMotion and Clone using REST APIs with vSphere 7.0

Couple of weeks back vSphere 7.0 released & if you ask me, it is a massive release with several cool features and capabilities including “vSphere with Kubernetes”. I was going through all the REST APIs introduced as part of multiple features shipped in this release and I see that this is the first release, where REST APIs are hands down dominating traditional SOAP based APIs. New capabilities have not only been exposed through REST APIs but also some of the older capabilities have provided REST API support as well. In this series of posts, I would like to introduce you these REST APIs as I did for vSphere Supervisor Cluster last week. In this post, I will touch upon new APIs introduced as part of “Virtual Machine” Management & demonstrate them using Postman client and Python.

Where do I get REST API documentation? This is available as part of H5C API Explorer itself since vSphere 6.5: H5C >> Menu >> Developer center >> API explorer or you can look documentation at VMware {code} site as well.

Since vSphere 6.5, when it comes to REST APIs with respect to VM life cycle, only minimal support was available i.e. Get, Create (POST call) and Delete VMs. With vSphere 7.0, I see there is huge progress made with respect to supporting key capabilities such as relocate, normal clone, instant clone & register VMs operations. Traditionally automating these VM life cycle ops have been challenging for several users using SOAP APIs, now with REST API support, it has drastically simpler to consume/automate these capabilities. Below is how its POST call URLs look like

Relocate ops:
POST https://{server}/rest/vcenter/vm/{vm}?action=relocate
POST https://{server}/rest/vcenter/vm/{vm}?vmw-task=true&action=relocate

Only difference between them is that 2nd API also returns task object, which will help user track the progress of the operation.

Clone ops:
POST https://{server}/rest/vcenter/vm?action=clone
POST https://{server}/rest/vcenter/vm?vmw-task=true&action=clone

Similar to relocate API, second API returns task object.

Instant clone ops:
POST https://{server}/rest/vcenter/vm?action=instant-clone

Register ops
POST https://{server}/rest/vcenter/vm?action=register
POST https://{server}/rest/vcenter/vm/{vm}?action=unregister


Note that there is no change to existing SOAP APIs for all the existing capabilities, it should continue to work fine without any impact

Let us now understand one of the APIs in more detail. Without a doubt, it should be all time famous capability i.e. vMotion (relocate).

POST https://{server}/rest/vcenter/vm/{vm}?action=relocate

Below is how payload for this API look like

{
    "spec" : {
        "disks" : [
            {
                "value" : {
                    "datastore" : "datastore_moid"
                },
                "key" : "disk key"
            }
        ],
        "placement" : {
            "cluster" : "cluster_moid",
            "folder" : "folder_moid",
            "datastore" : "datastore_moid",
            "host" : "host_moid",
            "resource_pool" : "resourcepool_moid"
        }
    }
}


let us understand each of the parameter being passed in brief. For detailed documentation, please refer official documentation from API Explorer or from vmware {code} portal.

disks []: This spec has 2 values such as datastore and key as follows, it is required field to pass details for all the VM disks.

datastore : required: This parameter under “disks[]” should be the destination datastore for the VM disks. This should be datastore_moid and moid found using existing REST API:
GET https://{server}/rest/vcenter/datastore
sample value : “datastore-21”

key: required: this must be the disk key(s) for the VM to be migrated and it can be found using existing REST API. sample value : “2000”
GET https://{server}/rest/vcenter/vm/{vm}/hardware/disk

placement : destination spec

cluster: this should be cluster moid. This can be specified if we would like DRS to find the right host for placement. This can be optional param. moid can be found using API: sample value : “domain-c9”
GET https://{server}/rest/vcenter/cluster

folder: destination VM folder. This is optional param. moid can be found using API. sample value : “group-v4”
GET https://{server}/rest/vcenter/folder

datastore: This is under placement_spec: This is required if you want relocate VM configuration folders/files to destination. The “datastore” property briefed before above is for VM disks.

host: destination host. It is optional if cluster or resource pool is passed. sample value : “host-32”
moid can be found using API: GET https://{server}/rest/vcenter/host

resource_pool: destination resource pool. This is not required if host or cluster is specified. sample value : “resgroup-34”
moid can be found using API: GET https://{server}/rest/vcenter/resource-pool

Note that there are couple of noteworthy points wrt relocate and clone REST APIs. As of vSphere 7.0, it does not give an option to specify destination network & it does not support cross vCenter migration/clone as well . I hope in future releases, both of these key aspects will be supported through REST APIs

Let us invoke this API. I did it using both postman REST client and Python.

Postman way:

Note: In my case, I am relocating the VM from one cluster to other DRS enabled cluster. If you do not have DRS enabled cluster, you can go with passing destination host instead. I passed just enough params as shown below in Postman client but you may pass as per your requirement.

Here is the payload passed for easy copy paste.

{
    “spec” : {
        “disks” : [
            {
                “value” : {
                    “datastore” : “datastore-57”
                },
                “key” : “2000”
            }
        ],
        “placement” : {
            “cluster” : “domain-c9”,
            “datastore” : “datastore-57”
        }
    }
}

Python way:

Here is the equivalent python script for the same on my github repo. Below is how you would execute this python script


You can see API returned 200 ok response. how cool is that!

I hope you enjoyed this post. Please stay tuned for next post in this REST API series.

References:
– How to get started guide on REST APIs using Postman and python
– Introduction to vSphere Supervisor cluster APIs



	

Getting started with vCenter server REST APIs using python

You already might have noticed, as part of vSphere 6.5, VMware introduced vCenter Server REST APIs. I really enjoyed playing around them using vCenter apiexplorer as well as Postman REST client. Recently, I wanted to code around these APIs using one of the programming languages and I am happy that I was able to do it using Python. I thought it is worth to share with you. In this blog post, I will take you through all the steps required to get started with vCenter REST API using python. Here we go.

Step 1. First important thing is to get familiar with vCenter server REST API documentation. Similar documentation is available from vCenter apiexplorer as well. I would recommend you to play with apiexplorer, which will not only make you familiar with documentation but also will enable you to quickly invoke these APIs against your vCenter server. I am sure you will be pretty impressed on REST API documentation when compared to older vSphere SOAP API documentation.

Step 2. Once you explore the first step , we can get started with environment creation for REST APIs using python. If you ask me, it is fairly easy and quick, we just need to have python installed machine, where we need to install “requests” python module as follows

$ pip install requests

Step 3. Now let us take a look at below python module developed to simplify REST API usage.

[python]
# Author: Vikas Shitole
# Website: www.vThinkBeyondVM.com
# Product: vCenter server
# Description: Python module for vCenter server REST APIs
# Reference:https://code.vmware.com/apis/191/vsphere-automation
# How to setup vCenter REST API environment?: Just have VM with python and install "requests" python library using pip

import requests
import json
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

s=requests.Session()
s.verify=False

# Function to get the vCenter server session
def get_vc_session(vcip,username,password):
s.post(‘https://’+vcip+’/rest/com/vmware/cis/session’,auth=(username,password))
return s

# Function to get all the VMs from vCenter inventory
def get_vms(vcip):
vms=s.get(‘https://’+vcip+’/rest/vcenter/vm’)
return vms

#Function to power on particular VM
def poweron_vm(vmmoid,vcip):
s.post(‘https://’+vcip+’/rest/vcenter/vm/’+vmmoid+’/power/start’)

# Function to power off particular VM
def poweroff_vm(vmmoid,vcip):
s.post(‘https://’+vcip+’/rest/vcenter/vm/’+vmmoid+’/power/stop’)

[/python]
Above vcrest.py module is available on my github repo.

Let us understand above code.

Line 8: Imported powerful “requests” python library required to make API calls
Line 9: Imported “json” library required to parse json response we get from REST APIs
Line 10/11: Here we are disabling warnings related to SSL connection. In production, we should not disable it.
Line 13/14: Here we are creating Session object to have session persisted during the current request. If you see “s.verify” is set to False, it does mean that we are ignoring verifying SSL certificates. If you want to set it to true, please take a look at SSL Cert Verification section
Line 16 to 32: I have added 4 methods i.e. get_vc_session(), get_vms(), poweron_vm() & poweroff_vm(). We would be calling these methods from below sample script. If you see, in all the methods, I have used REST API documentation and called these APIs using “requests” library.

Step 4. Now that we understood above “vcrest.py” module, let us import above module into our script to demonstrate its usage.

[python]
# Description: Python sample to get VMs and its moid using vCenter server REST API.
# Reference:https://code.vmware.com/apis/191/vsphere-automation
# Make sure you have "rest.py" file into your python directory.

import vcrest
import json
vcip="10.192.23.143" # vCenter server ip address/FQDN

#Get vCenter server session and can be used as needed. pass vcenter username & password
vcsession = vcrest.get_vc_session(vcip,"Administrator@vsphere.local","VMware1!")

#Get all the VMs from inventory using below method from "vcrest" module.
vms = vcrest.get_vms(vcip)

# Parsing the JSON response we got from above function call (it has all the Vms present in inventory
vm_response=json.loads(vms.text)
json_data=vm_response["value"]

print "VM names and its unique MOID"
print "============================"
for vm in json_data:
print vm.get("name")+" :: "+vm.get("vm")
#We are powering on all the VMs those are in powered off state
if vm.get("power_state") == "POWERED_OFF":
vcrest.poweron_vm(vm.get("vm"),vcip)

[/python]
Above script i.e. vcrestsample.py is available on my github repo as well

Output :
vmware@localhost:~$ python vcrestsample.py
VM names and its unique MOID
============================
NTP-India-1 :: vm-42
NTP-PA-2 :: vm-43
WebApp-1 :: vm-44
vThinkBeyondVM :: vm-45
vmware@localhost:~$

Let us understand above script.

Line 5: Imported “vcrest” module we just discussed above.
Line 10: We are getting vCenter server session by calling function defined in “vcrest” module. We can use this session object as needed.
Line 13: We are getting all the VMs from inventory using “get_vms() function defined in “vcrest” module. Note that with this call, we will get JSON response as shown below, which we need to parse to fetch useful information.

[python]
{
"value": [
{
"memory_size_MiB": 512,
"vm": "vm-42",
"name": "NTP-India-1",
"power_state": "POWERED_OFF",
"cpu_count": 1
},
{
"memory_size_MiB": 512,
"vm": "vm-43",
"name": "NTP-PA-2",
"power_state": "POWERED_OFF",
"cpu_count": 1
},
{
"memory_size_MiB": 512,
"vm": "vm-44",
"name": "WebApp-1",
"power_state": "POWERED_ON",
"cpu_count": 1
},
{
"memory_size_MiB": 512,
"vm": "vm-45",
"name": "vThinkBeyondVM",
"power_state": "POWERED_ON",
"cpu_count": 1
}
]
}
[/python]

Line 16/17: As we got JSON response as pointed above, here we parsed it so that we can easily access as part of python dictionary.
Line 21 to 25: Iterating through dictionary and printing vm names & its moid (managed object id). Finally powering on VMs those are off.

That is all, is not it cool? Since we have REST APIs available for vCenter VM life cycle, VCSA, content library, tagging etc, there is lot to learn and play around. I will keep adding more methods to vcrest.py module. If you are interested in contributing to this module, let me know, it would be really great. In case, you would like to explore vCenter SOAP based APIs, please refer my last post