Esempio n. 1
0
    def create_event_keyvalue_pairs(self):
        try:

            eri_list = []
            resource_folder_path = self.middleware.call_sync(
                'vcenter.resource_folder_path')
            for file in os.listdir(resource_folder_path):
                eri = vim.Extension.ResourceInfo()

                # Read locale file from vcp_locale
                eri.module = file.split("_")[0]
                with open(os.path.join(resource_folder_path, file),
                          'r') as file:
                    for line in file:
                        if len(line) > 2 and '=' in line:
                            if 'locale' in line:
                                eri.locale = line.split(
                                    '=')[1].lstrip().rstrip()
                            else:
                                prop = line.split('=')
                                key_val = vim.KeyValue()
                                key_val.key = prop[0].lstrip().rstrip()
                                key_val.value = prop[1].lstrip().rstrip()
                                eri.data.append(key_val)
                eri_list.append(eri)
            return eri_list
        except Exception as e:
            raise ValidationError('vcenter_update.create_event_keyvalue_pairs',
                                  f'Can not read locales : {e}')
Esempio n. 2
0
 def create_event_keyvalue_pairs(self):
     try:
         eri_list = []
         for file in os.listdir(self.resurce_folder_path):
             file = open(self.resurce_folder_path + '/' + file)
             eri = vim.Extension.ResourceInfo()
             eri.module = 'task'
             for line in file:
                 if len(line) > 2 and '=' in line:
                     if 'locale' in line:
                         eri.locale = line.split('=')[1].lstrip().rstrip()
                     else:
                         prop = line.split('=')
                         key_val = vim.KeyValue()
                         key_val.key = prop[0].lstrip().rstrip()
                         key_val.value = prop[1].lstrip().rstrip()
                         eri.data.append(key_val)
             file.close()
             eri_list.append(eri)
         return eri_list
     except Exception as ex:
         return 'can not read locales :' + str(ex)
def main():
    argument_spec = vmware_argument_spec()
    argument_spec.update(
        dict(
            labels=dict(type='dict', default=dict(source='ansible')),
            license=dict(type='str', required=True),
            state=dict(type='str',
                       default='present',
                       choices=['absent', 'present']),
            esxi_hostname=dict(type='str'),
            datacenter=dict(type='str'),
            cluster_name=dict(type='str'),
        ))

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

    license = module.params['license']
    state = module.params['state']

    # FIXME: This does not seem to work on vCenter v6.0
    labels = []
    for k in module.params['labels']:
        kv = vim.KeyValue()
        kv.key = k
        kv.value = module.params['labels'][k]
        labels.append(kv)

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

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

    lm = pyv.content.licenseManager

    result['licenses'] = pyv.list_keys(lm.licenses)
    if module._diff:
        result['diff']['before'] = '\n'.join(result['licenses']) + '\n'

    if state == 'present':
        if license not in result['licenses']:
            result['changed'] = True
            if module.check_mode:
                result['licenses'].append(license)
            else:
                lm.AddLicense(license, labels)

        key = pyv.find_key(lm.licenses, license)
        if key is not None:
            lam = lm.licenseAssignmentManager
            assigned_license = None
            datacenter = module.params['datacenter']
            datacenter_obj = None
            if datacenter:
                datacenter_obj = pyv.find_datacenter_by_name(datacenter)
                if not datacenter_obj:
                    module.fail_json(
                        msg="Unable to find the datacenter %(datacenter)s" %
                        module.params)

            cluster = module.params['cluster_name']
            if cluster:
                cluster_obj = pyv.find_cluster_by_name(
                    cluster_name=cluster, datacenter_name=datacenter_obj)
                if not cluster_obj:
                    msg = "Unable to find the cluster %(cluster_name)s"
                    if datacenter:
                        msg += " in datacenter %(datacenter)s"
                    module.fail_json(msg=msg % module.params)
                entityId = cluster_obj._moId
            # assign to current vCenter, if esxi_hostname is not specified
            elif module.params['esxi_hostname'] is None:
                entityId = pyv.content.about.instanceUuid
                # if key name not contain "VMware vCenter Server"
                if pyv.content.about.name not in key.name:
                    module.warn(
                        'License key "%s" (%s) is not suitable for "%s"' %
                        (license, key.name, pyv.content.about.name))
            # assign to ESXi server
            else:
                esxi_host = find_hostsystem_by_name(
                    pyv.content, module.params['esxi_hostname'])
                if esxi_host is None:
                    module.fail_json(
                        msg='Cannot find the specified ESXi host "%s".' %
                        module.params['esxi_hostname'])
                entityId = esxi_host._moId
                # e.g., key.editionKey is "esx.enterprisePlus.cpuPackage", not sure all keys are in this format
                if 'esx' not in key.editionKey:
                    module.warn(
                        'License key "%s" edition "%s" is not suitable for ESXi server'
                        % (license, key.editionKey))

            try:
                assigned_license = lam.QueryAssignedLicenses(entityId=entityId)
            except Exception as e:
                module.fail_json(
                    msg=
                    'Could not query vCenter "%s" assigned license info due to %s.'
                    % (entityId, to_native(e)))

            if not assigned_license or (
                    len(assigned_license) != 0 and
                    assigned_license[0].assignedLicense.licenseKey != license):
                try:
                    lam.UpdateAssignedLicense(entity=entityId,
                                              licenseKey=license)
                except Exception:
                    module.fail_json(
                        msg='Could not assign "%s" (%s) to vCenter.' %
                        (license, key.name))
                result['changed'] = True
            result['licenses'] = pyv.list_keys(lm.licenses)
        else:
            module.fail_json(
                msg='License "%s" is not existing or can not be added' %
                license)
        if module._diff:
            result['diff']['after'] = '\n'.join(result['licenses']) + '\n'

    elif state == 'absent' and license in result['licenses']:

        # Check if key is in use
        key = pyv.find_key(lm.licenses, license)
        if key.used > 0:
            module.fail_json(
                msg='Cannot remove key "%s", still in use %s time(s).' %
                (license, key.used))

        result['changed'] = True
        if module.check_mode:
            result['licenses'].remove(license)
        else:
            lm.RemoveLicense(license)
            result['licenses'] = pyv.list_keys(lm.licenses)
        if module._diff:
            result['diff']['after'] = '\n'.join(result['licenses']) + '\n'

    module.exit_json(**result)
 def create_option(key, value):
     """Create option"""
     option = vim.KeyValue()
     option.key = key
     option.value = value
     return option
