Exemple #1
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
Exemple #2
0
class VmwareTag(VmwareRestClient):
    def __init__(self, module):
        super(VmwareTag, self).__init__(module)
        self.tag_service = Tag(self.connect)
        self.global_tags = dict()
        self.tag_name = self.params.get('tag_name')
        self.get_all_tags()
        self.category_service = Category(self.connect)

    def ensure_state(self):
        """
        Manage internal states of tags

        """
        desired_state = self.params.get('state')
        states = {
            'present': {
                'present': self.state_update_tag,
                'absent': self.state_create_tag,
            },
            'absent': {
                'present': self.state_delete_tag,
                'absent': self.state_unchanged,
            }
        }
        states[desired_state][self.check_tag_status()]()

    def state_create_tag(self):
        """
        Create tag

        """
        tag_spec = self.tag_service.CreateSpec()
        tag_spec.name = self.tag_name
        tag_spec.description = self.params.get('tag_description')
        category_id = self.params.get('category_id', None)
        if category_id is None:
            self.module.fail_json(msg="'category_id' is required parameter while creating tag.")

        category_found = False
        for category in self.category_service.list():
            category_obj = self.category_service.get(category)
            if category_id == category_obj.id:
                category_found = True
                break

        if not category_found:
            self.module.fail_json(msg="Unable to find category specified using 'category_id' - %s" % category_id)

        tag_spec.category_id = category_id
        tag_id = self.tag_service.create(tag_spec)
        if tag_id:
            self.module.exit_json(changed=True,
                                  results=dict(msg="Tag '%s' created." % tag_spec.name,
                                               tag_id=tag_id))
        self.module.exit_json(changed=False,
                              results=dict(msg="No tag created", tag_id=''))

    def state_unchanged(self):
        """
        Return unchanged state

        """
        self.module.exit_json(changed=False)

    def state_update_tag(self):
        """
        Update tag

        """
        changed = False
        tag_id = self.global_tags[self.tag_name]['tag_id']
        results = dict(msg="Tag %s is unchanged." % self.tag_name,
                       tag_id=tag_id)
        tag_update_spec = self.tag_service.UpdateSpec()
        tag_desc = self.global_tags[self.tag_name]['tag_description']
        desired_tag_desc = self.params.get('tag_description')
        if tag_desc != desired_tag_desc:
            tag_update_spec.description = desired_tag_desc
            self.tag_service.update(tag_id, tag_update_spec)
            results['msg'] = 'Tag %s updated.' % self.tag_name
            changed = True

        self.module.exit_json(changed=changed, results=results)

    def state_delete_tag(self):
        """
        Delete tag

        """
        tag_id = self.global_tags[self.tag_name]['tag_id']
        self.tag_service.delete(tag_id=tag_id)
        self.module.exit_json(changed=True,
                              results=dict(msg="Tag '%s' deleted." % self.tag_name,
                                           tag_id=tag_id))

    def check_tag_status(self):
        """
        Check if tag exists or not
        Returns: 'present' if tag found, else 'absent'

        """
        ret = 'present' if self.tag_name in self.global_tags else 'absent'
        return ret

    def get_all_tags(self):
        """
        Retrieve all tag information

        """
        for tag in self.tag_service.list():
            tag_obj = self.tag_service.get(tag)
            self.global_tags[tag_obj.name] = 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
                                                  )
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)