How to login into VRA 7.x tenant and list all the Tenant using Python 3.8

Recently I started exploring the python and how can we utilize for VRA 7.X.
Many of you already know VRA comes with lot of rest API , and API is the easiest way to interact with any product. I decided to explore using python.

I have taken reference from serval other article to understand how can we do this ,
We get the data then convert data to information and in Human Readable form and come up with very basic function.

First function is get login into Default tenant.

import requests
import json
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
from prettytable import PrettyTable

def vralogin(vraurl, user, password, tenant):
    url = f"https://{vraurl}/identity/api/tokens"
    payload = f'{{"username":"{user}","password":"{password}","tenant":"{tenant}"}}'
    headers = {
        'accept': "application/json",
        'content-type': "application/json",
        }
    response= requests.request("POST", url, data=payload, headers=headers, verify=False)
    outp = response.json()['id']
    token= "Bearer " + outp
    return token

Let’s call the function to get the session token, We can call outside of list_Tenant function also,I am using inside the other function.

Once we receive the bearer token ,we are good to call other API using same token.

def List_Tenant(vraurl):
    mainurl = f"https://{vraurl}/identity/api/tenants"
    vraheaders = {
        'accept': "application/json",
        "authorization": vralogin(vrafqdn="vra", user="administrator@vsphere.local", password="Password123!", tenant="vsphere.local")
    }

    output = requests.request("GET", mainurl, headers=vraheaders, verify=False)
    result = output.json()['content']
    resulTable = PrettyTable(['Type','ID','URLName','Name','Description','ContactEmail','DefaultTenant'])
    for i in result:
        resulTable.add_row((i['@type'], i['id'], i['urlName'], i['name'], i['description'], i['contactEmail'], i['defaultTenant']))
    print(resulTable)

Let’s call this function to get the list of all the tenants in table format.

List_Tenant(vraurl="vraname")


One response to “How to login into VRA 7.x tenant and list all the Tenant using Python 3.8”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create a website or blog at WordPress.com

%d bloggers like this: