示例#1
0
    def get_tags_for_object(self, dobj):
        """
        Return tags associated with an object
        Args:
            dobj: Dynamic object
        Returns: List of tags associated with the given object
        """
        vmware_client = VmwareRestClient(self.module)

        cluster_dynamic_obj = DynamicID(type='ClusterComputeResource',
                                        id=dobj._moId)
        self.tag_service = vmware_client.api_client.tagging.Tag
        self.tag_association_svc = vmware_client.api_client.tagging.TagAssociation
        self.category_service = vmware_client.api_client.tagging.Category

        tag_ids = self.tag_association_svc.list_attached_tags(
            cluster_dynamic_obj)
        tags = []
        for tag_id in tag_ids:
            tag_obj = self.tag_service.get(tag_id)
            tags.append({
                'id':
                tag_obj.id,
                'category_name':
                self.category_service.get(tag_obj.category_id).name,
                'name':
                tag_obj.name,
                'description':
                tag_obj.description,
                'category_id':
                tag_obj.category_id,
            })
        return tags
示例#2
0
 def build_list(self):
     host_list = []
     container = self.content.rootFolder  # starting point to look into
     viewType = [vim.VirtualMachine]  # object types to look for
     recursive = True  # whether we should look into it recursively
     containerView = self.content.viewManager.CreateContainerView(
         container, viewType, recursive)
     children = containerView.view
     for child in children:
         print('Building definition for host: {}, UUID: {}'.format(
             child.summary.config.name, child.summary.config.uuid))
         vm_dynamic_id = DynamicID(type='VirtualMachine',
                                   id=child._GetMoId())
         if child.summary.guest is not None:
             host = Host(child.summary.config.uuid,
                         child.summary.config.name,
                         child.summary.guest.ipAddress)
             for tag in self.tag_association.list_attached_tags(
                     vm_dynamic_id):
                 host.add_values(self.tags_info[tag]['category'],
                                 self.tags_info[tag]['name'])
             host_list.append(host)
         else:
             print('Host is not valid or booted: {}'.format(
                 child.summary.config.name))
     return host_list
示例#3
0
    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')
示例#4
0
    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 == 'Folder':
            self.managed_object = self.pyv.find_folder_by_name(self.object_name)

        if self.object_type == 'Datacenter':
            self.managed_object = self.pyv.find_datacenter_by_name(self.object_name)

        if self.object_type == 'Datastore':
            self.managed_object = self.pyv.find_datastore_by_name(self.object_name)

        if self.object_type == 'DatastoreCluster':
            self.managed_object = self.pyv.find_datastore_cluster_by_name(self.object_name)
            self.object_type = 'StoragePod'

        if self.object_type == 'ClusterComputeResource':
            self.managed_object = self.pyv.find_cluster_by_name(self.object_name)

        if self.object_type == 'ResourcePool':
            self.managed_object = self.pyv.find_resource_pool_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 = self.api_client.tagging.Tag
        self.category_service = self.api_client.tagging.Category
        self.tag_association_svc = self.api_client.tagging.TagAssociation

        self.tag_names = self.params.get('tag_names')
def attach_tag(client, inv_obj, inv_type, tag):
    dyn_id = DynamicID(type=inv_type, id=inv_obj)
    try:
        client.tagging.TagAssociation.attach(tag.id, dyn_id)
    except Exception as e:
        print("Check that the tag is associable to {}".format(inv_type))
        raise e
示例#6
0
def append_tag():
    """
   Read the excel file in pandas dataframe and output name and tag
   get the vm-id and tag-id
   attach the tag to vm
   """
    df = pd.read_excel(path)
    df1 = df[['VM Name',
              'Taged to']]  #Reading the VM Name and tag column from the sheet
    df2 = df1.rename(columns={'VM Name': 'name', 'Taged to': 'tag_name'})
    for ind in df2.index:
        name = df2['name'][ind]
        tag_name_col = df2['tag_name'][ind]
        tag_name_split = tag_name_col.split(',')
        vm_moreof = get_vm_id(name)
        for tag_name in tag_name_split:
            tag = tag_id(tag_name)
            if tag is not None:
                dynamic_id = DynamicID(type='VirtualMachine', id=vm_moreof)
                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
                print('Tagged vm: {0}'.format(vm_moreof))
