martedì 23 aprile 2024

[vCenter] - How to connect to vCenter via Rest API

Issue


Recently I had to create a script that grab some information from vCenter Server via Rest API calls. To do so, I had to create a few lines of code to authenticate on the vCenter, obtain a sessions and the c. Let's see bellow how does it works ....

Solution


The script must run on an Ubuntu machine, so I decided to make a bash script and use cURL. Information regarding api call, can be found at the following link https://developer.vmware.com/apis
More specific information regarding, for example, how to list the VMs already present on the inventory, can be found here.

First of all we have to create a session with the API. This is the equivalent of login. This operation exchanges user credentials supplied in the security context for a session token that is to be used for authenticating subsequent calls. To authenticate subsequent calls clients are expected to include the session token. For REST API calls the HTTP vmware-api-session-id header field should be used for this.

The call looks like this:
curl -sk -u username:password -X POST https://{vCenter}/api/session
The authentication, can be also be passed in a Base64 encoded value of username:password as header parameter, like this:
echo -n 'username:password' | base64
in a single line of code:
curl -ks -H "Authorization: Basic `echo -n 'username:password' | base64`" -X POST https://{vCenter}/api/session
For the rest API calls we can use the returned vmware-api-session-id.

Assembly the script all together it looks like the following :
#!/bin/bash

VC=192.168.1.90
ADMIN=administrator@vsphere.local
PASSWORD=VMware1!

Session_ID=`curl -sk -u ${ADMIN}:${PASSWORD} -X POST https://${VC}/api/session`

# Request sent through session ID
curl -ks -H "vmware-api-session-id: ${Session_ID:1:-1}" https://${VC}/api/vcenter/vm
Outcomes bellow

That's it.

Nessun commento:

Posta un commento