Esempio n. 5
0
def main():
    args = setup_args()
    try:
        si = SmartConnectNoSSL(host=args.host,
                               user=args.user,
                               pwd=args.password,
                               port=args.port)
        atexit.register(Disconnect, si)
    except:
        print("Unable to connect to %s" % args.host)
        return 1

    if args.datacenter:
        dc = get_dc(si, args.datacenter)
    else:
        dc = si.content.rootFolder.childEntity[0]

    if args.datastore:
        ds = get_ds(dc, args.datastore)
    else:
        ds = get_largest_free_ds(dc)

    ovf_handle = OvfHandler(args.ova_path)

    ovfManager = si.content.ovfManager

    propertyMappingDict = {
        'vsm_cli_passwd_0': args.vsm_cli_passwd_0,
        'vsm_cli_en_passwd_0': args.vsm_cli_en_passwd_0,
        'vsm_hostname': args.vsm_hostname,
        'vsm_ip_0': args.vsm_ip_0,
        'vsm_netmask_0': args.vsm_netmask_0,
        'vsm_gateway_0': args.vsm_gateway_0,
        'vsm_ntp_0': args.vsm_ntp_0,
        'vsm_dns1_0': args.vsm_dns1_0
    }

    mapping = []
    for k in propertyMappingDict:
        v = propertyMappingDict[k]
        mapping.append(vim.KeyValue(key=k, value=v))

    network = get_network(si, dc, args.map_eth0_to_network)
    cluster_rp = get_cluster(si, dc, args.cluster)

    network_map = vim.OvfManager.NetworkMapping()
    network_map.name = 'Management Network'
    network_map.network = network
    vmname = 'HCI-NSX-Manager-1'

    cisp = vim.OvfManager.CreateImportSpecParams(propertyMapping=mapping,
                                                 entityName=vmname)
    cisp.networkMapping.append(network_map)

    cisr = ovfManager.CreateImportSpec(ovf_handle.get_descriptor(), cluster_rp,
                                       ds, cisp)

    # These errors might be handleable by supporting the parameters in
    # CreateImportSpecParams
    if len(cisr.error):
        print("The following errors will prevent import of this OVA:")
        for error in cisr.error:
            print("%s" % error)
        return 1

    ovf_handle.set_spec(cisr)

    lease = cluster_rp.ImportVApp(cisr.importSpec, dc.vmFolder)

    while lease.state == vim.HttpNfcLease.State.initializing:
        print("Waiting for lease to be ready...")
        time.sleep(1)

    if lease.state == vim.HttpNfcLease.State.error:
        print("Lease error: %s" % lease.error)
        return 1
    if lease.state == vim.HttpNfcLease.State.done:
        return 0

    print("Starting deploy...")

    ovf_handle.upload_disks(lease, args.host)

    # Wait a little bit then try to power nsx manager on

    time.sleep(60)
    vmnames = vmname
    content = si.content
    objView = content.viewManager.CreateContainerView(content.rootFolder,
                                                      [vim.VirtualMachine],
                                                      True)
    vmList = objView.view
    objView.Destroy()

    tasks = [vm.PowerOn() for vm in vmList if vm.name in vmnames]

    print(
        "NSX Manager appliance is deployed.  Please wait 10-15 minutes before running the configure_nsx_manager.py script as it can take a while for the services to fully start."
    )
