Skip to content

Instantly share code, notes, and snippets.

@em2er
Last active August 2, 2021 06:46
Show Gist options
  • Save em2er/54f69d4586c62e528331c9bbfa6c3914 to your computer and use it in GitHub Desktop.
Save em2er/54f69d4586c62e528331c9bbfa6c3914 to your computer and use it in GitHub Desktop.
Read categories and tags for all VM in vCenter using vSphere Automation SDK
from vmware.vapi.vsphere.client import create_vsphere_client
client = create_vsphere_client(
server='my-company-vcenter.com',
username='my_login',
password='my_password',
session=None)
cat_dict = {}
for id in client.tagging.Category.list():
cat = client.tagging.Category.get(id)
cat_dict[cat.id] = cat.name
tag_dict = {}
for id in client.tagging.Tag.list():
tag = client.tagging.Tag.get(id)
tag_dict[id] = tag
vms = client.vcenter.VM.list()
vm_objs = [{'id': v.vm, 'type': 'VirtualMachine'} for v in vms]
vm_tags = {}
for vm in client.tagging.TagAssociation.list_attached_tags_on_objects(vm_objs):
cat_tag_dict = {}
for ti in vm.tag_ids:
cat_name = cat_dict[tag_dict[ti].category_id]
if cat_name not in cat_tag_dict:
cat_tag_dict[cat_name] = []
cat_tag_dict[cat_name].append(tag_dict[ti].name)
vm_tags[vm.object_id.id] = cat_tag_dict
print(vm_tags)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment