Example #1
0
def test_required_params(request, params, msg, fake_ansible_module):
    """ Test if required params are correct or not"""
    fake_ansible_module.params = params
    with pytest.raises(FailJsonException):
        vmware_module_utils.connect_to_api(fake_ansible_module)
    assert fake_ansible_module.fail_json.called_once()
    assert msg in fake_ansible_module.fail_json.call_args[1]['msg']
Example #2
0
def main():

    argument_spec = vmware_argument_spec()
    argument_spec.update(
        dict(vmk_name=dict(required=True, type='str'),
             ip_address=dict(required=True, type='str'),
             subnet_mask=dict(required=True, type='str')))

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

    if not HAS_PYVMOMI:
        module.fail_json(msg='pyvmomi is required for this module')

    vmk_name = module.params['vmk_name']
    ip_address = module.params['ip_address']
    subnet_mask = module.params['subnet_mask']

    try:
        content = connect_to_api(module, False)
        host = get_all_objs(content, [vim.HostSystem])
        if not host:
            module.fail_json(msg="Unable to locate Physical Host.")
        host_system = list(host)[0]
        changed = configure_vmkernel_ip_address(host_system, vmk_name,
                                                ip_address, subnet_mask)
        module.exit_json(changed=changed)
    except vmodl.RuntimeFault as runtime_fault:
        module.fail_json(msg=runtime_fault.msg)
    except vmodl.MethodFault as method_fault:
        module.fail_json(msg=method_fault.msg)
    except Exception as e:
        module.fail_json(msg=str(e))
Example #3
0
def main():

    argument_spec = vmware_argument_spec()
    argument_spec.update(dict(cluster_uuid=dict(required=False, type='str')))

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

    if not HAS_PYVMOMI:
        module.fail_json(msg='pyvmomi is required for this module')

    new_cluster_uuid = module.params['cluster_uuid']

    try:
        content = connect_to_api(module, False)
        host = get_all_objs(content, [vim.HostSystem])
        if not host:
            module.fail_json(msg="Unable to locate Physical Host.")
        host_system = list(host)[0]
        changed, result, cluster_uuid = create_vsan_cluster(
            host_system, new_cluster_uuid)
        module.exit_json(changed=changed,
                         result=result,
                         cluster_uuid=cluster_uuid)

    except vmodl.RuntimeFault as runtime_fault:
        module.fail_json(msg=runtime_fault.msg)
    except vmodl.MethodFault as method_fault:
        module.fail_json(msg=method_fault.msg)
    except Exception as e:
        module.fail_json(msg=str(e))
Example #4
0
def main():

    argument_spec = vmware_argument_spec()
    argument_spec.update(
        dict(change_hostname_to=dict(required=True, type='str'),
             domainname=dict(required=True, type='str'),
             dns_servers=dict(required=True, type='list')))

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

    if not HAS_PYVMOMI:
        module.fail_json(msg='pyvmomi is required for this module')

    change_hostname_to = module.params['change_hostname_to']
    domainname = module.params['domainname']
    dns_servers = module.params['dns_servers']
    try:
        content = connect_to_api(module)
        host = get_all_objs(content, [vim.HostSystem])
        if not host:
            module.fail_json(msg="Unable to locate Physical Host.")
        host_system = list(host)[0]
        changed = configure_dns(host_system, change_hostname_to, domainname,
                                dns_servers)
        module.exit_json(changed=changed)
    except vmodl.RuntimeFault as runtime_fault:
        module.fail_json(msg=runtime_fault.msg)
    except vmodl.MethodFault as method_fault:
        module.fail_json(msg=method_fault.msg)
    except Exception as e:
        module.fail_json(msg=str(e))