Esempio n. 6
0
def main():
    argument_spec = vmware_argument_spec()
    argument_spec.update(
        dict(
            labels=dict(type='dict', default=dict(source='ansible')),
            license=dict(type='str', required=True),
            state=dict(type='str',
                       default='present',
                       choices=['absent', 'present']),
        ))

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

    license = module.params['license']
    state = module.params['state']

    # FIXME: This does not seem to work on vCenter v6.0
    labels = []
    for k in module.params['labels']:
        kv = vim.KeyValue()
        kv.key = k
        kv.value = module.params['labels'][k]
        labels.append(kv)

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

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

    content = connect_to_api(module)
    lm = content.licenseManager

    result['licenses'] = list_keys(lm.licenses)
    if module._diff:
        result['diff']['before'] = '\n'.join(result['licenses']) + '\n'

    if state == 'present' and license not in result['licenses']:

        result['changed'] = True
        if module.check_mode:
            result['licenses'].append(license)
        else:
            lm.AddLicense(license, labels)

            # Automatically assign to current vCenter, if needed
            key = find_key(lm.licenses, license)
            if content.about.name in key.name:
                try:
                    lam = lm.licenseAssignmentManager
                    lam.UpdateAssignedLicense(
                        entity=content.about.instanceUuid, licenseKey=license)
                except:
                    module.warn('Could not assign "%s" (%s) to vCenter.' %
                                (license, key.name))

            result['licenses'] = list_keys(lm.licenses)
        if module._diff:
            result['diff']['after'] = '\n'.join(result['licenses']) + '\n'

    elif state == 'absent' and license in result['licenses']:

        # Check if key is in use
        key = find_key(lm.licenses, license)
        if key.used > 0:
            module.fail_json(
                msg='Cannot remove key "%s", still in use %s time(s).' %
                (license, key.used))

        result['changed'] = True
        if module.check_mode:
            result['licenses'].remove(license)
        else:
            lm.RemoveLicense(license)
            result['licenses'] = list_keys(lm.licenses)
        if module._diff:
            result['diff']['after'] = '\n'.join(result['licenses']) + '\n'

    module.exit_json(**result)
Esempio n. 7
0
def _create_from_ova(si, vm_name, connection_host, data_center, resource_pool,
                     folder, host, datastore, vm_paramaters):
    logging.info('vcenter: creating from OVA("{0}") "{1}"'.format(
        vm_paramaters['ova'], vm_name))
    if hasattr(ssl, '_create_unverified_context'):
        sslContext = ssl._create_unverified_context()
    else:
        sslContext = None

    handler = OVAImportHandler(vm_paramaters['ova'], sslContext)

    ovf_manager = si.content.ovfManager

    network_mapping = []
    for interface in vm_paramaters['interface_list']:
        network_mapping.append(
            vim.OvfManager.NetworkMapping(name=interface['physical_location'],
                                          network=_getNetwork(
                                              host, interface['network'])))

    property_map = []
    try:
        for key, value in vm_paramaters['property_map'].items():
            property_map.append(vim.KeyValue(key=key, value=value))
    except KeyError:
        pass

    cisp = vim.OvfManager.CreateImportSpecParams(
        entityName=vm_name,
        hostSystem=host,
        propertyMapping=property_map,
        networkMapping=network_mapping)

    try:
        cisp.diskProvisioning = vm_paramaters['disk_provisioning']
    except KeyError:
        pass

    try:
        cisp.deploymentOption = vm_paramaters['deployment_option']
    except KeyError:
        pass

    try:
        cisp.ipProtocol = vm_paramaters['ip_protocol']
    except KeyError:
        pass

    logging.debug('vcenter: Import Spec Params: "{0}"'.format(cisp))

    result = ovf_manager.CreateImportSpec(handler.descriptor, resource_pool,
                                          datastore, cisp)

    if result.importSpec is not None and result.importSpec.configSpec.vAppConfig is not None:
        for property in result.importSpec.configSpec.vAppConfig.property:
            info = property.info
            if info.id in vm_paramaters[
                    'property_map'] and not info.userConfigurable:
                logging.warning(
                    'Setting non user configurable "{0}" to configurable'.
                    format(info.id))
                info.userConfigurable = True

    if len(result.warning):
        logging.warning('vcenter: Warning with OVA Import Spec: "{0}"'.format(
            result.warning))

    if len(result.error):
        raise Exception('OVA Import Errors: "{0}"'.format('","'.join(
            [str(i) for i in result.error])))

    uuid = handler.upload(connection_host, resource_pool, result, data_center)

    if si.content.about.productLineId == 'embeddedEsx':
        _inject_ovf_env(si, _getVM(si, uuid), vm_paramaters)

    return uuid
