コード例 #1
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 == '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')
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')
    )
    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/60/vcloudsuite-python")

                vm_rest_client = VmwareTag(module)
                instance.update(
                    tags=vm_rest_client.get_vm_tags(vm_rest_client.tag_service,
                                                    vm_rest_client.tag_association_svc,
                                                    vm_mid=vm._moId)
                )
            module.exit_json(instance=instance)
        except Exception as exc:
            module.fail_json(msg="Fact gather 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 facts for non-existing VM %s" % vm_id)
コード例 #3
0
 def __init__(self, module):
     """Constructor."""
     super(VmwareContentLibCreate, self).__init__(module)
     self.content_service = self.api_client
     self.local_libraries = dict()
     self.library_name = self.params.get('library_name')
     self.library_description = self.params.get('library_description')
     self.library_type = self.params.get('library_type')
     self.library_types = dict()
     self.datastore_name = self.params.get('datastore_name')
     self.get_all_libraries()
     self.pyv = PyVmomi(module=module)
コード例 #4
0
def main():
    argument_spec = vmware_argument_spec()
    argument_spec.update(state=dict(type='str',
                                    default='present',
                                    choices=['present', 'absent']),
                         name=dict(type='str'),
                         name_match=dict(type='str',
                                         choices=['first', 'last'],
                                         default='first'),
                         uuid=dict(type='str'),
                         moid=dict(type='str'),
                         folder=dict(type='str'),
                         vnc_ip=dict(type='str', default='0.0.0.0'),
                         vnc_port=dict(type='int', default=0),
                         vnc_password=dict(type='str', default='',
                                           no_log=True),
                         datacenter=dict(type='str', default='ha-datacenter'))

    module = AnsibleModule(argument_spec=argument_spec,
                           supports_check_mode=True,
                           required_one_of=[['name', 'uuid', 'moid']],
                           mutually_exclusive=[['name', 'uuid', 'moid']])

    result = dict(changed=False, failed=False)

    pyv = PyVmomi(module)
    vm = pyv.get_vm()
    if vm:
        result = set_vnc_extraconfig(pyv.content, vm,
                                     (module.params['state'] == "present"),
                                     module.params['vnc_ip'],
                                     module.params['vnc_port'],
                                     module.params['vnc_password'])
    else:
        vm_id = module.params.get('uuid') or module.params.get(
            'name') or module.params.get('moid')
        module.fail_json(
            msg=
            "Unable to set VNC config for non-existing virtual machine : '%s'"
            % vm_id)

    if result.get('failed') is True:
        module.fail_json(**result)

    module.exit_json(**result)
def main():
    argument_spec = vmware_argument_spec()
    argument_spec.update(
        state=dict(type='str',
                   default='present',
                   choices=[
                       'present', 'powered-off', 'powered-on', 'reboot-guest',
                       'restarted', 'shutdown-guest', 'suspended'
                   ]),
        name=dict(type='str'),
        name_match=dict(type='str', choices=['first', 'last'],
                        default='first'),
        uuid=dict(type='str'),
        moid=dict(type='str'),
        use_instance_uuid=dict(type='bool', default=False),
        folder=dict(type='str'),
        force=dict(type='bool', default=False),
        scheduled_at=dict(type='str'),
        schedule_task_name=dict(),
        schedule_task_description=dict(),
        schedule_task_enabled=dict(type='bool', default=True),
        state_change_timeout=dict(type='int', default=0),
    )

    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=False,
        mutually_exclusive=[
            ['name', 'uuid', 'moid'],
        ],
    )

    result = dict(changed=False, )

    pyv = PyVmomi(module)

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

    if vm:
        # VM already exists, so set power state
        scheduled_at = module.params.get('scheduled_at', None)
        if scheduled_at:
            if not pyv.is_vcenter():
                module.fail_json(
                    msg="Scheduling task requires vCenter, hostname %s "
                    "is an ESXi server." % module.params.get('hostname'))
            powerstate = {
                'present': vim.VirtualMachine.PowerOn,
                'powered-off': vim.VirtualMachine.PowerOff,
                'powered-on': vim.VirtualMachine.PowerOn,
                'reboot-guest': vim.VirtualMachine.RebootGuest,
                'restarted': vim.VirtualMachine.Reset,
                'shutdown-guest': vim.VirtualMachine.ShutdownGuest,
                'suspended': vim.VirtualMachine.Suspend,
            }
            dt = ''
            try:
                dt = datetime.strptime(scheduled_at, '%d/%m/%Y %H:%M')
            except ValueError as e:
                module.fail_json(
                    msg=
                    "Failed to convert given date and time string to Python datetime object,"
                    "please specify string in 'dd/mm/yyyy hh:mm' format: %s" %
                    to_native(e))
            schedule_task_spec = vim.scheduler.ScheduledTaskSpec()
            schedule_task_name = module.params[
                'schedule_task_name'] or 'task_%s' % str(randint(10000, 99999))
            schedule_task_desc = module.params['schedule_task_description']
            if schedule_task_desc is None:
                schedule_task_desc = 'Schedule task for vm %s for ' \
                                     'operation %s at %s' % (vm.name, module.params['state'], scheduled_at)
            schedule_task_spec.name = schedule_task_name
            schedule_task_spec.description = schedule_task_desc
            schedule_task_spec.scheduler = vim.scheduler.OnceTaskScheduler()
            schedule_task_spec.scheduler.runAt = dt
            schedule_task_spec.action = vim.action.MethodAction()
            schedule_task_spec.action.name = powerstate[module.params['state']]
            schedule_task_spec.enabled = module.params['schedule_task_enabled']

            try:
                pyv.content.scheduledTaskManager.CreateScheduledTask(
                    vm, schedule_task_spec)
                # As this is async task, we create scheduled task and mark state to changed.
                module.exit_json(changed=True)
            except vim.fault.InvalidName as e:
                module.fail_json(
                    msg="Failed to create scheduled task %s for %s : %s" %
                    (module.params.get('state'), vm.name, to_native(e.msg)))
            except vim.fault.DuplicateName as e:
                module.exit_json(chanaged=False, details=to_native(e.msg))
            except vmodl.fault.InvalidArgument as e:
                module.fail_json(
                    msg="Failed to create scheduled task %s as specifications "
                    "given are invalid: %s" %
                    (module.params.get('state'), to_native(e.msg)))
        else:
            result = set_vm_power_state(pyv.content, vm,
                                        module.params['state'],
                                        module.params['force'],
                                        module.params['state_change_timeout'])
    else:
        id = module.params.get('uuid') or module.params.get(
            'moid') or module.params.get('name')
        module.fail_json(
            msg=
            "Unable to set power state for non-existing virtual machine : '%s'"
            % id)

    if result.get('failed') is True:
        module.fail_json(**result)

    module.exit_json(**result)
