Build lookup table of VM instances known to the cloud provider.

        The returned dictionary links VM id with the actual VM object.
439801
def _build_cached_instances(self):
        
        connection = self._connect()
        reservations = connection.get_all_reservations()
        cached_instances = {}
        for rs in reservations:
            for vm in rs.instances:
                cached_instances[vm.id] = vm
        return cached_instances
9157
def _smartos_computenode_data():
    '''
    
    '''
    # Provides:
    #   vms_total
    #   vms_running
    #   vms_stopped
    #   vms_type
    #   sdc_version
    #   vm_capable
    #   vm_hw_virt

    grains = {}

    # collect vm data
    vms = {}
    for vm in __salt__['cmd.run']('vmadm list -p -o uuid,alias,state,type').split("\n"):
        vm = dict(list(zip(['uuid', 'alias', 'state', 'type'], vm.split(':'))))
        vms[vm['uuid']] = vm
        del vms[vm['uuid']]['uuid']

    # set vm grains
    grains['computenode_vms_total'] = len(vms)
    grains['computenode_vms_running'] = 0
    grains['computenode_vms_stopped'] = 0
    grains['computenode_vms_type'] = {'KVM': 0, 'LX': 0, 'OS': 0}
    for vm in vms:
        if vms[vm]['state'].lower() == 'running':
            grains['computenode_vms_running'] += 1
        elif vms[vm]['state'].lower() == 'stopped':
            grains['computenode_vms_stopped'] += 1

        if vms[vm]['type'] not in grains['computenode_vms_type']:
            # NOTE: be prepared for when bhyve gets its own type
            grains['computenode_vms_type'][vms[vm]['type']] = 0
        grains['computenode_vms_type'][vms[vm]['type']] += 1

    # sysinfo derived grains
    sysinfo = salt.utils.json.loads(__salt__['cmd.run']('sysinfo'))
    grains['computenode_sdc_version'] = sysinfo['SDC Version']
    grains['computenode_vm_capable'] = sysinfo['VM Capable']
    if sysinfo['VM Capable']:
        grains['computenode_vm_hw_virt'] = sysinfo['CPU Virtualization']

    # sysinfo derived smbios grains
    grains['manufacturer'] = sysinfo['Manufacturer']
    grains['productname'] = sysinfo['Product']
    grains['uuid'] = sysinfo['UUID']

    return grains
93603
async def list_vms(self, preset_name):
        '''
        
        '''

        response = await self.nova.servers.list(name=f'^{preset_name}$')
        result = []
        for server in response['servers']:
            result.append(self._map_vm_structure(server))
        return result
37749
def get_size(vm_):
    '''
    
    '''
    sizes = avail_sizes()
    vm_size = six.text_type(config.get_cloud_config_value(
        'size', vm_, __opts__, search_global=False
    ))

    if not vm_size:
        raise SaltCloudNotFound('No size specified for this VM.')

    if vm_size and six.text_type(vm_size) in sizes:
        return sizes[vm_size]['InstanceTypeId']

    raise SaltCloudNotFound(
        'The specified size, \'{0}\', could not be found.'.format(vm_size)
    )
910218
def avail_images(conn=None, call=None):
    '''
    
    '''
    if call == 'action':
        raise SaltCloudSystemExit(
            'The avail_images function must be called with '
            '-f or --function, or with the --list-images option'
        )

    if not conn:
        conn = get_conn()

    ret = {}
    for item in conn.list_os_images():
        ret[item.name] = object_to_dict(item)
    for item in conn.list_vm_images():
        ret[item.name] = object_to_dict(item)
    return ret
1110495
def find_vm_by_name(self, si, path, name):
        
        return self.find_obj_by_path(si, path, name, self.VM)
377634
def __get_metadata(vm_):
    '''
    
    '''
    md = config.get_cloud_config_value(
        'metadata', vm_, __opts__,
        default='{}', search_global=False)
    # Consider warning the user that the metadata in the cloud profile
    # could not be interpreted, bad formatting?
    try:
        metadata = literal_eval(md)
    except Exception:  # pylint: disable=W0703
        metadata = None
    if not metadata or not isinstance(metadata, dict):
        metadata = {'items': [{
            'key': 'salt-cloud-profile',
            'value': vm_['profile']
        }]}
    else:
        metadata['salt-cloud-profile'] = vm_['profile']
        items = []
        for k, v in six.iteritems(metadata):
            items.append({'key': k, 'value': v})
        metadata = {'items': items}
    return metadata
442549
def map_vnics(vm):
        
        return {device.deviceInfo.label: device
                for device in vm.config.hardware.device
                if isinstance(device, vim.vm.device.VirtualEthernetCard)}