Esempio n. 8
0
 def _new_task_extension_resource_info(self, locale, module, items):
     data = [vim.KeyValue(key=key, value=value) for key, value in items]
     return vim.ExtensionResourceInfo(locale=locale,
                                      module=module,
                                      data=data)
def main():
    args = setup_args()
    try:
        si = SmartConnectNoSSL(host=args.host,
                               user=args.user,
                               pwd=args.password,
                               port=args.port)
        atexit.register(Disconnect, si)
    except Exception as e:
        print("Unable to connect to %s" % args.host)
        return 1

    if args.datacenter:
        dc = get_dc(si, args.datacenter)
    else:
        dc = si.content.rootFolder.childEntity[0]

    if args.resource_pool:
        rp = get_rp(si, dc, args.resource_pool)
    else:
        rp = get_largest_free_rp(si, dc)

    if args.datastore:
        ds = get_ds(dc, args.datastore)
    else:
        ds = get_largest_free_ds(dc)

    ovf_handle = OvfHandler(args.ova_path)

    ovfManager = si.content.ovfManager
    # CreateImportSpecParams can specify many useful things such as
    # diskProvisioning (thin/thick/sparse/etc)
    # networkMapping (to map to networks)
    # propertyMapping (descriptor specific properties)

    propertyMappingDict = get_config(args.service, 'properties',
                                     args.configpath)

    mapping = []
    network_mappings = []
    for k in propertyMappingDict:
        v = propertyMappingDict[k]
        mapping.append(vim.KeyValue(key=k, value=v))

    # datacenter_list = si.content.rootFolder.childEntity
    # resourcepool_obj = get_obj_in_list('network_adapter_1', datacenter_list)
    network = find_network_by_name(si.content, 'VLAN_358')
    network_map = vim.OvfManager.NetworkMapping()
    network_map.name = 'VLAN_358'
    network_map.network = network
    network_mappings.append(network_map)

    cisp = vim.OvfManager.CreateImportSpecParams(
        networkMapping=network_mappings, propertyMapping=mapping,
        entityName=propertyMappingDict['Hostname'], diskProvisioning='thin')
    print(cisp)
    cisr = ovfManager.CreateImportSpec(ovf_handle.get_descriptor(),
                                       rp, ds, cisp)

    # These errors might be handleable by supporting the parameters in
    # CreateImportSpecParams
    if len(cisr.error):
        print("The following errors will prevent import of this OVA:")
        for error in cisr.error:
            print("%s" % error)
        return 1

    ovf_handle.set_spec(cisr)

    lease = rp.ImportVApp(cisr.importSpec, dc.vmFolder)
    while lease.state == vim.HttpNfcLease.State.initializing:
        print("Waiting for lease to be ready...")
        time.sleep(1)

    if lease.state == vim.HttpNfcLease.State.error:
        print("Lease error: %s" % lease.error)
        return 1
    if lease.state == vim.HttpNfcLease.State.done:
        return 0

    print("Starting deploy...")
    return ovf_handle.upload_disks(lease, args.host)
