コード例 #1
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')
コード例 #2
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')
コード例 #3
0
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
コード例 #4
0
ファイル: vmware_tag_manager.py プロジェクト: ydd171/public
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)
コード例 #5
0
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)
コード例 #6
0
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
    print('Tagged vm: {0}'.format(vm_moid))
elif tag_op == "untag":
    print('Tagging the vm {0}...'.format(vm_moid))
    dynamic_id = DynamicID(type='VirtualMachine', id=vm_moid)
    tag_association.detach(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
コード例 #7
0
ファイル: tagging_workflow.py プロジェクト: kedr275/jk-2
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)