Ejemplo n.º 1
0
def main():
    argument_spec = VmwareRestClient.vmware_client_argument_spec()
    argument_spec.update(
        ovf_template=dict(type='str',
                          aliases=['template_src', 'ovf'],
                          required=True),
        name=dict(type='str', required=True, aliases=['vm_name']),
        datacenter=dict(type='str', required=True),
        datastore=dict(type='str', required=True),
        folder=dict(type='str', required=True),
        host=dict(type='str', required=True),
        resource_pool=dict(type='str', required=False),
        cluster=dict(type='str', required=False),
    )
    module = AnsibleModule(argument_spec=argument_spec,
                           supports_check_mode=True)
    result = {'failed': False, 'changed': False}
    pyv = PyVmomi(module=module)
    vm = pyv.get_vm()
    if vm:
        module.exit_json(changed=False,
                         vm_deploy_info=dict(
                             msg="Virtual Machine '%s' already Exists." %
                             module.params['name'],
                             vm_id=vm._moId,
                         ))
    vmware_contentlib_create = VmwareContentDeployOvfTemplate(module)
    if module.check_mode:
        result.update(
            vm_name=module.params['name'],
            changed=True,
            desired_operation='Create VM with PowerOff State',
        )
        module.exit_json(**result)
    vmware_contentlib_create.deploy_vm_from_ovf_template()
Ejemplo n.º 2
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')
Ejemplo n.º 3
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'),
        folder=dict(type='str', default='/vm'),
        question=dict(type='str', required=True),
        answer=dict(type='str', required=True),
    )

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

    result = dict(changed=True,)

    pyv = PyVmomi(module)

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

    if vm:
        # VM exists
        result['answer'] = answer_vm(vm=vm, question=module.params['question'], answer=module.params['answer'])
    else:
        module.fail_json(msg="Unable to answer non-existing virtual machine : '%s'" % (module.params.get('uuid') or module.params.get('name')))

    module.exit_json(**result)
Ejemplo n.º 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 == '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')
Ejemplo n.º 5
0
def test_vmdk_disk_path_split(mocker, fake_ansible_module):
    """ Test vmdk_disk_path_split function"""
    fake_ansible_module.params = test_data[0][0]

    mocker.patch('ansible.module_utils.vmware.connect_to_api', new=fake_connect_to_api)
    pyv = PyVmomi(fake_ansible_module)
    v = pyv.vmdk_disk_path_split('[ds1] VM_0001/VM0001_0.vmdk')
    assert v == ('ds1', 'VM_0001/VM0001_0.vmdk', 'VM0001_0.vmdk', 'VM_0001')
Ejemplo n.º 6
0
def test_vmdk_disk_path_split_negative(mocker, fake_ansible_module):
    """ Test vmdk_disk_path_split function"""
    fake_ansible_module.params = test_data[0][0]

    mocker.patch('ansible.module_utils.vmware.connect_to_api', new=fake_connect_to_api)
    with pytest.raises(FailJson) as exec_info:
        pyv = PyVmomi(fake_ansible_module)
        pyv.vmdk_disk_path_split('[ds1]')

    assert 'Bad path' in exec_info.value.kwargs['msg']
Ejemplo n.º 7
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),
        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']],
                           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_VCLOUD:
                    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:
        module.fail_json(msg="Unable to gather facts for non-existing VM %s" % (module.params.get('uuid') or
                                                                                module.params.get('name')))
 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 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'),
    )

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

    result = dict(changed=False, )

    pyv = PyVmomi(module)

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

    if vm:
        facts = pyv.gather_facts(vm)
        power_state = facts['hw_power_status'].lower()

        # VMware will fail the ReconfigVM_Task if the VM is powered on. For idempotency
        # in our UAT automation, we need to exit 'OK' and not change the VM if it is powered on.
        if power_state == 'poweredoff':
            result['uuid'] = str(uuid())
            config_spec = vim.vm.ConfigSpec()
            config_spec.uuid = result['uuid']
            try:
                task = vm.ReconfigVM_Task(config_spec)
                result['changed'], info = wait_for_task(task)
            except vmodl.fault.InvalidRequest as e:
                self.module.fail_json(
                    msg=
                    "Failed to modify bios.uuid of virtual machine due to invalid configuration "
                    "parameter %s" % to_native(e.msg))

    else:
        module.fail_json(
            msg=
            "Unable to set bios uuid for non-existing virtual machine : '%s'" %
            (module.params.get('uuid') or module.params.get('name')))

    module.exit_json(**result)