def deploy_svmc(svmc_name, vc_ip, vc_user, vc_password, vc_port,
                datacenter_svmc, datastore_svmc, cluster_svmc,
                svmc_net_details, svmcloc, svmc_root_user, svmc_root_pw):
    ovf_path = extract_ova(svmcloc)
    ovf_file = get_files_from_dir(ovf_path, ".ovf")[0]
    vmdk_path = get_files_from_dir(ovf_path, ".vmdk")
    ovfd = get_ovf_descriptor(ovf_file)
    try:
        si = connect.Connect(vc_ip, vc_port, vc_user, vc_password)
        content = si.RetrieveContent()
    except:
        print "Unable to connect to %s" % vc_ip
        exit(1)
    objs = get_objects(si, datacenter_svmc, datastore_svmc, cluster_svmc)
    propertydict = {
        "eth0_:_ipaddress": svmc_net_details[0][0],
        "eth0_:_subnet_mask": svmc_net_details[0][1],
        "eth0_:_default_gateway": svmc_net_details[0][2],
        "eth0_:_dns_servers": svmc_net_details[0][3][0]
    }
    manager = si.content.ovfManager
    spec_params = vim.OvfManager.CreateImportSpecParams()
    ovfPropertyMappings = []
    for key, value in propertydict.items():
        param = vim.KeyValue()
        param.key = key
        param.value = value
        ovfPropertyMappings.append(param)
    spec_params.propertyMapping = ovfPropertyMappings
    spec_params.ipAllocationPolicy = 'fixedPolicy'
    spec_params.ipProtocol = 'static'
    import_spec = manager.CreateImportSpec(ovfd, objs["resource pool"],
                                           objs["datastore"], spec_params)
    import_spec.importSpec.configSpec.name = svmc_name
    lease = objs["resource pool"].ImportVApp(import_spec.importSpec,
                                             objs["datacenter"].vmFolder)
    while (True):
        if (lease.state == vim.HttpNfcLease.State.ready):
            keepalive_thread = Thread(target=keep_lease_alive, args=(lease, ))
            keepalive_thread.start()
            curl_loc = "C:/curl-7.53.1-win64-mingw/bin/curl.exe"
            i = 0
            for vmdk in vmdk_path:
                url = lease.info.deviceUrl[0].url.replace('*', vc_ip)
                curl_cmd = (
                    curl_loc + " --globoff" +
                    " -Ss -X POST --insecure -T %s -H 'Content-Type:application/x-vnd.vmware-streamVmdk' %s"
                    % (vmdk, url))
                system(curl_cmd)
                i = i + 1
            lease.HttpNfcLeaseComplete()
            keepalive_thread.join()
            vm_obj = get_obj(content, [vim.VirtualMachine], svmc_name)
            tasks = vm_obj.PowerOn()
            time.sleep(300)
            # execute_command_for_svmc(svmc_net_details[0][0], svmc_root_user, svmc_root_pw)
            connect.Disconnect(si)
            return 0
        elif (lease.state == vim.HttpNfcLease.State.error):
            print "Lease error: " + lease.state.error
            exit(1)
    connect.Disconnect(si)
Esempio n. 11
0
    args.datastore_name = datastores[i]
    args.cluster_name = cluster_names[i]

    objs = get_objects(si, args)

    manager = si.content.ovfManager

    spec_params = vim.OvfManager.CreateImportSpecParams()
    spec_params.entityName = args.vmname
    spec_params.networkMapping = [
        vim.OvfManager.NetworkMapping(name='DataNetwork', network=objs["network1"]),
        vim.OvfManager.NetworkMapping(name='SecondaryNetwork', network=objs["network2"])
    ]

    spec_params.propertyMapping = [
        vim.KeyValue(key='dataIp', value=ip),
        vim.KeyValue(key='dataNetmask', value=args.netmask),
        vim.KeyValue(key='dataGateway', value=args.gateway),
        vim.KeyValue(key='DeploymentOption', value='small'),
        vim.KeyValue(key='IpAssignment.IpProtocol', value='IPv4'),
        vim.KeyValue(key='NetworkMapping.DataNetwork', value=args.network1),
        vim.KeyValue(key='NetworkMapping.SecondaryNetwork', value=args.network2)
    ]

    import_spec = manager.CreateImportSpec(ovfd,
                                           objs["resource pool"],
                                           objs["datastore"],
                                           spec_params)

    lease = objs["resource pool"].ImportVApp(import_spec.importSpec,
                                             objs["datacenter"].vmFolder)
Esempio n. 12
0
def create_vim_keyvalue(key, value):
    key_value = vim.KeyValue()
    key_value.key = key
    key_value.value = value
    return key_value