示例#7
0
    def get_tags_for_dynamic_obj(self, mid=None, type=None):
        """
        Return list of tag object details associated with object
        Args:
            mid: Dynamic object for specified object
            type: Type of DynamicID to lookup

        Returns: List of tag object details associated with the given object

        """
        tags = []
        if mid is None:
            return tags
        dynamic_managed_object = DynamicID(type=type, id=mid)

        temp_tags_model = self.get_tags_for_object(dynamic_managed_object)

        category_service = self.api_client.tagging.Category

        for tag_obj in temp_tags_model:
            tags.append({
                'id':
                tag_obj.id,
                'category_name':
                category_service.get(tag_obj.category_id).name,
                'name':
                tag_obj.name,
                'description':
                tag_obj.description,
                'category_id':
                tag_obj.category_id,
            })

        return tags
示例#8
0
    def get_vm_tags(self,
                    tag_service=None,
                    tag_association_svc=None,
                    vm_mid=None):
        """
        Return list of tag name associated with virtual machine
        Args:
            tag_service:  Tag service object
            tag_association_svc: Tag association object
            vm_mid: Dynamic object for virtual machine

        Returns: List of tag names associated with the given virtual machine

        """
        # This API returns just names of tags
        # Please use get_tags_for_vm for more tag object details
        tags = []
        if vm_mid is None:
            return tags
        dynamic_managed_object = DynamicID(type='VirtualMachine', id=vm_mid)

        temp_tags_model = self.get_tags_for_object(tag_service,
                                                   tag_association_svc,
                                                   dynamic_managed_object)

        for tag_obj in temp_tags_model:
            tags.append(tag_obj.name)

        return tags
示例#9
0
文件: tag.py 项目: D3DeFi/vmcli
    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')
示例#10
0
def main():
    argument_spec = vmware_argument_spec()
    argument_spec.update(
        name=dict(type='str'),
        name_match=dict(type='str', choices=['first', 'last'], default='first'),
        uuid=dict(type='str'),
        use_instance_uuid=dict(type='bool', default=False),
        moid=dict(type='str'),
        folder=dict(type='str'),
        datacenter=dict(type='str', required=True),
        tags=dict(type='bool', default=False),
        schema=dict(type='str', choices=['summary', 'vsphere'], default='summary'),
        properties=dict(type='list', elements='str'),
        tag_details=dict(type='bool', default=False),
    )
    module = AnsibleModule(argument_spec=argument_spec,
                           required_one_of=[['name', 'uuid', 'moid']],
                           supports_check_mode=True)

    if module.params.get('folder'):
        # FindByInventoryPath() does not require an absolute path
        # so we should leave the input folder path unmodified
        module.params['folder'] = module.params['folder'].rstrip('/')

    if module.params['schema'] != 'vsphere' and module.params.get('properties'):
        module.fail_json(msg="The option 'properties' is only valid when the schema is 'vsphere'")

    pyv = PyVmomi(module)
    # Check if the VM exists before continuing
    vm = pyv.get_vm()

    # VM already exists
    if vm:
        try:
            if module.params['schema'] == 'summary':
                instance = pyv.gather_facts(vm)
            else:
                instance = pyv.to_json(vm, module.params['properties'])
            if module.params.get('tags'):
                if not HAS_VSPHERE:
                    module.fail_json(msg="Unable to find 'vCloud Suite SDK' Python library which is required."
                                         " Please refer this URL for installation steps"
                                         " - https://code.vmware.com/web/sdk/vsphere-automation-python")

                vm_rest_client = VmwareTag(module)
                tags = []
                if module.params.get('tag_details'):
                    tags = vm_rest_client.get_tags_for_vm(vm_mid=vm._moId)
                else:
                    dynamic_obj = DynamicID(type='VirtualMachine', id=vm._moId)
                    tags = vm_rest_client.get_vm_tags(vm_rest_client.tag_service,
                                                      vm_rest_client.tag_association_svc,
                                                      vm_mid=dynamic_obj)
                instance.update(tags=tags)
            module.exit_json(instance=instance)
        except Exception as exc:
            module.fail_json(msg="Information gathering failed with exception %s" % to_text(exc))
    else:
        vm_id = (module.params.get('uuid') or module.params.get('name') or module.params.get('moid'))
        module.fail_json(msg="Unable to gather information for non-existing VM %s" % vm_id)
    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 = self.api_client.tagging.Tag
        self.category_service = self.api_client.tagging.Category
        self.tag_association_svc = self.api_client.tagging.TagAssociation

        self.tag_names = self.params.get("tag_names")