Ejemplo n.º 10
0
def main():
    argument_spec = VmwareRestClient.vmware_client_argument_spec()
    argument_spec.update(
        vm=dict(type='str', required=True),
        uuid=dict(type='str', required=True),
        tags=dict(type='dict', required=True),
        category_ids=dict(type='dict', required=True),
    )
    module = AnsibleModule(argument_spec=argument_spec)
    pyv = PyVmomi(module)
    vm = pyv.get_vm()
    vmware_tag = VmwareTag(module)
    result = vmware_tag.apply_tags(vm._moId, module.params['category_ids'],
                                   module.params['tags'])
    module.exit_json()
Ejemplo n.º 11
0
def test_pyvmomi_lib_exists(mocker, fake_ansible_module):
    """ Test if Pyvmomi is present or not"""
    mocker.patch('ansible.module_utils.vmware.HAS_PYVMOMI', new=False)
    with pytest.raises(FailJson) as exec_info:
        PyVmomi(fake_ansible_module)

    assert 'Failed to import the required Python library (PyVmomi) on' in exec_info.value.kwargs['msg']
def main():
    argument_spec = vmware_argument_spec()
    argument_spec.update(
        state=dict(type='str',
                   default='present',
                   choices=[
                       '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'),
        folder=dict(type='str', default='/vm'),
        force=dict(type='bool', default=False),
    )

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

    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
        result = set_vm_power_state(pyv.content, vm, module.params['state'],
                                    module.params['force'])
    else:
        module.fail_json(
            msg=
            "Unable to set power state for non-existing virtual machine : '%s'"
            % (module.params.get('uuid') or module.params.get('name')))

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

    module.exit_json(**result)
def test_requests_lib_exists(mocker, fake_ansible_module):
    """ Test if requests is present or not"""
    mocker.patch('ansible.module_utils.vmware.HAS_REQUESTS', new=False)
    with pytest.raises(FailJson) as exec_info:
        PyVmomi(fake_ansible_module)

    msg = "Unable to find 'requests' Python library which is required. Please install using 'pip install requests'"
    assert msg == exec_info.value.kwargs['msg']
def test_pyvmomi_lib_exists(mocker, fake_ansible_module):
    """ Test if Pyvmomi is present or not"""
    mocker.patch('ansible.module_utils.vmware.HAS_PYVMOMI', new=False)
    with pytest.raises(FailJson) as exec_info:
        PyVmomi(fake_ansible_module)

    assert 'PyVmomi Python module required. Install using "pip install PyVmomi"' == exec_info.value.kwargs[
        'msg']
Ejemplo n.º 15
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)
Ejemplo n.º 16
0
def test_validate_certs(mocker, fake_ansible_module):
    """ Test if SSL is required or not"""
    fake_ansible_module.params = test_data[3][0]

    mocker.patch('ansible.module_utils.vmware.ssl', new=None)
    with pytest.raises(FailJson) as exec_info:
        PyVmomi(fake_ansible_module)
    msg = 'pyVim does not support changing verification mode with python < 2.7.9.' \
          ' Either update python or use validate_certs=false.'
    assert msg == exec_info.value.kwargs['msg']
Ejemplo n.º 17
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'),
        folder=dict(type='str', default='/vm'),
        bootdelay=dict(type='int'),
        bootorder=dict(type='list'),
        bootretrydelay=dict(type='int'),
        bootretry=dict(type='bool'),
        enterbios=dict(type='bool'),
    )

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

    pyv = PyVmomi(module)

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

    if vm:
        result = build_hardware_map(vm, vim)
        #result = get_boot_options_vm(vm=vm)

        #changed, configspec = compare_boot_options(vim, result, module.params)

    else:
        module.fail_json(
            msg=
            "Unable to set boot options on non-existing virtual machine : '%s'"
            % (module.params.get('uuid') or module.params.get('name')))

    module.exit_json(**result)
    def __init__(self, module):
        """
        Constructor
        """
        super(VmwareObjectRename, self).__init__(module)
        self.pyv = PyVmomi(module=module)
        self.soap_stub = self.pyv.si._stub

        self.object_type = self.params.get('object_type')
        self.object_name = self.params.get('object_name')
        self.object_new_name = self.params.get('new_name')
        self.object_moid = self.params.get('object_moid')

        self.managed_object = None
