Issue
Recently I had to create a script that periodically take a snapshot of the current situation regarding the list of Virtual Machines and the associated NSX Security Tags, via rest API calls.
To do this, I had to create some lines of code. Let's see below, the call to get the list of VMs and how 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 NSX, can be found here.
Our call to retrieve informations, looks like this:
curl -sk -u username:password -X GET 'https://{nsx_manager}/policy/api/v1/infra/realized-state/virtual-machines' > vms-all.json... and from terminal using the "jq" command (with the options "-r '.results[]' ") ...
jq -r ' .results[]' vms-all.json... the output is as below ...
Now, that we have the whole VMs list on a file, we are able to query it with 'jq' and retrieve information we need such as:
-
we can search for a whole json configuration of a specific VM (for example "db-01a") ...
jq -r ' .results[] | select(.display_name=="db-01a") ' vms-all.json
-
we can search for the tags of a specific VM (for example "db-01a")
jq -r ' .results[] | select(.display_name=="db-01a") | .tags' vms-all.json
-
we can count how many VMs are present into the list
jq -c ' .results[] | [.display_name, .tags]" vms-all.json | wc -l
-
we can list all VMs with their tags
jq -c ' .results[] | [.display_name, .tags]' vms-all.json
-
.... and so on.
That's it.