示例#12
0
 def _getTagsForObject(self, obj, vs_type='VirtualMachine'):
     """List tag objects for given id/object """
     d_obj = obj if type(obj) == DynamicID else DynamicID(type=vs_type,
                                                          id=obj)
     tag_ids = self.tagAssociationSvc.list_attached_tags(d_obj)
     tags = []
     for tid in tag_ids:
         tags.append(self.tagSvc.get(tid))
     return tags
示例#13
0
    def populate(self):

        objects = self._get_managed_objects_properties(
            vim_type=vim.VirtualMachine, properties=['name'])
        tag_svc = self.rest_content.tagging.Tag
        tag_association = self.rest_content.tagging.TagAssociation
        cat_svc = self.rest_content.tagging.Category

        # Get tags and categories to lower amount of api requests needed
        cat_info = dict()
        tags_info = dict()
        tags = tag_svc.list()
        cats = cat_svc.list()

        for cat in cats:
            cat_obj = cat_svc.get(cat)
            cat_info[cat_obj.id] = cat_obj.name
        for tag in tags:
            tag_obj = tag_svc.get(tag)
            tags_info[tag_obj.id] = dict(
                name=tag_obj.name, category=cat_info[tag_obj.category_id])

        del self.hostlist
        self.hostlist = HostList(self.output_filename)

        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
                if not vm_obj.obj.config:
                    # Sometime orphaned VMs return no configurations
                    continue

                if not self.hostlist.host_exists(vm_obj.obj.config.uuid):
                    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)

                    if not vm_obj.obj.guest or not vm_obj.obj.guest.ipAddress:
                        continue

                    host_ip = vm_obj.obj.guest.ipAddress
                    if host_ip is None:
                        continue

                    current_host = Host(vm_obj.obj.config.uuid,
                                        vm_obj_property.val, host_ip)

                    for tag_id in attached_tags:
                        current_host.add_values(tags_info[tag_id]['category'],
                                                tags_info[tag_id]['name'])

                    self.hostlist.add_host(current_host)
        return
    def get_tag_facts(self):
        vmware_client = VmwareRestClient(self.module)

        host_dynamic_obj = DynamicID(type='HostSystem', id=self.host._moId)
        self.tag_service = vmware_client.api_client.tagging.Tag
        self.tag_association_svc = vmware_client.api_client.tagging.TagAssociation
        self.category_service = vmware_client.api_client.tagging.Category
        facts = {'tags': self.get_tags_for_object(host_dynamic_obj)}
        return facts
示例#15
0
 def tag_vm(self, vm_id, tag_id):
     tag_attached = False
     dynamic_id = DynamicID(type='VirtualMachine', id=vm_id)
     self.tag_association.attach(tag_id=tag_id, object_id=dynamic_id)
     for tag_id in self.tag_association.list_attached_tags(dynamic_id):
         if tag_id == self.kms_tag_id:
             tag_attached = True
             break
     return tag_attached