def test_validate_certs(mocker, fake_ansible_module):
    """ Test if SSL is required or not"""
    fake_ansible_module.params = dict(
        username='******',
        password='******',
        hostname='esxi1',
        validate_certs=True,
    )

    mocker.patch('ansible.module_utils.vmware.ssl', new=None)
    with pytest.raises(FailJson) as exec_info:
        PyVmomi(fake_ansible_module)
    msg = 'pyVim does not support changing verification mode with python < 2.7.9.' \
          ' Either update python or use validate_certs=false.'
    assert msg == exec_info.value.kwargs['msg']
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'),
        folder=dict(type='str', default='/vm'),
        force=dict(type='bool', default=False),
        scheduled_at=dict(type='str'),
    )

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

    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 = {
                '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_desc = 'Schedule task for vm %s for operation %s at %s' % (vm.name,
                                                                                     module.params.get('state'),
                                                                                     scheduled_at)
            schedule_task_spec.name = schedule_task_desc
            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.get('state')]
            schedule_task_spec.enabled = True

            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'])
    else:
        module.fail_json(msg="Unable to set power state for non-existing virtual machine : '%s'" % (module.params.get('uuid') or module.params.get('name')))

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

    module.exit_json(**result)
Ejemplo n.º 21
0
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'),
        folder=dict(type='str', default='/vm'),
        force=dict(type='bool', default=False),
        scheduled_at=dict(type='str'),
        state_change_timeout=dict(type='int', default=0),
    )

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

    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 = {
                '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_desc = 'Schedule task for vm %s for operation %s at %s' % (vm.name,
                                                                                     module.params.get('state'),
                                                                                     scheduled_at)
            schedule_task_spec.name = schedule_task_desc
            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.get('state')]
            schedule_task_spec.enabled = True

            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'])
    else:
        module.fail_json(msg="Unable to set power state for non-existing virtual machine : '%s'" % (module.params.get('uuid') or module.params.get('name')))

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

    module.exit_json(**result)
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)
Ejemplo n.º 23
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
                    try:
                        self.tag_association_svc.attach(tag_id=tag_obj.id, object_id=self.dynamic_managed_object)
                        changed = True
                    except Error as error:
                        self.module.fail_json(msg="%s" % self.get_error_message(error))

            elif action == 'set':
                # Remove all tags first
                try:
                    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
                except Error as error:
                    self.module.fail_json(msg="%s" % self.get_error_message(error))

            elif action in ('remove', 'absent'):
                if tag_obj in available_tag_obj:
                    try:
                        self.tag_association_svc.detach(tag_id=tag_obj.id, object_id=self.dynamic_managed_object)
                        changed = True
                    except Error as error:
                        self.module.fail_json(msg="%s" % self.get_error_message(error))

        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)