694025
def get_image(vm_):
    
    '''
    images = avail_images()
    vm_image = six.text_type(config.get_cloud_config_value(
        'image', vm_, __opts__, search_global=False
    ))
    for image in images:
        if vm_image in (images[image]['name'], images[image]['id']):
            return images[image]['id']
    raise SaltCloudNotFound(
        'The specified image, \'{0}\', could not be found.'.format(vm_image)
    )
1147635
def get_vm_ids_by_ud(access_token, subscription_id, resource_group, vmssname, updatedomain):
    ''''''
    instance_viewlist = azurerm.list_vmss_vm_instance_view(access_token, subscription_id,
                                                           resource_group, vmssname)
    # print(json.dumps(instance_viewlist, sort_keys=False, indent=2, separators=(',', ': ')))

    # loop through the instance view list, and build the vm id list of VMs in
    # the matching UD
    udinstancelist = []
    for instance_view in instance_viewlist['value']:
        vmud = instance_view['properties']['instance_view']['platformUpdateDomain']
        if vmud == updatedomain:
            udinstancelist.append(instance_view['instanceId'])
    udinstancelist.sort()
    return udinstancelist
1112342
def get_size(conn, vm_):
    '''
    
    '''
    sizes = conn.list_sizes()
    vm_size = config.get_cloud_config_value('size', vm_, __opts__)
    if not vm_size:
        return sizes[0]

    for size in sizes:
        if vm_size and six.text_type(vm_size) in (six.text_type(sizes[size]['id']), six.text_type(size)):
            return sizes[size]['id']
    raise SaltCloudNotFound(
        'The specified size, \'{0}\', could not be found.'.format(vm_size)
    )
1343651
def show_instance(name, call=None):
    '''
    
    '''
    if call != 'action':
        raise SaltCloudSystemExit(
            'The show_instance action must be called with '
            '-a or --action.'
        )

    vm_properties = [
        "config.hardware.device",
        "summary.storage.committed",
        "summary.storage.uncommitted",
        "summary.storage.unshared",
        "layoutEx.file",
        "config.guestFullName",
        "config.guestId",
        "guest.net",
        "config.hardware.memoryMB",
        "name",
        "config.hardware.numCPU",
        "config.files.vmPathName",
        "summary.runtime.powerState",
        "guest.toolsStatus"
    ]

    vm_list = salt.utils.vmware.get_mors_with_properties(_get_si(), vim.VirtualMachine, vm_properties)

    for vm in vm_list:
        if vm['name'] == name:
            return _format_instance_info(vm)

    return {}
363507
def get_vmconfig(vmid, node=None, node_type='openvz'):
    '''
    
    '''
    if node is None:
        # We need to figure out which node this VM is on.
        for host_name, host_details in six.iteritems(avail_locations()):
            for item in query('get', 'nodes/{0}/{1}'.format(host_name, node_type)):
                if item['vmid'] == vmid:
                    node = host_name

    # If we reached this point, we have all the information we need
    data = query('get', 'nodes/{0}/{1}/{2}/config'.format(node, node_type, vmid))

    return data
1338961
def avail_images(call=None):
    '''
    
    '''
    if call == 'action':
        raise SaltCloudSystemExit(
            'The avail_images function must be called with '
            '-f or --function, or with the --list-images option.'
        )

    templates = {}
    vm_properties = [
        "name",
        "config.template",
        "config.guestFullName",
        "config.hardware.numCPU",
        "config.hardware.memoryMB"
    ]

    vm_list = salt.utils.vmware.get_mors_with_properties(_get_si(), vim.VirtualMachine, vm_properties)

    for vm in vm_list:
        if "config.template" in vm and vm["config.template"]:
            templates[vm["name"]] = {
                'name': vm["name"],
                'guest_fullname': vm["config.guestFullName"] if "config.guestFullName" in vm else "N/A",
                'cpus': vm["config.hardware.numCPU"] if "config.hardware.numCPU" in vm else "N/A",
                'ram': vm["config.hardware.memoryMB"] if "config.hardware.memoryMB" in vm else "N/A"
            }

    return templates
1107219
def get_vm(self, resource_group_name, vm_name):
        '''
        
        '''
        return self.client.virtual_machines.get(
            resource_group_name, vm_name, expand='instanceView')
447856
def _get_vm_by_name(name, allDetails=False):
    '''
    
    '''
    vms = get_resources_vms(includeConfig=allDetails)
    if name in vms:
        return vms[name]

    log.info('VM with name "%s" could not be found.', name)
    return False
33563
def _get_vms_from_inventory(self, inventory_path):
        

        vm_entries = {}
        vmware_vms = []
        log.info('Searching for VMware VMs in inventory file "{}"'.format(inventory_path))
        try:
            pairs = self.parse_vmware_file(inventory_path)
            for key, value in pairs.items():
                if key.startswith("vmlist"):
                    try:
                        vm_entry, variable_name = key.split('.', 1)
                    except ValueError:
                        continue
                    if vm_entry not in vm_entries:
                        vm_entries[vm_entry] = {}
                    vm_entries[vm_entry][variable_name.strip()] = value
        except OSError as e:
            log.warning("Could not read VMware inventory file {}: {}".format(inventory_path, e))

        for vm_settings in vm_entries.values():
            if "displayname" in vm_settings and "config" in vm_settings:
                if os.path.exists(vm_settings["config"]):
                    log.debug('Found VM named "{}" with VMX file "{}"'.format(vm_settings["displayname"], vm_settings["config"]))
                    vmware_vms.append({"vmname": vm_settings["displayname"], "vmx_path": vm_settings["config"]})
        return vmware_vms