示例#16
0
    def get_tags_for_hostsystem(self, hostsystem_mid=None):
        """
        Return list of tag object associated with host system
        Args:
            hostsystem_mid: Dynamic object for host system

        Returns: List of tag object associated with the given host system

        """
        dobj = DynamicID(type='HostSystem', id=hostsystem_mid)
        return self.get_tags_for_dynamic_obj(dobj=dobj)
示例#17
0
    def get_tags_for_cluster(self, cluster_mid=None):
        """
        Return list of tag object associated with cluster
        Args:
            cluster_mid: Dynamic object for cluster

        Returns: List of tag object associated with the given cluster

        """
        dobj = DynamicID(type='cluster', id=cluster_mid)
        return self.get_tags_for_dynamic_obj(dobj=dobj)
示例#18
0
    def get_tags_for_datacenter(self, datacenter_mid=None):
        """
        Return list of tag object associated with datacenter
        Args:
            datacenter_mid: Dynamic object for datacenter

        Returns: List of tag object associated with the given datacenter

        """
        dobj = DynamicID(type='Datacenter', id=datacenter_mid)
        return self.get_tags_for_dynamic_obj(dobj=dobj)
示例#19
0
    def _removeTagFromObject(self, tag, obj, vs_type='VirtualMachine'):
        """Given a tag id/object and a vmware object(Dynamic ID object or id)
        Detach the tag to the object
        """
        tag_id = tag.id if type(tag) == TagModel else tag
        obj_did = obj if type(obj) == DynamicID else DynamicID(type=vs_type,
                                                               id=obj)

        result = self.tagAssociationSvc.detach(tag_id=tag_id,
                                               object_id=obj_did)
        return result
示例#20
0
    def get_tags_for_vm(self, vm_mid=None):
        """
        Return list of tag object associated with virtual machine
        Args:
            vm_mid: Dynamic object for virtual machine

        Returns: List of tag object associated with the given virtual machine

        """
        dobj = DynamicID(type='VirtualMachine', id=vm_mid)
        return self.get_tags_for_dynamic_obj(dobj=dobj)
    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))
示例#22
0
    def _addTagToObject(self, tag, obj, vs_type='VirtualMachine'):
        """Given a tag id/object and a vmware object(Dynamic ID object or id)
        Attach the tag to the object
        """
        tag_id = tag.id if type(tag) == TagModel else tag
        d_obj = obj if type(obj) == DynamicID else DynamicID(type=vs_type,
                                                             id=obj)

        self.tagAssociationSvc.attach(tag_id=tag_id, object_id=d_obj)

        if not self._checkObjectHasTag(tag, obj, vs_type):
            raise SystemError("Impossibile aggiungere il Tag alla VM")
示例#23
0
def tag_vm(stub, vm, tag):
    """
    Tag a VM
    """
    import com.vmware.cis.tagging_client as tagclient
    from com.vmware.vapi.std_client import DynamicID

    if isinstance(tag, tagclient.TagModel):
        tag_id = tag.id
    else:
        tag_obj = get_tag_by_name(stub, tag)
        tag_id = tag_obj.id
    if isinstance(vm, DynamicID):
        obj_did = vm
    else:
        obj_did = DynamicID(type="VirtualMachine", id=vm._moId)
    tag_ass = tagclient.TagAssociation(stub)
    result = tag_ass.attach(tag_id=tag_id, object_id=obj_did)
    return result
示例#24
0
    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
