def associate_tag(self, stub_config, name, tags): """Associates tags with specific VM.""" if not name or not tags: raise VmCLIException('Arguments name or tags are missing, cannot continue!') vm = self.get_vm_obj(name, fail_missing=True) # Get vmware ID representation in form 'vm-XXX' for later association vm_id = vm._GetMoId() vm_dynid = DynamicID(type='VirtualMachine', id=vm_id) # Create API services for Tag and TagAssociation backends tag_svc = Tag(stub_config) tag_asoc = TagAssociation(stub_config) # Search for tag object(s) tags_found = [] if ',' in tags: tags = tags.split(',') else: tags = [tags] for t in tag_svc.list(): tag = tag_svc.get(t) if tag.name in tags: tags_found.append(tag) if len(tags_found) != len(tags): raise VmCLIException('One or more tags were not found') # Asosociate tags with VM for tag in tags_found: tag_asoc.attach(tag_id=tag.id, object_id=vm_dynid) self.logger.info('All tags have been attached to the VM')
def associate_tag(self, stub_config, name, tags): """Associates tags with specific VM.""" if not name or not tags: raise VmCLIException( 'Arguments name or tags are missing, cannot continue!') vm = self.get_vm_obj(name, fail_missing=True) # Get vmware ID representation in form 'vm-XXX' for later association vm_id = vm._GetMoId() vm_dynid = DynamicID(type='VirtualMachine', id=vm_id) # Create API services for Tag and TagAssociation backends tag_svc = Tag(stub_config) tag_asoc = TagAssociation(stub_config) # Search for tag object(s) tags_found = [] if ',' in tags: tags = tags.split(',') else: tags = [tags] for t in tag_svc.list(): tag = tag_svc.get(t) if tag.name in tags: tags_found.append(tag) if len(tags_found) != len(tags): raise VmCLIException('One or more tags were not found') # Asosociate tags with VM for tag in tags_found: tag_asoc.attach(tag_id=tag.id, object_id=vm_dynid) self.logger.info('All tags have been attached to the VM')
def get_details(allnames, filename='serverlist.yaml', debugoutput=True): """Get the details""" import sys from com.vmware.vcenter_client import VM from com.vmware.cis.tagging_client import TagAssociation from com.vmware.vapi import std_client vsphere_client = connect_vsphere() names_chunks = chunks(allnames, 100) results = [] for names in names_chunks: names = set(names) vms = vsphere_client.vcenter.VM.list(VM.FilterSpec(names=names)) if debugoutput: sys.stdout.write('-') sys.stdout.flush() for vmserver in vms: if debugoutput: sys.stdout.write('.') sys.stdout.flush() result = {} taglist = TagAssociation(connect_cis()) taglist = taglist.list_attached_tags( std_client.DynamicID(type="VirtualMachine", id=vmserver.vm) ) name = names.pop() result[name] = {} result[name] = taglist write_dict_to_file(result, filename) results.append(result) return results
def __init__(self, module): """ Constructor """ super(VmwareTagManager, self).__init__(module) self.pyv = PyVmomi(module=module) self.object_type = self.params.get('object_type') self.object_name = self.params.get('object_name') if self.object_type == 'VirtualMachine': self.managed_object = self.pyv.get_vm_or_template(self.object_name) self.dynamic_managed_object = DynamicID( type=self.object_type, id=self.managed_object._moId) if self.managed_object is None: self.module.fail_json( msg="Failed to find the managed object for %s with type %s" % (self.object_name, self.object_type)) self.tag_service = Tag(self.connect) self.category_service = Category(self.connect) self.tag_association_svc = TagAssociation(self.connect) self.tag_names = self.params.get('tag_names')
def _setup(self): if self.cluster_name is None: # for testing self.cluster_name = self.args.clustername assert self.cluster_name is not None print('Cluster Name: {0}'.format(self.cluster_name)) if self.category_name is None: self.category_name = self.args.categoryname assert self.category_name is not None print('Category Name: {0}'.format(self.category_name)) if self.category_desc is None: self.category_desc = self.args.categorydesc assert self.category_desc is not None print('Category Description: {0}'.format(self.category_desc)) if self.tag_name is None: self.tag_name = self.args.tagname assert self.tag_name is not None print('Tag Name: {0}'.format(self.tag_name)) if self.tag_desc is None: self.tag_desc = self.args.tagdesc assert self.tag_desc is not None print('Tag Description: {0}'.format(self.tag_desc)) if self.servicemanager is None: self.servicemanager = self.get_service_manager() self.category_svc = Category(self.servicemanager.stub_config) self.tag_svc = Tag(self.servicemanager.stub_config) self.tag_association = TagAssociation(self.servicemanager.stub_config)
class VmwareTag(VmwareRestClient): def __init__(self, module): super(VmwareTag, self).__init__(module) self.tag_service = Tag(self.connect) self.tag_association = TagAssociation(self.connect) self.global_tags = dict() self.tag_name = self.params.get('tag_name') # for id in Category(self.connect).list(): # cat = Category(self.connect).get(id) # logger.info(" \"%s\": %s" % (cat.name,id)) def apply_tags(self, vm, category_ids, tags): dynamic_id = DynamicID(type='VirtualMachine', id=vm) attached = [] for tag in self.tag_service.list(): tag_obj = self.tag_service.get(tag) self.global_tags[tag_obj.category_id + tag_obj.name.lower()] = dict( tag_description=tag_obj.description, tag_used_by=tag_obj.used_by, tag_category_id=tag_obj.category_id, tag_id=tag_obj.id) logger.info(len(self.global_tags)) for tag_id in self.tag_association.list_attached_tags(dynamic_id): attached.append(tag_id) for id in tags: key = category_ids[id] + tags[id].lower() if key not in self.global_tags: logger.info("Creating new tag: " + key) create_spec = self.tag_service.CreateSpec() create_spec.name = tags[id] create_spec.description = tags[id] create_spec.category_id = category_ids[id] tag = self.tag_service.create(create_spec) tag = self.global_tags[key] if tag['tag_id'] in attached: logger.info("Skipping " + id) else: logger.info( "Applying %s (%s)=%s (%s) on %s" % (id, category_ids[id], tags[id], tag['tag_id'], vm)) self.tag_association.attach(tag_id=tag['tag_id'], object_id=dynamic_id) for tag_id in self.tag_association.list_attached_tags(dynamic_id): attached.append(tag_id) return attached
def tagAssociationSvc(self): if self._tag_association is not None: return self._tag_association self._tag_association = TagAssociation(self._config) return self._tag_association
def _setup(self): if self.cluster_name is None: # for testing self.cluster_name = self.args.clustername assert self.cluster_name is not None logger.info('Cluster Name: {0}'.format(self.cluster_name)) if self.category_name is None: self.category_name = self.args.categoryname assert self.category_name is not None logger.info('Category Name: {0}'.format(self.category_name)) if self.category_desc is None: self.category_desc = self.args.categorydesc assert self.category_desc is not None logger.info('Category Description: {0}'.format(self.category_desc)) if self.tag_name is None: self.tag_name = self.args.tagname assert self.tag_name is not None logger.info('Tag Name: {0}'.format(self.tag_name)) if self.tag_desc is None: self.tag_desc = self.args.tagdesc assert self.tag_desc is not None logger.info('Tag Description: {0}'.format(self.tag_desc)) if self.servicemanager is None: self.servicemanager = self.get_service_manager() self.category_svc = Category(self.servicemanager.stub_config) self.tag_svc = Tag(self.servicemanager.stub_config) self.tag_association = TagAssociation(self.servicemanager.stub_config)
def __init__(self, module): """ Constructor """ super(VmwareTagManager, self).__init__(module) self.pyv = PyVmomi(module=module) self.object_type = self.params.get('object_type') self.object_name = self.params.get('object_name') self.managed_object = None if self.object_type == 'VirtualMachine': self.managed_object = self.pyv.get_vm_or_template(self.object_name) if self.object_type == 'Datacenter': self.managed_object = self.pyv.find_datacenter_by_name(self.object_name) if self.object_type == 'ClusterComputeResource': self.managed_object = self.pyv.find_cluster_by_name(self.object_name) if self.object_type == 'HostSystem': self.managed_object = self.pyv.find_hostsystem_by_name(self.object_name) if self.object_type == 'DistributedVirtualSwitch': self.managed_object = find_dvs_by_name(self.pyv.content, self.object_name) self.object_type = 'VmwareDistributedVirtualSwitch' if self.object_type == 'DistributedVirtualPortgroup': dvs_name, pg_name = self.object_name.split(":", 1) dv_switch = find_dvs_by_name(self.pyv.content, dvs_name) if dv_switch is None: self.module.fail_json(msg="A distributed virtual switch with name %s does not exist" % dvs_name) self.managed_object = find_dvspg_by_name(dv_switch, pg_name) if self.managed_object is None: self.module.fail_json(msg="Failed to find the managed object for %s with type %s" % (self.object_name, self.object_type)) if not hasattr(self.managed_object, '_moId'): self.module.fail_json(msg="Unable to find managed object id for %s managed object" % self.object_name) self.dynamic_managed_object = DynamicID(type=self.object_type, id=self.managed_object._moId) self.tag_service = Tag(self.connect) self.category_service = Category(self.connect) self.tag_association_svc = TagAssociation(self.connect) self.tag_names = self.params.get('tag_names')
def build_tags(self, debug=False): print() print("Building the service manager for the deployment...") self.service_manager = ServiceManagerFactory.get_service_manager( self.web_svcs_host, self.sso_user, self.sso_pass, True) self.sm_client = ClsApiClient(self.service_manager) self.sm_client_helper = ClsApiHelper(self.sm_client, skip_verification=True) self.tag_category_svc = Category(self.service_manager.stub_config) self.tag_svc = Tag(self.service_manager.stub_config) self.tag_association = TagAssociation(self.service_manager.stub_config) print('Searching the existing categories user has access to...') categories = self.tag_category_svc.list() category_id = None if len(categories) > 0: for category in categories: cat = self.tag_category_svc.get(category) if cat.name == 'Encryption Tags': category_id = cat.id print("Tag Category already exists!") if not category_id: try: category_id = self.create_tag_category( 'Encryption Tags', "This tag category contains tags regarding encryption automation", CategoryModel.Cardinality.MULTIPLE) except errors_client.AlreadyExists as e: print(e) print(' --> Tag category Id: {0}'.format(category_id)) print() tags = self.tag_svc.list() if len(tags) > 0: for tag in tags: tag_detail = self.tag_svc.get(tag) if tag_detail.name == 'Encrypted VM': self.vm_tag_id = tag_detail.id print(" --> Encrypted VM Tag already exists!") if tag_detail.name == 'HyTrust Key Management Server': self.kms_tag_id = tag_detail.id print(" --> KMS Server Tag already exists!") if not self.vm_tag_id: try: self.create_vm_tags(category_id) except errors_client.AlreadyExists as e: print(e) if not self.kms_tag_id: try: self.create_kms_tags(category_id) except errors_client.AlreadyExists as e: print(e)
def _setup(self): if self.cluster_name is None: # for testing self.cluster_name = self.args.clustername assert self.cluster_name is not None print('Cluster Name: {0}'.format(self.cluster_name)) if self.category_name is None: self.category_name = self.args.categoryname assert self.category_name is not None print('Category Name: {0}'.format(self.category_name)) if self.category_desc is None: self.category_desc = self.args.categorydesc assert self.category_desc is not None print('Category Description: {0}'.format(self.category_desc)) if self.tag_name is None: self.tag_name = self.args.tagname assert self.tag_name is not None print('Tag Name: {0}'.format(self.tag_name)) if self.tag_desc is None: self.tag_desc = self.args.tagdesc assert self.tag_desc is not None print('Tag Description: {0}'.format(self.tag_desc)) if self.servicemanager is None: self.servicemanager = self.get_service_manager() # Sample is not failing if Clustername passed is not valid # Validating if Cluster Name passed is Valid print('finding the cluster {0}'.format(self.cluster_name)) self.cluster_moid = get_cluster_id(service_manager=self.servicemanager, cluster_name=self.cluster_name) assert self.cluster_moid is not None print('Found cluster:{0} mo_id:{1}'.format(self.cluster_name, self.cluster_moid)) self.category_svc = Category(self.servicemanager.stub_config) self.tag_svc = Tag(self.servicemanager.stub_config) self.tag_association = TagAssociation(self.servicemanager.stub_config)
class VmwareTagManager(VmwareRestClient): def __init__(self, module): """ Constructor """ super(VmwareTagManager, self).__init__(module) self.pyv = PyVmomi(module=module) self.object_type = self.params.get('object_type') self.object_name = self.params.get('object_name') self.managed_object = None if self.object_type == 'VirtualMachine': self.managed_object = self.pyv.get_vm_or_template(self.object_name) if self.object_type == 'Datacenter': self.managed_object = self.pyv.find_datacenter_by_name(self.object_name) if self.object_type == 'ClusterComputeResource': self.managed_object = self.pyv.find_cluster_by_name(self.object_name) if self.object_type == 'HostSystem': self.managed_object = self.pyv.find_hostsystem_by_name(self.object_name) if self.object_type == 'DistributedVirtualSwitch': self.managed_object = find_dvs_by_name(self.pyv.content, self.object_name) self.object_type = 'VmwareDistributedVirtualSwitch' if self.object_type == 'DistributedVirtualPortgroup': dvs_name, pg_name = self.object_name.split(":", 1) dv_switch = find_dvs_by_name(self.pyv.content, dvs_name) if dv_switch is None: self.module.fail_json(msg="A distributed virtual switch with name %s does not exist" % dvs_name) self.managed_object = find_dvspg_by_name(dv_switch, pg_name) if self.managed_object is None: self.module.fail_json(msg="Failed to find the managed object for %s with type %s" % (self.object_name, self.object_type)) if not hasattr(self.managed_object, '_moId'): self.module.fail_json(msg="Unable to find managed object id for %s managed object" % self.object_name) self.dynamic_managed_object = DynamicID(type=self.object_type, id=self.managed_object._moId) self.tag_service = Tag(self.connect) self.category_service = Category(self.connect) self.tag_association_svc = TagAssociation(self.connect) self.tag_names = self.params.get('tag_names') def is_tag_category(self, cat_obj, tag_obj): for tag in self.tag_service.list_tags_for_category(cat_obj.id): if tag_obj.name == self.tag_service.get(tag).name: return True return False def ensure_state(self): """ Manage the internal state of tags """ results = dict( changed=False, tag_status=dict(), ) changed = False action = self.params.get('state') available_tag_obj = self.get_tags_for_object(tag_service=self.tag_service, tag_assoc_svc=self.tag_association_svc, dobj=self.dynamic_managed_object) # Already existing tags from the given object avail_tag_obj_name_list = [tag.name for tag in available_tag_obj] results['tag_status']['previous_tags'] = avail_tag_obj_name_list results['tag_status']['desired_tags'] = self.tag_names # Check if category and tag combination exists as per user request removed_tags_for_set = False for tag in self.tag_names: category_obj, category_name, tag_name = None, None, None if ":" in tag: # User specified category category_name, tag_name = tag.split(":", 1) category_obj = self.search_svc_object_by_name(self.category_service, category_name) if not category_obj: self.module.fail_json(msg="Unable to find the category %s" % category_name) else: # User specified only tag tag_name = tag tag_obj = self.search_svc_object_by_name(self.tag_service, tag_name) if not tag_obj: self.module.fail_json(msg="Unable to find the tag %s" % tag_name) if category_name and category_obj and not self.is_tag_category(category_obj, tag_obj): self.module.fail_json(msg="Category %s does not contain tag %s" % (category_name, tag_name)) if action in ('add', 'present'): if tag_obj not in available_tag_obj: # Tag is not already applied self.tag_association_svc.attach(tag_id=tag_obj.id, object_id=self.dynamic_managed_object) changed = True elif action == 'set': # Remove all tags first if not removed_tags_for_set: for av_tag in available_tag_obj: self.tag_association_svc.detach(tag_id=av_tag.id, object_id=self.dynamic_managed_object) removed_tags_for_set = True self.tag_association_svc.attach(tag_id=tag_obj.id, object_id=self.dynamic_managed_object) changed = True elif action in ('remove', 'absent'): if tag_obj in available_tag_obj: self.tag_association_svc.detach(tag_id=tag_obj.id, object_id=self.dynamic_managed_object) changed = True results['tag_status']['current_tags'] = [tag.name for tag in self.get_tags_for_object(self.tag_service, self.tag_association_svc, self.dynamic_managed_object)] results['changed'] = changed self.module.exit_json(**results)
def __init__(self, module): super(VmwareTag, self).__init__(module) self.tag_service = Tag(self.connect) self.tag_association = TagAssociation(self.connect) self.global_tags = dict() self.tag_name = self.params.get('tag_name')
session.verify = False connector = get_requests_connector(session=session, url=url) stub_config = StubConfigurationFactory.new_std_configuration(connector) user_password_security_context = create_user_password_security_context( vcenter_username, vcenter_password) stub_config.connector.set_security_context(user_password_security_context) session_svc = Session(stub_config) session_id = session_svc.create() session_security_context = create_session_security_context(session_id) stub_config.connector.set_security_context(session_security_context) # Create Tagging services tag_association = TagAssociation(stub_config) print('finding the vm {0}'.format(vm_name)) vm_moid = get_vm_id(vm_name) assert vm_moid is not None print('Found vm:{0} mo_id:{1}'.format('vAPISDKVM', vm_moid)) if tag_op == "tag": print('Tagging the vm {0}...'.format(vm_moid)) dynamic_id = DynamicID(type='VirtualMachine', id=vm_moid) tag_association.attach(tag_id=tag_id, object_id=dynamic_id) for tag_id in tag_association.list_attached_tags(dynamic_id): if tag_id == tag_id: tag_attached = True break assert tag_attached
username, password) stub_config.connector.set_security_context(user_password_security_context) # Create the stub for the session service and login by creating a session. session_svc = Session(stub_config) session_id = session_svc.create() # Successful authentication. Store the session identifier in the security # context of the stub and use that for all subsequent remote requests session_security_context = create_session_security_context(session_id) stub_config.connector.set_security_context(session_security_context) # Create Tagging services tag_svc = Tag(stub_config) category_svc = Category(stub_config) tag_association = TagAssociation(stub_config) def get_vm_id(name): """Find vm id by given name using pyVmomi.""" context = None if hasattr(ssl, '_create_unverified_context'): context = ssl._create_unverified_context() si = connect.Connect(host=server, user=username, pwd=password, sslContext=context) content = si.content container = content.rootFolder viewType = [vim.VirtualMachine]
def _populate_from_source(self, source_data, using_current_cache): """ Populate inventory data from direct source """ if using_current_cache: self._populate_from_cache(source_data) return source_data cacheable_results = {} hostvars = {} objects = self._get_managed_objects_properties( vim_type=vim.VirtualMachine, properties=['name']) if self.with_tags: tag_svc = Tag(self.rest_content) tag_association = TagAssociation(self.rest_content) tags_info = dict() tags = tag_svc.list() for tag in tags: tag_obj = tag_svc.get(tag) tags_info[tag_obj.id] = tag_obj.name if tag_obj.name not in cacheable_results: cacheable_results[tag_obj.name] = {'hosts': []} self.inventory.add_group(tag_obj.name) for temp_vm_object in objects: for temp_vm_object_property in temp_vm_object.propSet: # VMware does not provide a way to uniquely identify VM by its name # i.e. there can be two virtual machines with same name # Appending "_" and VMware UUID to make it unique current_host = temp_vm_object_property.val + "_" + temp_vm_object.obj.config.uuid if current_host not in hostvars: hostvars[current_host] = {} self.inventory.add_host(current_host) host_ip = temp_vm_object.obj.guest.ipAddress if host_ip: self.inventory.set_variable(current_host, 'ansible_host', host_ip) # Load VM properties in host_vars vm_properties = [ 'name', 'config.cpuHotAddEnabled', 'config.cpuHotRemoveEnabled', 'config.instanceUuid', 'config.hardware.numCPU', 'config.template', 'config.name', 'guest.hostName', 'guest.ipAddress', 'guest.guestId', 'guest.guestState', 'runtime.maxMemoryUsage', 'customValue', ] for vm_prop in vm_properties: vm_value = self._get_vm_prop(temp_vm_object.obj, vm_prop.split(".")) self.inventory.set_variable(current_host, vm_prop, vm_value) # Only gather facts related to tag if vCloud and vSphere is installed. if HAS_VCLOUD and HAS_VSPHERE and self.with_tags: # Add virtual machine to appropriate tag group vm_mo_id = temp_vm_object.obj._GetMoId() vm_dynamic_id = DynamicID(type='VirtualMachine', id=vm_mo_id) attached_tags = tag_association.list_attached_tags( vm_dynamic_id) for tag_id in attached_tags: self.inventory.add_child(tags_info[tag_id], current_host) cacheable_results[tags_info[tag_id]][ 'hosts'].append(current_host) # Based on power state of virtual machine vm_power = temp_vm_object.obj.summary.runtime.powerState if vm_power not in cacheable_results: cacheable_results[vm_power] = [] self.inventory.add_group(vm_power) cacheable_results[vm_power].append(current_host) self.inventory.add_child(vm_power, current_host) # Based on guest id vm_guest_id = temp_vm_object.obj.config.guestId if vm_guest_id and vm_guest_id not in cacheable_results: cacheable_results[vm_guest_id] = [] self.inventory.add_group(vm_guest_id) cacheable_results[vm_guest_id].append(current_host) self.inventory.add_child(vm_guest_id, current_host) return cacheable_results
def __init__(self, module): super(VmwareTag, self).__init__(module) self.tag_service = Tag(self.connect) self.tag_association_svc = TagAssociation(self.connect)
class TaggingWorkflow(SampleBase): """ Demonstrates tagging CRUD operations Step 1: Create a Tag category. Step 2: Create a Tag under the category. Step 3: Retrieve the managed object id of an existing cluster from its name. Step 4: Assign the tag to the cluster. Additional steps when clearData flag is set to TRUE: Step 5: Detach the tag from the cluster. Step 6: Delete the tag. Step 7: Delete the tag category. Note: the sample needs an existing cluster """ def __init__(self, platformservicecontroller): SampleBase.__init__(self, self.__doc__, platformservicecontroller) self.servicemanager = None self.category_svc = None self.tag_svc = None self.tag_association = None self.category_name = None self.category_desc = None self.tag_name = None self.tag_desc = None self.cluster_name = None self.cluster_moid = None self.category_id = None self.tag_id = None self.tag_attached = False self.dynamic_id = None def _options(self): self.argparser.add_argument('-clustername', '--clustername', help='Name of the cluster to be tagged') self.argparser.add_argument('-categoryname', '--categoryname', help='Name of the Category to be created') self.argparser.add_argument('-categorydesc', '--categorydesc', help='Description of the Category to be created') self.argparser.add_argument('-tagname', '--tagname', help='Name of the tag to be created') self.argparser.add_argument('-tagdesc', '--tagdesc', help='Description of the tag to be created') def _setup(self): if self.cluster_name is None: # for testing self.cluster_name = self.args.clustername assert self.cluster_name is not None logger.info('Cluster Name: {0}'.format(self.cluster_name)) if self.category_name is None: self.category_name = self.args.categoryname assert self.category_name is not None logger.info('Category Name: {0}'.format(self.category_name)) if self.category_desc is None: self.category_desc = self.args.categorydesc assert self.category_desc is not None logger.info('Category Description: {0}'.format(self.category_desc)) if self.tag_name is None: self.tag_name = self.args.tagname assert self.tag_name is not None logger.info('Tag Name: {0}'.format(self.tag_name)) if self.tag_desc is None: self.tag_desc = self.args.tagdesc assert self.tag_desc is not None logger.info('Tag Description: {0}'.format(self.tag_desc)) if self.servicemanager is None: self.servicemanager = self.get_service_manager() self.category_svc = Category(self.servicemanager.stub_config) self.tag_svc = Tag(self.servicemanager.stub_config) self.tag_association = TagAssociation(self.servicemanager.stub_config) def _execute(self): logger.info('List all the existing categories user has access to...') categories = self.category_svc.list() if len(categories) > 0: for category in categories: logger.info('Found Category: {0}'.format(category)) else: logger.info('No Tag Category Found...') logger.info('List all the existing tags user has access to...') tags = self.tag_svc.list() if len(tags) > 0: for tag in tags: logger.info('Found Tag: {0}'.format(tag)) else: logger.info('No Tag Found...') logger.info('creating a new tag category...') self.category_id = self.create_tag_category(self.category_name, self.category_desc, CategoryModel.Cardinality.MULTIPLE) assert self.category_id is not None logger.info('Tag category created; Id: {0}'.format(self.category_id)) logger.info("creating a new Tag...") self.tag_id = self.create_tag(self.tag_name, self.tag_desc, self.category_id) assert self.tag_id is not None logger.info('Tag created; Id: {0}'.format(self.tag_id)) logger.info('updating the tag...') date_time = time.strftime('%d/%m/%Y %H:%M:%S') self.update_tag(self.tag_id, 'Server Tag updated at ' + date_time) logger.info('Tag updated; Id: {0}'.format(self.tag_id)) logger.info('finding the cluster {0}'.format(self.cluster_name)) self.cluster_moid = get_cluster_id(service_manager=self.servicemanager, cluster_name=self.cluster_name) assert self.cluster_moid is not None logger.info('Found cluster:{0} mo_id:{1}'.format('vAPISDKCluster', self.cluster_moid)) logger.info('Tagging the cluster {0}...'.format(self.cluster_name)) self.dynamic_id = DynamicID(type='ClusterComputeResource', id=self.cluster_moid) self.tag_association.attach(tag_id=self.tag_id, object_id=self.dynamic_id) for tag_id in self.tag_association.list_attached_tags(self.dynamic_id): if tag_id == self.tag_id: self.tag_attached = True break assert self.tag_attached logger.info('Tagged cluster: {0}'.format(self.cluster_moid)) def _cleanup(self): try: if self.tag_attached: self.tag_association.detach(self.tag_id, self.dynamic_id) logger.info('Removed tag from cluster: {0}'.format(self.cluster_moid)) if self.tag_id is not None: self.delete_tag(self.tag_id) logger.info('Tag deleted; Id: {0}'.format(self.tag_id)) if self.category_id is not None: self.delete_tag_category(self.category_id) logger.info('Tag category deleted; Id: {0}'.format(self.category_id)) except Exception as e: raise Exception(e) def create_tag_category(self, name, description, cardinality): """create a category. User who invokes this needs create category privilege.""" create_spec = self.category_svc.CreateSpec() create_spec.name = name create_spec.description = description create_spec.cardinality = cardinality associableTypes = set() create_spec.associable_types = associableTypes return self.category_svc.create(create_spec) def delete_tag_category(self, category_id): """Deletes an existing tag category; User who invokes this API needs delete privilege on the tag category. """ self.category_svc.delete(category_id) def create_tag(self, name, description, category_id): """Creates a Tag""" create_spec = self.tag_svc.CreateSpec() create_spec.name = name create_spec.description = description create_spec.category_id = category_id return self.tag_svc.create(create_spec) def update_tag(self, tag_id, description): """Update the description of an existing tag. User who invokes this API needs edit privilege on the tag. """ update_spec = self.tag_svc.UpdateSpec() update_spec.setDescription = description self.tag_svc.update(tag_id, update_spec) def delete_tag(self, tag_id): """Delete an existing tag. User who invokes this API needs delete privilege on the tag.""" self.tag_svc.delete(tag_id)
def _populate_from_source(self, source_data, using_current_cache): """ Populate inventory data from direct source """ if using_current_cache: self._populate_from_cache(source_data) return source_data cacheable_results = {'_meta': {'hostvars': {}}} hostvars = {} objects = self.pyv._get_managed_objects_properties(vim_type=vim.VirtualMachine, properties=['name']) if self.pyv.with_tags: tag_svc = Tag(self.pyv.rest_content) tag_association = TagAssociation(self.pyv.rest_content) tags_info = dict() tags = tag_svc.list() for tag in tags: tag_obj = tag_svc.get(tag) tags_info[tag_obj.id] = tag_obj.name if tag_obj.name not in cacheable_results: cacheable_results[tag_obj.name] = {'hosts': []} self.inventory.add_group(tag_obj.name) for vm_obj in objects: for vm_obj_property in vm_obj.propSet: # VMware does not provide a way to uniquely identify VM by its name # i.e. there can be two virtual machines with same name # Appending "_" and VMware UUID to make it unique current_host = vm_obj_property.val + "_" + vm_obj.obj.config.uuid if current_host not in hostvars: hostvars[current_host] = {} self.inventory.add_host(current_host) host_ip = vm_obj.obj.guest.ipAddress if host_ip: self.inventory.set_variable(current_host, 'ansible_host', host_ip) self._populate_host_properties(vm_obj, current_host) # Only gather facts related to tag if vCloud and vSphere is installed. if HAS_VCLOUD and HAS_VSPHERE and self.pyv.with_tags: # Add virtual machine to appropriate tag group vm_mo_id = vm_obj.obj._GetMoId() vm_dynamic_id = DynamicID(type='VirtualMachine', id=vm_mo_id) attached_tags = tag_association.list_attached_tags(vm_dynamic_id) for tag_id in attached_tags: self.inventory.add_child(tags_info[tag_id], current_host) cacheable_results[tags_info[tag_id]]['hosts'].append(current_host) # Based on power state of virtual machine vm_power = str(vm_obj.obj.summary.runtime.powerState) if vm_power not in cacheable_results: cacheable_results[vm_power] = {'hosts': []} self.inventory.add_group(vm_power) cacheable_results[vm_power]['hosts'].append(current_host) self.inventory.add_child(vm_power, current_host) # Based on guest id vm_guest_id = vm_obj.obj.config.guestId if vm_guest_id and vm_guest_id not in cacheable_results: cacheable_results[vm_guest_id] = {'hosts': []} self.inventory.add_group(vm_guest_id) cacheable_results[vm_guest_id]['hosts'].append(current_host) self.inventory.add_child(vm_guest_id, current_host) for host in hostvars: h = self.inventory.get_host(host) cacheable_results['_meta']['hostvars'][h.name] = h.vars return cacheable_results
class TaggingWorkflow(SampleBase): """ Demonstrates tagging CRUD operations Step 1: Create a Tag category. Step 2: Create a Tag under the category. Step 3: Retrieve the managed object id of an existing cluster from its name. Step 4: Assign the tag to the cluster. Additional steps when clearData flag is set to TRUE: Step 5: Detach the tag from the cluster. Step 6: Delete the tag. Step 7: Delete the tag category. Note: the sample needs an existing cluster """ def __init__(self): SampleBase.__init__(self, self.__doc__) self.servicemanager = None self.category_svc = None self.tag_svc = None self.tag_association = None self.category_name = None self.category_desc = None self.tag_name = None self.tag_desc = None self.cluster_name = None self.cluster_moid = None self.category_id = None self.tag_id = None self.tag_attached = False self.dynamic_id = None def _options(self): self.argparser.add_argument('-clustername', '--clustername', help='Name of the cluster to be tagged') self.argparser.add_argument('-categoryname', '--categoryname', help='Name of the Category to be created') self.argparser.add_argument( '-categorydesc', '--categorydesc', help='Description of the Category to be created') self.argparser.add_argument('-tagname', '--tagname', help='Name of the tag to be created') self.argparser.add_argument( '-tagdesc', '--tagdesc', help='Description of the tag to be created') def _setup(self): if self.cluster_name is None: # for testing self.cluster_name = self.args.clustername assert self.cluster_name is not None print('Cluster Name: {0}'.format(self.cluster_name)) if self.category_name is None: self.category_name = self.args.categoryname assert self.category_name is not None print('Category Name: {0}'.format(self.category_name)) if self.category_desc is None: self.category_desc = self.args.categorydesc assert self.category_desc is not None print('Category Description: {0}'.format(self.category_desc)) if self.tag_name is None: self.tag_name = self.args.tagname assert self.tag_name is not None print('Tag Name: {0}'.format(self.tag_name)) if self.tag_desc is None: self.tag_desc = self.args.tagdesc assert self.tag_desc is not None print('Tag Description: {0}'.format(self.tag_desc)) if self.servicemanager is None: self.servicemanager = self.get_service_manager() self.category_svc = Category(self.servicemanager.stub_config) self.tag_svc = Tag(self.servicemanager.stub_config) self.tag_association = TagAssociation(self.servicemanager.stub_config) def _execute(self): print('List all the existing categories user has access to...') categories = self.category_svc.list() if len(categories) > 0: for category in categories: print('Found Category: {0}'.format(category)) else: print('No Tag Category Found...') print('List all the existing tags user has access to...') tags = self.tag_svc.list() if len(tags) > 0: for tag in tags: print('Found Tag: {0}'.format(tag)) else: print('No Tag Found...') print('creating a new tag category...') self.category_id = self.create_tag_category( self.category_name, self.category_desc, CategoryModel.Cardinality.MULTIPLE) assert self.category_id is not None print('Tag category created; Id: {0}'.format(self.category_id)) print("creating a new Tag...") self.tag_id = self.create_tag(self.tag_name, self.tag_desc, self.category_id) assert self.tag_id is not None print('Tag created; Id: {0}'.format(self.tag_id)) print('updating the tag...') date_time = time.strftime('%d/%m/%Y %H:%M:%S') self.update_tag(self.tag_id, 'Server Tag updated at ' + date_time) print('Tag updated; Id: {0}'.format(self.tag_id)) print('finding the cluster {0}'.format(self.cluster_name)) self.cluster_moid = get_cluster_id(service_manager=self.servicemanager, cluster_name=self.cluster_name) assert self.cluster_moid is not None print('Found cluster:{0} mo_id:{1}'.format('vAPISDKCluster', self.cluster_moid)) print('Tagging the cluster {0}...'.format(self.cluster_name)) self.dynamic_id = DynamicID(type='ClusterComputeResource', id=self.cluster_moid) self.tag_association.attach(tag_id=self.tag_id, object_id=self.dynamic_id) for tag_id in self.tag_association.list_attached_tags(self.dynamic_id): if tag_id == self.tag_id: self.tag_attached = True break assert self.tag_attached print('Tagged cluster: {0}'.format(self.cluster_moid)) def _cleanup(self): try: if self.tag_attached: self.tag_association.detach(self.tag_id, self.dynamic_id) print('Removed tag from cluster: {0}'.format( self.cluster_moid)) if self.tag_id is not None: self.delete_tag(self.tag_id) print('Tag deleted; Id: {0}'.format(self.tag_id)) if self.category_id is not None: self.delete_tag_category(self.category_id) print('Tag category deleted; Id: {0}'.format(self.category_id)) except Exception as e: raise Exception(e) def create_tag_category(self, name, description, cardinality): """create a category. User who invokes this needs create category privilege.""" create_spec = self.category_svc.CreateSpec() create_spec.name = name create_spec.description = description create_spec.cardinality = cardinality associableTypes = set() create_spec.associable_types = associableTypes return self.category_svc.create(create_spec) def delete_tag_category(self, category_id): """Deletes an existing tag category; User who invokes this API needs delete privilege on the tag category. """ self.category_svc.delete(category_id) def create_tag(self, name, description, category_id): """Creates a Tag""" create_spec = self.tag_svc.CreateSpec() create_spec.name = name create_spec.description = description create_spec.category_id = category_id return self.tag_svc.create(create_spec) def update_tag(self, tag_id, description): """Update the description of an existing tag. User who invokes this API needs edit privilege on the tag. """ update_spec = self.tag_svc.UpdateSpec() update_spec.setDescription = description self.tag_svc.update(tag_id, update_spec) def delete_tag(self, tag_id): """Delete an existing tag. User who invokes this API needs delete privilege on the tag.""" self.tag_svc.delete(tag_id)