def main():
    argument_spec = vmware_argument_spec()
    argument_spec.update(cluster_name=dict(required=True, type='str'),
                         fetch_from_cache=dict(required=False, type='bool'))

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

    if not HAS_PYVMOMI:
        module.fail_json(msg=missing_required_lib('PyVmomi'),
                         exception=PYVMOMI_IMP_ERR)

    if not HAS_VSANPYTHONSDK:
        module.fail_json(
            msg=missing_required_lib('vSAN Management SDK for Python'),
            exception=VSANPYTHONSDK_IMP_ERR)

    if not HAS_PYVMOMIJSON:
        module.fail_json(
            msg=
            'The installed version of pyvmomi lacks JSON output support; need pyvmomi>6.7.1'
        )

    try:
        si, content = connect_to_api(module, True, True)
    except Exception as e:
        module.fail_json(msg=e.msg)

    client_stub = si._GetStub()
    ssl_context = client_stub.schemeArgs.get('context')

    cluster = find_cluster_by_name(content, module.params['cluster_name'])

    if not cluster:
        module.fail_json(msg="Failed to find cluster %s" %
                         module.params['cluster_name'])

    apiVersion = vsanapiutils.GetLatestVmodlVersion(module.params['hostname'])
    vcMos = vsanapiutils.GetVsanVcMos(client_stub,
                                      context=ssl_context,
                                      version=apiVersion)

    vsanClusterHealthSystem = vcMos['vsan-cluster-health-system']

    try:
        clusterHealth = vsanClusterHealthSystem.VsanQueryVcClusterHealthSummary(
            cluster=cluster, fetchFromCache=module.params['fetch_from_cache'])
    except vmodl.fault.NotFound as not_found:
        module.fail_json(msg=not_found.msg)
    except vmodl.fault.RuntimeFault as runtime_fault:
        module.fail_json(msg=runtime_fault.msg)

    health = json.dumps(clusterHealth,
                        cls=VmomiSupport.VmomiJSONEncoder,
                        sort_keys=True,
                        strip_dynamic=True)

    module.exit_json(changed=False, vsan_health_info=health)
 def __init__(self, module):
     self.module = module
     self.host_system = None
     self.migrate_switch_name = self.module.params['migrate_switch_name']
     self.migrate_portgroup_name = self.module.params['migrate_portgroup_name']
     self.device = self.module.params['device']
     self.esxi_hostname = self.module.params['esxi_hostname']
     self.current_portgroup_name = self.module.params['current_portgroup_name']
     self.current_switch_name = self.module.params['current_switch_name']
     self.content = connect_to_api(module)
    def sanitize_params(self):
        '''
        this method is used to verify user provided parameters
        '''
        self.vm_obj = self.get_vm()
        if self.vm_obj is None:
            vm_id = self.vm_uuid or self.vm_name or self.moid
            self.module.fail_json(
                msg="Failed to find the VM/template with %s" % vm_id)

        # connect to destination VC
        self.destination_content = connect_to_api(
            self.module,
            hostname=self.destination_vcenter,
            username=self.destination_vcenter_username,
            password=self.destination_vcenter_password,
            port=self.destination_vcenter_port,
            validate_certs=self.destination_vcenter_validate_certs)

        # Check if vm name already exists in the destination VC
        vm = find_vm_by_name(content=self.destination_content,
                             vm_name=self.params['destination_vm_name'])
        if vm:
            self.module.exit_json(
                changed=False, msg="A VM with the given name already exists")

        datastore_name = self.params['destination_datastore']
        datastore_cluster = find_obj(self.destination_content,
                                     [vim.StoragePod], datastore_name)
        if datastore_cluster:
            # If user specified datastore cluster so get recommended datastore
            datastore_name = self.get_recommended_datastore(
                datastore_cluster_obj=datastore_cluster)
            # Check if get_recommended_datastore or user specified datastore exists or not
        self.destination_datastore = find_datastore_by_name(
            content=self.destination_content, datastore_name=datastore_name)
        if self.destination_datastore is None:
            self.module.fail_json(msg="Destination datastore not found.")

        self.destination_host = find_hostsystem_by_name(
            content=self.destination_content,
            hostname=self.params['destination_host'])
        if self.destination_host is None:
            self.module.fail_json(msg="Destination host not found.")

        if self.params['destination_resource_pool']:
            self.destination_resource_pool = find_resource_pool_by_name(
                content=self.destination_content,
                resource_pool_name=self.params['destination_resource_pool'])
        else:
            self.destination_resource_pool = self.destination_host.parent.resourcePool
Example #8
0
 def __init__(self, module):
     self.module = module
     self.datacenter = module.params['datacenter']
     self.cluster = module.params['cluster']
     self.resource_pool = module.params['resource_pool']
     self.hostname = module.params['hostname']
     self.username = module.params['username']
     self.password = module.params['password']
     self.state = module.params['state']
     self.mem_shares = module.params['mem_shares']
     self.mem_limit = module.params['mem_limit']
     self.mem_reservation = module.params['mem_reservation']
     self.mem_expandable_reservations = module.params[
         'cpu_expandable_reservations']
     self.cpu_shares = module.params['cpu_shares']
     self.cpu_limit = module.params['cpu_limit']
     self.cpu_reservation = module.params['cpu_reservation']
     self.cpu_expandable_reservations = module.params[
         'cpu_expandable_reservations']
     self.dc_obj = None
     self.cluster_obj = None
     self.host_obj = None
     self.resource_pool_obj = None
     self.content = connect_to_api(module)
