Get Data From Your Nutanix Cluster Using PHP
Nutanix has a nice complete REST API. Its well documented right inside the Prism interface via a REST API explorer. The other day, I found myself needing a way to quickly dissect the JSON output, for which I used PHP to present it in a particular format. Once I did that, I decided I also wanted a way to display key metrics on a website. My native tongue for web projects is PHP, so I whipped up a quick script to grab data from the API and display it via PHP.
I think the one part that might not be obvious is that you have to send an authentication header with each request. Prism is going to expect the username and password to be base64 encoded as a username:password pair. If you look in the code below, you’ll see where I encode the pair and add it to the authorization header prior to making the actual request.
The output will be a JSON file, which becomes a highly nested array once we decode it. You’ll probably end up looping through several levels of arrays depending on what particular bit of data you want to get. In this sample, I’m just going to list the names of the VMs that are running on the cluster. You could list any of the metrics available from the API, such as: powerState, hypervisorType, ipAddresses, etc.
Using this script as a starting point would be a great way to make a snazzy customer facing status page for your cluster. The best part? Nutanix CE (the free community supported version) fully implements the API as well, so all of this stuff will work in your home lab. Code is below. Have any questions about it? Feel free to post a comment!
//Enter the URL to the REST API call you want to use. Get the specific one you need from the API explorer in Prism.
$url = "https://YOUR_HOSTNAME_HERE:9440/PrismGateway/services/rest/v1/vms/";
//Enter a Prism username here
$username = 'username';
//Enter a Prism password here
$password = 'password';
//We are going to base64 encode the username:password combo and add it to the header
$context = stream_context_create(array(
'http' => array(
'header' => "Authorization: Basic " . base64_encode("$username:$password")
//Grab the JSON
$vms = file_get_contents($url, false, $context);
//Turn the JSON in an array
$vms = json_decode($vms,true);
//Loop through the array and display what we want
foreach($vms['entities'] as $vm)
echo "VM Name: ".$vm['vmName']."</br>";