示例#25
0
    def __init__(self, module):
        """
        Constructor
        """
        super(VmwareTagManager, self).__init__(module)
        self.pyv = PyVmomi(module=module)

        moid = self.params.get('moid')
        self.object_type = self.params.get('object_type')
        managed_object_id = None

        if moid:
            managed_object_id = moid
        else:
            object_name = self.params.get('object_name')
            managed_object = self.get_managed_object(object_name,
                                                     self.object_type)

            if managed_object is None:
                self.module.fail_json(
                    msg="Failed to find the managed object for %s with type %s"
                    % (object_name, self.object_type))

            if not hasattr(managed_object, '_moId'):
                self.module.fail_json(
                    msg="Unable to find managed object id for %s managed object"
                    % object_name)

            managed_object_id = managed_object._moId

        self.dynamic_managed_object = DynamicID(type=self.object_type,
                                                id=managed_object_id)

        self.tag_service = self.api_client.tagging.Tag
        self.category_service = self.api_client.tagging.Category
        self.tag_association_svc = self.api_client.tagging.TagAssociation

        self.tag_names = self.params.get('tag_names')
示例#26
0
    def _populate_from_source(self):
        """
        Populate inventory data from direct source

        """
        hostvars = {}
        strict = self.get_option('strict')

        vm_properties = self.get_option('properties')
        if not isinstance(vm_properties, list):
            vm_properties = [vm_properties]

        if len(vm_properties) == 0:
            vm_properties = ['name']

        if 'all' in vm_properties:
            query_props = None
            vm_properties.remove('all')
        else:
            if 'runtime.connectionState' not in vm_properties:
                vm_properties.append('runtime.connectionState')
            query_props = [x for x in vm_properties if x != "customValue"]

        objects = self.pyv.get_managed_objects_properties(
            vim_type=vim.VirtualMachine,
            properties=query_props,
            resources=self.get_option('resources'),
            strict=strict,
        )

        tags_info = dict()
        if self.pyv.with_tags:
            tag_svc = self.pyv.rest_content.tagging.Tag
            cat_svc = self.pyv.rest_content.tagging.Category

            tags = tag_svc.list()
            for tag in tags:
                tag_obj = tag_svc.get(tag)
                tags_info[tag_obj.id] = (tag_obj.name,
                                         cat_svc.get(tag_obj.category_id).name)

        hostnames = self.get_option('hostnames')

        for vm_obj in objects:
            properties = dict()
            for vm_obj_property in vm_obj.propSet:
                properties[vm_obj_property.name] = vm_obj_property.val

            if (properties.get('runtime.connectionState') or
                    properties['runtime'].connectionState) in ('orphaned',
                                                               'inaccessible',
                                                               'disconnected'):
                continue

            # Custom values
            if 'customValue' in vm_properties:
                field_mgr = []
                if self.pyv.content.customFieldsManager:  # not an ESXi
                    field_mgr = self.pyv.content.customFieldsManager.field
                for cust_value in vm_obj.obj.customValue:
                    properties[[
                        y.name for y in field_mgr if y.key == cust_value.key
                    ][0]] = cust_value.value

            # Tags
            if tags_info:
                # Add virtual machine to appropriate tag group
                vm_mo_id = vm_obj.obj._GetMoId()  # pylint: disable=protected-access
                vm_dynamic_id = DynamicID(type='VirtualMachine', id=vm_mo_id)
                tag_association = self.pyv.rest_content.tagging.TagAssociation
                properties['tags'] = []
                properties['categories'] = []
                properties['tag_category'] = {}
                for tag_id in tag_association.list_attached_tags(
                        vm_dynamic_id):
                    if tag_id not in tags_info:
                        # Ghost Tags - community.vmware#681
                        continue
                    # Add tags related to VM
                    properties['tags'].append(tags_info[tag_id][0])
                    # Add categories related to VM
                    properties['categories'].append(tags_info[tag_id][1])
                    # Add tag and categories related to VM
                    if tags_info[tag_id][1] not in properties['tag_category']:
                        properties['tag_category'][tags_info[tag_id][1]] = []
                    properties['tag_category'][tags_info[tag_id][1]].append(
                        tags_info[tag_id][0])

            # Path
            with_path = self.get_option('with_path')
            if with_path:
                path = []
                parent = vm_obj.obj.parent
                while parent:
                    path.append(parent.name)
                    parent = parent.parent
                path.reverse()
                properties['path'] = "/".join(path)

            host_properties = to_nested_dict(properties)

            host = self._get_hostname(host_properties,
                                      hostnames,
                                      strict=strict)

            host_filters = self.get_option('filters')

            if host not in hostvars and self._can_add_host(
                    host_filters, host_properties, host, strict=strict):
                hostvars[host] = host_properties
                self._populate_host_properties(host_properties, host)

        return hostvars