コード例 #6
0
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 = 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 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)
コード例 #7
0
class VmwareContentLibCreate(VmwareRestClient):
    def __init__(self, module):
        """Constructor."""
        super(VmwareContentLibCreate, self).__init__(module)
        self.content_service = self.api_client
        self.local_libraries = dict()
        self.library_name = self.params.get('library_name')
        self.library_description = self.params.get('library_description')
        self.library_type = self.params.get('library_type')
        self.library_types = dict()
        self.datastore_name = self.params.get('datastore_name')
        self.get_all_libraries()
        self.pyv = PyVmomi(module=module)

    def process_state(self):
        """
        Manage states of Content Library
        """
        self.desired_state = self.params.get('state')
        library_states = {
            'absent': {
                'present': self.state_destroy_library,
                'absent': self.state_exit_unchanged,
            },
            'present': {
                'present': self.state_update_library,
                'absent': self.state_create_library,
            }
        }
        library_states[self.desired_state][
            self.check_content_library_status()]()

    def get_all_libraries(self):
        content_libs = self.content_service.content.LocalLibrary.list()
        if content_libs:
            for content_lib in content_libs:
                lib_details = self.content_service.content.LocalLibrary.get(
                    content_lib)
                self.local_libraries[lib_details.name] = dict(
                    lib_name=lib_details.name,
                    lib_description=lib_details.description,
                    lib_id=lib_details.id,
                    lib_type=lib_details.type)

    def check_content_library_status(self):
        """
        Check if Content Library exists or not
        Returns: 'present' if library found, else 'absent'

        """
        ret = 'present' if self.library_name in self.local_libraries else 'absent'
        return ret

    def state_create_library(self):
        # Find the datastore by the given datastore name
        datastore_id = self.pyv.find_datastore_by_name(
            datastore_name=self.datastore_name)
        if not datastore_id:
            self.module.fail_json(msg="Failed to find the datastore %s" %
                                  self.datastore_name)
        self.datastore_id = datastore_id._moId
        # Build the storage backing for the library to be created
        storage_backings = []
        storage_backing = StorageBacking(type=StorageBacking.Type.DATASTORE,
                                         datastore_id=self.datastore_id)
        storage_backings.append(storage_backing)

        # Build the specification for the library to be created
        create_spec = LibraryModel()
        create_spec.name = self.library_name
        create_spec.description = self.library_description
        self.library_types = {
            'local': create_spec.LibraryType.LOCAL,
            'subscribed': create_spec.LibraryType.SUBSCRIBED
        }
        create_spec.type = self.library_types[self.library_type]
        create_spec.storage_backings = storage_backings

        # Create a local content library backed the VC datastore
        library_id = self.content_service.content.LocalLibrary.create(
            create_spec=create_spec, client_token=str(uuid.uuid4()))
        if library_id:
            self.module.exit_json(
                changed=True,
                content_library_info=dict(
                    msg="Content Library '%s' created." % create_spec.name,
                    library_id=library_id,
                    library_description=self.library_description,
                    library_type=create_spec.type,
                ))
        self.module.exit_json(
            changed=False,
            content_library_info=dict(
                msg=
                "Content Library not created. Datastore and library_type required",
                library_id=''))

    def state_update_library(self):
        """
        Update Content Library

        """
        changed = False
        library_id = self.local_libraries[self.library_name]['lib_id']
        content_library_info = dict(msg="Content Library %s is unchanged." %
                                    self.library_name,
                                    library_id=library_id)
        library_update_spec = LibraryModel()
        library_desc = self.local_libraries[
            self.library_name]['lib_description']
        desired_lib_desc = self.params.get('library_description')
        if library_desc != desired_lib_desc:
            library_update_spec.description = desired_lib_desc
            self.content_service.content.LocalLibrary.update(
                library_id, library_update_spec)
            content_library_info[
                'msg'] = 'Content Library %s updated.' % self.library_name
            changed = True

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

    def state_destroy_library(self):
        """
        Delete Content Library

        """
        library_id = self.local_libraries[self.library_name]['lib_id']
        self.content_service.content.LocalLibrary.delete(library_id=library_id)
        self.module.exit_json(
            changed=True,
            content_library_info=dict(msg="Content Library '%s' deleted." %
                                      self.library_name,
                                      library_id=library_id))

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

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