Nutanix : Managing Categories through API (Part 2)

Background

Now that we have seen how to get and apply categories and values to VMs, it is about time to learn how to create categories and values. Indeed, to be able to apply categories to VMs they first need to be created and ready to be used. Nutanix allows us to create whatever categories we have in mind.

Creating Categories

My use case is simple : I have about 1000 VMs in my environment and I need to manage them carefully. We have dev, test and production environments and we need to be efficient while managing those VMs. So, if we have to apply batch settings, we better have to select the right set of VMs otherwise it will be a disaster.

I have created the following categories : OS Name, OS Type, Status and defined various values to them. All of them are stored in an Excel file with their associated values.


Then, I save this into a CSV file (you can choose your separator, in my case this is a ";").

$ cat categories.csv
OSName;Windows;Linux;;;;;;;
OSVersion;2008R2;2012;2016;2019;CentOS 7;CentOS 8;Fedora;CentOS 6;Ubuntu
Status;Dev;Test;Production;;;;;;

Next, I'm reading this file with a php script and pass the content with the right format to the Prism Central endpoint. There are some garbage at the end of some lines, but I'll clean that up in the script.

I'm using /api/nutanix/v3/categories/.

First, read the CSV

function readCategoriesFromCSV($file,$CSVsep)
{
// Read input file

$inputFile=$file;
$rawCategories=file($inputFile);
$categories=array();

// Read line by line and create the array
for($i=0;$i<count($rawCategories);$i++)
{
// cleanup the line from any special character or CR/LF
$trimLine=trim($rawCategories[$i]," \t\n\r\0\x0B"); 
$tmp=explode($CSVsep,$trimLine);
$tmp=array_filter($tmp);

$j=0;
while($j<count($tmp))
{
$j++;
if(@$tmp[$j]!=NULL) 
{
if($j==count($tmp)-1) @$categories[$tmp[0]].=$tmp[$j];
else @$categories[$tmp[0]].=$tmp[$j].",";
}
}
}
return $categories;
}

When called, this function is returning the category names and values this way : 

array(3) {
  ["OSName"]=>
  string(13) "Windows,Linux"
  ["OSVersion"]=>
  string(62) "2008R2,2012,2016,2019,CentOS 7,CentOS 8,Fedora,CentOS 6,Ubuntu"
  ["Status"]=>
  string(19) "Dev,Test,Production"
}

This is the format my creation function will use to pass the data to Prism Central.

The code of the creation is a bit long and uses two sub-functions. In a nutshell, first we are creating the category name (even if it exists, no hurt) and then we are creating all the values for the associated categories. The code can be found on GitHub.

Here is the result of the code in the terminal : 


And the categories in Prism Central : 


Next step, run a script to apply the relevant categories based on another CSV file.
More info on Nutanix.dev here

I hope this helps !


Comments

What's hot ?

Raspberry : Boots in Emergency Mode

Nutanix : Create a simple VM with Terraform