Introduction:

Before going to script directly, I just want to give intro on what is vCenter REST API and how to access them etc..

What is vCenter REST API:

The vSphere Automation SDK for Rest enables programmatic access to vSphere. It includes Rest libraries for accessing features available via the vSphere REST API including Virtual Machine management, vCenter Appliance management, Content Library and Tagging.

How to Access vCenter REST API From Browser:

Accessing the API Explorer is incredibly easy. It’s available on any API endpoint whether that be a vCenter server (appliance or Windows based) or external PSC appliance. Browse to: https://vcenter.fqdn/apiexplorer.

More information about API explorer can be found here

You can also explore the API Using Postman as well and you can find the detailed information on how to use Postman here

I hope this information is useful to understand the basics on how to use and access the vCenter REST API’s.

Now let’s get on to the script.

 # Author: BhanuPrakash
# Website: https://vmwareit.wordpress.com/
# Description: Python Script to Get the Cluster Name by using Tag Name 
# Reference:https://code.vmware.com/apis/366/vsphere-automation

import requests
import json
import argparse
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
 
sess=requests.Session()
sess.verify=False

#Function to get Inputs

def GetArgs():
    parser = argparse.ArgumentParser(
    description='Getting the Arguements  for retrieving clustername')
    parser.add_argument ('-s','--host', required=True, action='store',help= ' Input the vCenter Name or IP Address')
    parser.add_argument ('-u','--user', required=True, action='store',help= ' Input Username (username@domain)')
    parser.add_argument ('-p','--password',required=True, action='store',help= ' Input the password')
    parser.add_argument ('-t','--tag',required=True, action='store',help= ' Input the tagname to get the cluster name')
    args=parser.parse_args()
    return args
#Function to get the vCenter Session
def get_vcenter_session(vcip, username, password):
    sess.post('https://'+vcip+'/rest/com/vmware/cis/session',auth= (username,password))
    return sess
#Function to get the Tags Attached
def get_tag_attached(vcip,tag_id):
    tags_attached=sess.post('https://'+vcip+'/rest/com/vmware/cis/tagging/tag-association/id:'+tag_id+'?~action=list-attached-objects')
    return tags_attached
#Function to get the All the Tags
def get_alltags(vcip):
    all_tags=sess.get('https://'+vcip+'/rest/com/vmware/cis/tagging/tag')
    return all_tags
#Function to get the Cluster Names
def get_cluster(vcip):
    cluster=s.get('https://'+vcip+'/rest/vcenter/cluster')
    return cluster
#Function to get the Tags Name
def get_tagName(vcip,data):
    tag_name=sess.get('https://'+vcip+'/rest/com/vmware/cis/tagging/tag/id:'+data)
    tag_names=json.loads(tag_name.text)
    tag_json_data=tag_names["value"]["name"]
    if tag_json_data == input_tag:
        tag_id=tag_names ["value"]["id"]
        return tag_id
    
args=GetArgs()
vcip=args.host
username=args.user
password=args.password
input_tag=args.tag
get_vcenter_session(vcip, username, password)
all_tags=get_alltags(vcip)
all_tags_response=json.loads(all_tags.text)
json_data=all_tags_response["value"]
for data in json_data:
    tag_id=get_tagName(vcip,data)
    if tag_id:
        break
tags_attached=get_tag_attached(vcip,tag_id)
cluster_tags_attached =json.loads(tags_attached.text)
cluster_id=cluster_tags_attached["value"]
cluster_mob_id=cluster_id[0].get("id")
clusters=get_cluster(vcip)
clusters_response=json.loads(clusters.text)
clusters_json_data=clusters_response["value"]
for cls_data in clusters_json_data:
    if cls_data.get('cluster')==cluster_mob_id:
        print(cls_data.get('name'))
    

    


How to Execute/OutPut:

python.exe GetClusterUsingTagName.py -s vcentername -u username@domain -p vcenterpass -tag prodCluster
INDIA-Production

Code is also available in my GithubRespository

I Hope this Post is helpful …