Ejemplo n.º 24
0
def main():
    argument_spec = vmware_argument_spec()
    argument_spec.update(
        disk_provisioning=dict(type='str',
                               default='thin',
                               choices=[
                                   'flat', 'eagerZeroedThick',
                                   'monolithicSparse', 'twoGbMaxExtentSparse',
                                   'twoGbMaxExtentFlat', 'thin', 'sparse',
                                   'thick', 'seSparse', 'monolithicFlat'
                               ]),
        name=dict(type='str', required=True),
        datacenter=dict(type='str', default='ha-datacenter'),
        datastore=dict(type='str', default='datastore1'),
        resource_pool=dict(type='str', default='Resources'),
        name_match=dict(type='str', choices=['first', 'last'],
                        default='first'),
        networks=dict(type='list', default=[]),
        property_map=dict(type='dict', default={}),
        deployment_option=dict(type='str', default=None),
        uuid=dict(type='str'),
        folder=dict(type='str', default='/vm'),
        ovf_networks=dict(type='dict', default={'VM Network': 'VM Network'}),
        ovf=dict(type=path_exists),
        force=dict(type='bool', default=False),
        power_on=dict(type='bool', default=True),
        wait=dict(type='bool', default=True),
        wait_for_ip_address=dict(type='bool', default=True),
        guest_id=dict(type='str'),
        customization=dict(type='dict', default={}, no_log=True),
    )
    module = AnsibleModule(argument_spec=argument_spec, )

    if not module.params['power_on'] and (module.params['wait_for_ip_address']
                                          or module.params['wait']):
        module.fail_json(msg='Cannot wait for VM when power_on=False')

    if not HAS_PYVMOMI:
        module.fail_json(msg='pyvmomi python library not found')

    pyv_ovf = PyVmomi(module)
    pyv_vmomihelper = PyVmomiHelper(module)
    vm_ovf = pyv_ovf.get_vm()

    #vm_find = find_vm_by_name()
    #vm_ovf_helper = pyv_vmomihelper.get_vm()

    deploy_ovf = VMwareDeployOvf(module)
    deploy_ovf_PyVmH = PyVmomiHelper(module)

    vm = deploy_ovf.get_vm_obj()

    if vm:
        if vm.runtime.powerState != 'poweredOff':
            if module.params['force']:
                set_vm_power_state(deploy_ovf_PyVmH.content, vm, 'poweredoff',
                                   module.params['force'])
            else:
                module.fail_json(
                    msg=
                    "Virtual Machine is Powered ON. Please Power Off the VM or use force to power it off before doing any customizations."
                )
        if module.params['networks'] or module.params['customization']:
            deploy_ovf_PyVmH.customize_vm(vm)
            myspec = deploy_ovf_PyVmH.customspec
            task = vm.CustomizeVM_Task(spec=myspec)

            facts = deploy_ovf.vm_power_on(vm)

            #wait_for_task(task)
            #task_power=vm.PowerOn()
            #wait_for_task(task_power)
            #facts=pyv_vmomihelper.gather_facts(vm)

            #cust=self.customspec
            #deploy_ovf_PyVmH.customize_vm(vm_obj=vm)
            #customspec = vim.vm.customization.Specification()
        else:
            module.fail_json(
                msg=
                "VM already exists in the vCenter..! Use networks or customization parameters to customize the existing VM"
            )

    else:
        #deploy_ovf = VMwareDeployOvf(module)

        deploy_ovf.upload()
        deploy_ovf.complete()

        #facts = deploy_ovf.power_on()

        if module.params['networks'] or module.params['customization']:
            vm_deploy = deploy_ovf.get_vm_obj()
            deploy_ovf_PyVmH.customize_vm(vm_deploy)
            myspec = deploy_ovf_PyVmH.customspec
            task = vm_deploy.CustomizeVM_Task(spec=myspec)

            #            custom_wait_for_task(task, module)

            try:
                wait_for_task(task)
            except Exception, e:
                module.fail_json(msg="Error:%s" % e.message.msg)
            if task.info.state == 'error':
                module.fail_json(msg="Error occured: %s" %
                                 to_native(task.info.error.msg))

            try:
                facts = deploy_ovf.vm_power_on(vm_deploy)
            except Exception, e:
                module.fail_json(msg="Error from vCenter: %s" % (e.message))
def main():
    argument_spec = vmware_argument_spec()
    argument_spec.update(
        dict(
            remove_unmanaged_tasks=dict(type='bool', default=False),
            managed_tasks=dict(type='list', default=[]),
        ))

    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
    )

    result = {
        "changed": False,
        "vCenterScheduledTasksRemoved": [],
        "diff": {
            "before": [],
            "after": []
        }
    }

    pyv = PyVmomi(module)
    if not pyv.is_vcenter():
        module.fail_json(
            msg="vcenter_scheduled_tasks  is meant for vCenter, hostname %s "
            "is not vCenter server." % module.params.get('hostname'))

    existingScheduledTasks = pyv.content.scheduledTaskManager.RetrieveEntityScheduledTask(
    )

    for existingScheduledTask in existingScheduledTasks:
        result['diff']['before'].append(existingScheduledTask.info.name)

    diffs = diffcheck(result['diff']['before'], module.params['managed_tasks'])

    if diffs:
        if module.params['remove_unmanaged_tasks']:
            for diff in diffs:
                existingScheduledTasks = pyv.content.scheduledTaskManager.RetrieveEntityScheduledTask(
                )
                for existingScheduledTask in existingScheduledTasks:
                    if diff == existingScheduledTask.info.name:
                        existingScheduledTask.RemoveScheduledTask()
                        result['vCenterScheduledTasksRemoved'].append(diff)
                        result['changed'] = True
                    else:
                        module.debug(
                            'This task is managed by ansible config - not deleting "%s"'
                            % diff)
        else:
            module.debug(
                'argurment remove_unmanaged_tasks is false so skipping the removal of unmanaged tasks'
            )
    else:
        module.debug(
            'There is no difference between desired state and current state - no changes required'
        )

    existingScheduledTasks = pyv.content.scheduledTaskManager.RetrieveEntityScheduledTask(
    )
    for existingScheduledTask in existingScheduledTasks:
        result['diff']['after'].append(existingScheduledTask.info.name)

    module.exit_json(**result)