示例#27
0
    def _populate_from_source(self):
        """
        Populate inventory data from direct source

        """
        hostvars = {}
        strict = self.get_option('strict')

        vm_properties = self.get_option('properties')
        if not isinstance(vm_properties, list):
            vm_properties = [vm_properties]

        if len(vm_properties) == 0:
            vm_properties = ['name']

        if 'all' in vm_properties:
            query_props = None
            vm_properties.remove('all')
        else:
            query_props = [x for x in vm_properties if x != "customValue"]

        objects = self.pyv.get_managed_objects_properties(
            vim_type=vim.VirtualMachine,
            properties=query_props,
            # resources=self.get_option('resources'),
            strict=strict,
        )

        tags_info = dict()
        if self.pyv.with_tags:
            tag_svc = self.pyv.rest_content.tagging.Tag
            tag_association = self.pyv.rest_content.tagging.TagAssociation

            tags = tag_svc.list()
            for tag in tags:
                tag_obj = tag_svc.get(tag)
                tags_info[tag_obj.id] = tag_obj.name

        hostnames = self.get_option('hostnames')

        for vm_obj in objects:
            if not vm_obj.obj.config:
                # Sometime orphaned VMs return no configurations
                continue

            properties = dict()
            for vm_obj_property in vm_obj.propSet:
                properties[vm_obj_property.name] = vm_obj_property.val

            # Custom values
            if 'customValue' in vm_properties:
                field_mgr = self.pyv.content.customFieldsManager.field
                for cust_value in vm_obj.obj.customValue:
                    properties[[y.name for y in field_mgr if y.key == cust_value.key][0]] = cust_value.value

            # Tags
            if tags_info:
                # Add virtual machine to appropriate tag group
                vm_mo_id = vm_obj.obj._GetMoId()  # pylint: disable=protected-access
                vm_dynamic_id = DynamicID(type='VirtualMachine', id=vm_mo_id)
                attached_tags = [tags_info[tag_id] for tag_id in tag_association.list_attached_tags(vm_dynamic_id)]
                properties['tags'] = attached_tags

            host_properties = to_nested_dict(properties)

            host = self._get_hostname(host_properties, hostnames, strict=strict)

            host_filters = self.get_option('filters')

            if host not in hostvars and self._can_add_host(host_filters, host_properties, host, strict=strict):
                hostvars[host] = host_properties
                self._populate_host_properties(host_properties, host)

        return hostvars
    def run(self):
        print('List all the existing categories user has access to...')
        categories = self.client.tagging.Category.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.client.tagging.Tag.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("Get category name and description...")
        category_ids = self.client.tagging.Category.list()
        for category_id in category_ids:
            category_model = self.client.tagging.Category.get(category_id)
            print("Category ID '{}', name '{}', description '{}'".format(
                category_model.id, category_model.name,
                category_model.description))

        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("Get tag name and description...")
        tag_ids = self.client.tagging.Tag.list()
        for tag_id in tag_ids:
            tag_model = self.client.tagging.Tag.get(tag_id)
            print("Tag ID '{}', name '{}', description '{}'".format(
                tag_model.id, tag_model.name, tag_model.description))

        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('Tagging the cluster {0}...'.format(self.cluster_name))
        self.dynamic_id = DynamicID(type='ClusterComputeResource',
                                    id=self.cluster_moid)
        self.client.tagging.TagAssociation.attach(tag_id=self.tag_id,
                                                  object_id=self.dynamic_id)
        for tag_id in self.client.tagging.TagAssociation.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))