Example #9
0
def main():
    argument_spec = vmware_argument_spec()
    argument_spec.update(
        dict(
            extension_key=dict(type='str', required=True),
            version=dict(type='str', required=True),
            email=dict(type='str', required=False),
            description=dict(type='str', required=False),
            company=dict(type='str', required=False),
            name=dict(type='str', required=False),
            url=dict(type='str', required=False),
            ssl_thumbprint=dict(type='str', required=False),
            client_type=dict(type='str',
                             default='vsphere-client-serenity',
                             required=False),
            server_type=dict(type='str',
                             default='vsphere-client-serenity',
                             required=False),
            visible=dict(type='bool', default='True', required=False),
            state=dict(type='str',
                       default='present',
                       choices=['absent', 'present']),
        ))

    module = AnsibleModule(argument_spec=argument_spec,
                           supports_check_mode=False,
                           required_if=[[
                               'state', 'present',
                               [
                                   'email', 'description', 'company', 'name',
                                   'url', 'ssl_thumbprint', 'server_type',
                                   'client_type'
                               ]
                           ]])

    state = module.params['state']
    extension_key = module.params['extension_key']
    version = module.params['version']
    email = module.params['email']
    desc = module.params['description']
    name = module.params['name']
    company = module.params['company']
    client_type = module.params['client_type']
    server_type = module.params['server_type']
    url = module.params['url']
    visible = module.params['visible']
    thumbprint = module.params['ssl_thumbprint']

    content = connect_to_api(module, False)
    em = content.extensionManager
    key_check = em.FindExtension(extension_key)
    results = dict(changed=False, installed=dict())

    if state == 'present' and key_check:
        results['changed'] = False
        results['installed'] = "'%s' is already installed" % (extension_key)

    elif state == 'present' and not key_check:
        extension = vim.Extension()
        extension.key = extension_key
        extension.company = company
        extension.version = version
        extension.lastHeartbeatTime = datetime.datetime.now()
        description = vim.Description()
        description.label = name
        description.summary = desc
        extension.description = description
        extension.shownInSolutionManager = visible

        client = vim.Extension.ClientInfo()
        client.company = company
        client.version = version
        client.description = description
        client.type = client_type
        client.url = url
        extension.client = [client]

        server = vim.Extension.ServerInfo()
        server.company = company
        server.description = description
        server.type = server_type
        server.adminEmail = email
        server.serverThumbprint = thumbprint
        server.url = url
        extension.server = [server]

        em.RegisterExtension(extension)
        results['changed'] = True
        results['installed'] = "'%s' installed." % (extension_key)

    elif state == 'absent' and key_check:
        em.UnregisterExtension(extension_key)
        results['changed'] = True
        results['installed'] = "'%s' uninstalled." % (extension_key)

    elif state == 'absent' and not key_check:
        results['changed'] = False
        results['installed'] = "'%s' is not installed." % (extension_key)

    module.exit_json(**results)
Example #10
0
 def __init__(self, module):
     self.module = module
     self.content = connect_to_api(module)
     self.vm = None
     self.vm_name = module.params['vm_name']
     self.dvportgroup_name = module.params['dvportgroup_name']
Example #11
0
def test_connect_to_api_validate_certs(monkeypatch, fake_ansible_module):
    monkeypatch.setattr(vmware_module_utils, 'connect', mock.Mock())

    def MockSSLContext(proto):
        ssl_context.proto = proto
        return ssl_context

    # New Python with SSLContext + validate_certs=True
    vmware_module_utils.connect.reset_mock()
    ssl_context = mock.Mock()
    monkeypatch.setattr(vmware_module_utils.ssl, 'SSLContext', MockSSLContext)
    fake_ansible_module.params['validate_certs'] = True
    vmware_module_utils.connect_to_api(fake_ansible_module)
    assert ssl_context.proto == ssl.PROTOCOL_SSLv23
    assert ssl_context.verify_mode == ssl.CERT_REQUIRED
    assert ssl_context.check_hostname is True
    vmware_module_utils.connect.SmartConnect.assert_called_once_with(
        host='esxi1',
        port=443,
        pwd='Esxi@123$%',
        user='******',
        sslContext=ssl_context)

    # New Python with SSLContext + validate_certs=False
    vmware_module_utils.connect.reset_mock()
    ssl_context = mock.Mock()
    monkeypatch.setattr(vmware_module_utils.ssl, 'SSLContext', MockSSLContext)
    fake_ansible_module.params['validate_certs'] = False
    vmware_module_utils.connect_to_api(fake_ansible_module)
    assert ssl_context.proto == ssl.PROTOCOL_SSLv23
    assert ssl_context.verify_mode == ssl.CERT_NONE
    assert ssl_context.check_hostname is False
    vmware_module_utils.connect.SmartConnect.assert_called_once_with(
        host='esxi1',
        port=443,
        pwd='Esxi@123$%',
        user='******',
        sslContext=ssl_context)

    # Old Python with no SSLContext + validate_certs=True
    vmware_module_utils.connect.reset_mock()
    ssl_context = mock.Mock()
    ssl_context.proto = None
    monkeypatch.delattr(vmware_module_utils.ssl, 'SSLContext')
    fake_ansible_module.params['validate_certs'] = True
    with pytest.raises(FailJsonException):
        vmware_module_utils.connect_to_api(fake_ansible_module)
    assert ssl_context.proto is None
    fake_ansible_module.fail_json.assert_called_once_with(
        msg=('pyVim does not support changing verification mode with python '
             '< 2.7.9. Either update python or use validate_certs=false.'))
    assert not vmware_module_utils.connect.SmartConnect.called

    # Old Python with no SSLContext + validate_certs=False
    vmware_module_utils.connect.reset_mock()
    ssl_context = mock.Mock()
    ssl_context.proto = None
    monkeypatch.delattr(vmware_module_utils.ssl, 'SSLContext', raising=False)
    fake_ansible_module.params['validate_certs'] = False
    vmware_module_utils.connect_to_api(fake_ansible_module)
    assert ssl_context.proto is None
    vmware_module_utils.connect.SmartConnect.assert_called_once_with(
        host='esxi1',
        port=443,
        pwd='Esxi@123$%',
        user='******')