Ejemplo n.º 26
0
def vmware_guest_facts(VcenterConfig: VcenterConfig,
                       show_attribute=False,
                       datacenter='Datacenter',
                       uuid='',
                       schema='summary',
                       name='') -> dict:
    """

    :param VcenterConfig:
    :param show_attribute:
    :param datacenter:
    :param uuid:
    :param schema:
    :param name:
    :return: {
        "annotation": "",
        "current_snapshot": null,
        "customvalues": {},
        "guest_consolidation_needed": false,
        "guest_question": null,
        "guest_tools_status": "guestToolsNotRunning",
        "guest_tools_version": "10247",
        "hw_cores_per_socket": 1,
        "hw_datastores": [
            "ds_226_3"
        ],
        "hw_esxi_host": "10.76.33.226",
        "hw_eth0": {
            "addresstype": "assigned",
            "ipaddresses": null,
            "label": "Network adapter 1",
            "macaddress": "00:50:56:87:a5:9a",
            "macaddress_dash": "00-50-56-87-a5-9a",
            "portgroup_key": null,
            "portgroup_portkey": null,
            "summary": "VM Network"
        },
        "hw_files": [
            "[ds_226_3] ubuntu_t/ubuntu_t.vmx",
            "[ds_226_3] ubuntu_t/ubuntu_t.nvram",
            "[ds_226_3] ubuntu_t/ubuntu_t.vmsd",
            "[ds_226_3] ubuntu_t/vmware.log",
            "[ds_226_3] u0001/u0001.vmdk"
        ],
        "hw_folder": "/DC0/vm/Discovered virtual machine",
        "hw_guest_full_name": null,
        "hw_guest_ha_state": null,
        "hw_guest_id": null,
        "hw_interfaces": [
            "eth0"
        ],
        "hw_is_template": false,
        "hw_memtotal_mb": 1024,
        "hw_name": "ubuntu_t",
        "hw_power_status": "poweredOff",
        "hw_processor_count": 1,
        "hw_product_uuid": "4207072c-edd8-3bd5-64dc-903fd3a0db04",
        "hw_version": "vmx-13",
        "instance_uuid": "5007769d-add3-1e12-f1fe-225ae2a07caf",
        "ipv4": null,
        "ipv6": null,
        "module_hw": true,
        "snapshots": [],
        "tags": [
            "backup"
        ],
        "vnc": {}
    }
    """

    argument_spec = {
        'show_attribute': show_attribute,
        'datacenter': datacenter,
        # 'uuid': uuid,
        'schema': schema,
        # 'name': name
    }

    if uuid:
        argument_spec['uuid'] = uuid
    if name:
        argument_spec['name'] = name

    argument_spec.update(**VcenterConfig.as_dict())

    # print(argument_spec)

    module = AnsibleModule(argument_spec=argument_spec,
                           supports_check_mode=True)

    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'):
                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))
            return instance
            # module.exit_json(instance=instance)
        except Exception as exc:
            module.fail_json(msg="Fact gather failed with exception %s" %
                             to_text(exc))
    else:
        module.fail_json(
            msg="Unable to gather facts for non-existing VM %s" %
            (module.params.get('uuid') or module.params.get('name')))
Ejemplo n.º 27
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')

        if self.object_type == 'VirtualMachine':
            self.managed_object = self.pyv.get_vm_or_template(self.object_name)
            self.dynamic_managed_object = DynamicID(
                type=self.object_type, id=self.managed_object._moId)

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

        self.tag_service = Tag(self.connect)
        self.category_service = Category(self.connect)
        self.tag_association_svc = TagAssociation(self.connect)

        self.tag_names = self.params.get('tag_names')

    def 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)