示例#29
0
    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
    def _populate_from_source(self):
        """
        Populate inventory data from direct source

        """
        hostvars = {}
        strict = self.get_option("strict")

        host_properties = self.get_option("properties")
        if not isinstance(host_properties, list):
            host_properties = [host_properties]

        if len(host_properties) == 0:
            host_properties = ["name"]

        if "all" in host_properties:
            query_props = None
            host_properties.remove("all")
        else:
            if "runtime.connectionState" not in host_properties:
                host_properties.append("runtime.connectionState")
            query_props = [x for x in host_properties if x != "customValue"]

        objects = self.pyv.get_managed_objects_properties(
            vim_type=vim.HostSystem,
            properties=query_props,
            resources=self.get_option("resources"),
            strict=strict,
        )

        tags_info = dict()
        if self.pyv.with_tags:
            tag_svc = self.pyv.rest_content.tagging.Tag
            cat_svc = self.pyv.rest_content.tagging.Category

            tags = tag_svc.list()
            for tag in tags:
                tag_obj = tag_svc.get(tag)
                tags_info[tag_obj.id] = (
                    tag_obj.name,
                    cat_svc.get(tag_obj.category_id).name,
                )

        hostnames = self.get_option("hostnames")

        for host_obj in objects:
            properties = dict()
            for host_obj_property in host_obj.propSet:
                properties[host_obj_property.name] = host_obj_property.val

            if (properties.get("runtime.connectionState")
                    or properties["runtime"].connectionState) in (
                        "disconnected", "notResponding"):
                continue

            # Custom values
            if "customValue" in host_properties:
                field_mgr = []
                if self.pyv.content.customFieldsManager:  # not an ESXi
                    field_mgr = self.pyv.content.customFieldsManager.field
                for cust_value in host_obj.obj.customValue:
                    properties[[
                        y.name for y in field_mgr if y.key == cust_value.key
                    ][0]] = cust_value.value

            # Tags
            if self.pyv.with_tags:
                properties["tags"] = []
                properties["categories"] = []
                properties["tag_category"] = {}

            if tags_info:
                # Add virtual machine to appropriate tag group
                host_mo_id = host_obj.obj._GetMoId()  # pylint: disable=protected-access
                host_dynamic_id = DynamicID(type="HostSystem", id=host_mo_id)
                tag_association = self.pyv.rest_content.tagging.TagAssociation
                for tag_id in tag_association.list_attached_tags(
                        host_dynamic_id):
                    if tag_id not in tags_info:
                        # Ghost Tags
                        continue
                    # Add tags related to VM
                    properties["tags"].append(tags_info[tag_id][0])
                    # Add categories related to VM
                    properties["categories"].append(tags_info[tag_id][1])
                    # Add tag and categories related to VM
                    if tags_info[tag_id][1] not in properties["tag_category"]:
                        properties["tag_category"][tags_info[tag_id][1]] = []
                    properties["tag_category"][tags_info[tag_id][1]].append(
                        tags_info[tag_id][0])

            # Path
            with_path = self.get_option("with_path")
            if with_path:
                path = []
                parent = host_obj.obj.parent
                while parent:
                    path.append(parent.name)
                    parent = parent.parent
                path.reverse()
                properties["path"] = "/".join(path)

            host_properties = to_nested_dict(properties)

            # Check if we can add host as per filters
            host_filters = self.get_option("filters")
            if not self._can_add_host(
                    host_filters, host_properties, strict=strict):
                continue

            host = self._get_hostname(host_properties,
                                      hostnames,
                                      strict=strict)

            if host not in hostvars:
                hostvars[host] = host_properties
                self._populate_host_properties(host_properties, host)
                self.inventory.set_variable(
                    host, "ansible_host", self.get_management_ip(host_obj.obj))

        return hostvars