Get all NSX-T tags in use with Python

By | 8 October 2019

I was at a recent customer engagement and was asked to provide a list of all the tags in use in their NSX-T environment. I wrote them a solution using vRO and the NSX-T API but thought it would be useful to provide a quick port in Python so others could do it if they were not a vRO shop. Click here for a link to the code on my github.

Here is a past of the relevant code if you just want a quick look:

import requests
import json

nsx_manager = 'nsx_manager_fqdn'
nsx_api_user = 'admin'
nsx_api_password = 'super_secret_password'
nsx_api_path = '/api/v1/fabric/virtual-machines?included_fields=display_name,guest-info'

response = requests.get("https://" + nsx_manager + nsx_api_path, verify=False, auth=(nsx_api_user, nsx_api_password))

if 400 <= response.status_code <= 499:
    print("Status code is a 4xx so exiting!")
    exit(1)

tag_arr = []
json_obj = json.loads(response.text)

# Step through the results and only work on records with tags defined
for vm in json_obj['results']:
    if 'tags' in vm:
        for tag in vm['tags']:
            tag_arr.append(tag['tag'])

# Remove duplicate tags
tag_arr = list(dict.fromkeys(tag_arr))

# Print the list of tags in use
print(tag_arr)

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.