List available images for OpenStack

    CLI Example

    .. code-block:: bash

        salt-cloud -f avail_images myopenstack
        salt-cloud --list-images myopenstack
767671
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 conn is None:
        conn = get_conn()
    return conn.list_images()
166859
def avail_images(call=None, location='local'):
    '''
    
    '''
    if call == 'action':
        raise SaltCloudSystemExit(
            'The avail_images function must be called with '
            '-f or --function, or with the --list-images option'
        )

    ret = {}
    for host_name, host_details in six.iteritems(avail_locations()):
        for item in query('get', 'nodes/{0}/storage/{1}/content'.format(host_name, location)):
            ret[item['volid']] = item
    return ret
146330
def list_resourcepools(kwargs=None, call=None):
    '''
    
    '''
    if call != 'function':
        raise SaltCloudSystemExit(
            'The list_resourcepools function must be called with '
            '-f or --function.'
        )

    return {'Resource Pools': salt.utils.vmware.list_resourcepools(_get_si())}
559259
def __gather_avail(self):
        '''
        
        '''
        avail = {}
        for saltenv in self._get_envs():
            avail[saltenv] = self.client.list_states(saltenv)
        return avail
17456
def list_subnets(call=None, kwargs=None):
    '''
    
    '''
    if kwargs is None:
        kwargs = {}

    if call == 'action':
        raise SaltCloudSystemExit(
            'The avail_sizes function must be called with '
            '-f or --function'
        )

    netconn = get_conn(client_type='network')

    resource_group = kwargs.get('resource_group') or config.get_cloud_config_value(
                         'resource_group',
                         get_configured_provider(), __opts__, search_global=False
                     )

    if not resource_group and 'group' in kwargs and 'resource_group' not in kwargs:
        resource_group = kwargs['group']

    if not resource_group:
        raise SaltCloudSystemExit(
            'A resource group must be specified'
        )

    if kwargs.get('network') is None:
        kwargs['network'] = config.get_cloud_config_value(
            'network', get_configured_provider(), __opts__, search_global=False
        )

    if 'network' not in kwargs or kwargs['network'] is None:
        raise SaltCloudSystemExit(
            'A "network" must be specified'
        )

    ret = {}
    subnets = netconn.subnets.list(resource_group, kwargs['network'])
    for subnet in subnets:
        ret[subnet.name] = subnet.as_dict()
        ret[subnet.name]['ip_configurations'] = {}
        for ip_ in subnet.ip_configurations:
            comps = ip_.id.split('/')
            name = comps[-1]
            ret[subnet.name]['ip_configurations'][name] = ip_.as_dict()
            ret[subnet.name]['ip_configurations'][name]['subnet'] = subnet.name
        ret[subnet.name]['resource_group'] = resource_group
    return ret
793216
def avail_sizes(call=None):
    '''
    
    '''
    if call == 'action':
        raise SaltCloudSystemExit(
            'The avail_sizes function must be called with '
            '-f or --function, or with the --list-sizes option'
        )

    rcode, items = query(command='my/packages')
    if rcode not in VALID_RESPONSE_CODES:
        return {}
    return key_list(items=items)
1261027
def get_image(conn, vm_):
    '''
    
    '''
    images = conn.list_images()
    vm_image = config.get_cloud_config_value('image', vm_, __opts__)

    if not six.PY3:
        vm_image = vm_image.encode('ascii', 'salt-cloud-force-ascii')

    for img in images:
        if isinstance(img.id, six.string_types) and not six.PY3:
            img_id = img.id.encode('ascii', 'salt-cloud-force-ascii')
        else:
            img_id = str(img.id)  # future lint: disable=blacklisted-function

        if isinstance(img.name, six.string_types) and not six.PY3:
            img_name = img.name.encode('ascii', 'salt-cloud-force-ascii')
        else:
            img_name = str(img.name)  # future lint: disable=blacklisted-function

        if vm_image and vm_image in (img_id, img_name):
            return img

    raise SaltCloudNotFound(
        'The specified image, \'{0}\', could not be found.'.format(vm_image)
    )
1176695
def list_virtual_networks(call=None, kwargs=None):
    '''
    
    '''
    if kwargs is None:
        kwargs = {}

    if call == 'action':
        raise SaltCloudSystemExit(
            'The avail_sizes function must be called with '
            '-f or --function'
        )

    netconn = get_conn(client_type='network')
    resource_groups = list_resource_groups()

    ret = {}
    for group in resource_groups:
        try:
            networks = netconn.virtual_networks.list(
                resource_group_name=group
            )
        except CloudError:
            networks = {}
        for network_obj in networks:
            network = network_obj.as_dict()
            ret[network['name']] = network
            ret[network['name']]['subnets'] = list_subnets(
                kwargs={'resource_group': group, 'network': network['name']}
            )

    return ret
661958
def list_storage_containers(kwargs=None, storage_conn=None, call=None):
    '''
    
    '''
    if call != 'function':
        raise SaltCloudSystemExit(
            'The list_storage_containers function must be called with -f or --function.'
        )

    if not storage_conn:
        storage_conn = get_storage_conn(conn_kwargs=kwargs)

    data = storage_conn.list_containers()
    ret = {}
    for item in data.containers:
        ret[item.name] = object_to_dict(item)
    return ret
1215193
def build_image_list(config, image, imagefile, all_local, include_allanchore, dockerfile=None, exclude_file=None):
    """"""

    if not image and not (imagefile or all_local):
        raise click.BadOptionUsage('No input found for image source. One of <image>, <imagefile>, or <all> must be specified')

    if image and imagefile:
        raise click.BadOptionUsage('Only one of <image> and <imagefile> can be specified')

    filter_images = []
    if exclude_file:
        with open(exclude_file) as f:
            for line in f.readlines():
                filter_images.append(line.strip())

    imagelist = {}
    if image:
        imagelist[image] = {'dockerfile':dockerfile}

    if imagefile:
        filelist = anchore_utils.read_kvfile_tolist(imagefile)
        for i in range(len(filelist)):
            l = filelist[i]
            imageId = l[0]
            try:
                dfile = l[1]
            except:
                dfile = None
            imagelist[imageId] = {'dockerfile':dfile}

    if all_local:
        docker_cli = contexts['docker_cli']
        if docker_cli:
            for f in docker_cli.images(all=True, quiet=True, filters={'dangling': False}):
                if f not in imagelist and f not in filter_images:
                    imagelist[f] = {'dockerfile':None}
        else:
            raise Exception("Could not load any images from local docker host - is docker running?")

    if include_allanchore:
        ret = contexts['anchore_db'].load_all_images().keys()
        if ret and len(ret) > 0:
            for l in list(set(imagelist.keys()) | set(ret)):
                imagelist[l] = {'dockerfile':None}

    # Remove excluded items
    for excluded in filter_images:
        docker_cli = contexts['docker_cli']
        if not docker_cli:
            raise Exception("Could not query docker - is docker running?")
        for img in docker_cli.images(name=excluded, quiet=True):
            imagelist.pop(img, None)

    return imagelist
1024817
def show_instance(name, conn=None, call=None):
    '''
    

    '''
    if call != 'action':
        raise SaltCloudSystemExit(
            'The show_instance action must be called with -a or --action.'
        )
    if conn is None:
        conn = get_conn()

    node = conn.get_server(name, bare=True)
    ret = dict(node)
    ret['id'] = node.id
    ret['name'] = node.name
    ret['size'] = conn.get_flavor(node.flavor.id).name
    ret['state'] = node.status
    ret['private_ips'] = _get_ips(node, 'private')
    ret['public_ips'] = _get_ips(node, 'public')
    ret['floating_ips'] = _get_ips(node, 'floating')
    ret['fixed_ips'] = _get_ips(node, 'fixed')
    if isinstance(node.image, six.string_types):
        ret['image'] = node.image
    else:
        ret['image'] = conn.get_image(node.image.id).name
    return ret
794195
def avail_sizes(call=None):
    '''
    
    '''
    if call == 'action':
        raise SaltCloudSystemExit(
            'The avail_sizes function must be called with '
            '-f or --function, or with the --list-sizes option'
        )

    ret = {
        'block devices': {},
        'memory': {},
        'processors': {},
    }
    conn = get_conn()
    response = conn.getCreateObjectOptions()
    for device in response['blockDevices']:
        #return device['template']['blockDevices']
        ret['block devices'][device['itemPrice']['item']['description']] = {
            'name': device['itemPrice']['item']['description'],
            'capacity':
                device['template']['blockDevices'][0]['diskImage']['capacity'],
        }
    for memory in response['memory']:
        ret['memory'][memory['itemPrice']['item']['description']] = {
            'name': memory['itemPrice']['item']['description'],
            'maxMemory': memory['template']['maxMemory'],
        }
    for processors in response['processors']:
        ret['processors'][processors['itemPrice']['item']['description']] = {
            'name': processors['itemPrice']['item']['description'],
            'start cpus': processors['template']['startCpus'],
        }
    return ret
1125265
def list(host=None, quiet=False, hyper=None):  # pylint: disable=redefined-builtin
    '''
    
    '''
    if quiet:
        log.warning("'quiet' is deprecated. Please migrate to --quiet")
    ret = {}
    client = salt.client.get_local_client(__opts__['conf_file'])
    for info in client.cmd_iter('virtual:physical',
                                'virt.vm_info', tgt_type='grain'):
        if not info:
            continue
        if not isinstance(info, dict):
            continue
        chunk = {}
        id_ = next(six.iterkeys(info))
        if host:
            if host != id_:
                continue
        if not isinstance(info[id_], dict):
            continue
        if 'ret' not in info[id_]:
            continue
        if not isinstance(info[id_]['ret'], dict):
            continue
        data = {}
        for key, val in six.iteritems(info[id_]['ret']):
            if val['state'] in data:
                data[val['state']].append(key)
            else:
                data[val['state']] = [key]
        chunk[id_] = data
        ret.update(chunk)
        if not quiet:
            __jid_event__.fire_event({'data': chunk, 'outputter': 'nested'}, 'progress')

    return ret
6935
def image_list(self, name=None):
        '''
        
        '''
        nt_ks = self.compute_conn
        ret = {}
        for image in nt_ks.images.list():
            links = {}
            for link in image.links:
                links[link['rel']] = link['href']
            ret[image.name] = {
                'name': image.name,
                'id': image.id,
                'status': image.status,
                'progress': image.progress,
                'created': image.created,
                'updated': image.updated,
                'metadata': image.metadata,
                'links': links,
            }
            if hasattr(image, 'minDisk'):
                ret[image.name]['minDisk'] = image.minDisk
            if hasattr(image, 'minRam'):
                ret[image.name]['minRam'] = image.minRam
        if name:
            return {name: ret[name]}
        return ret
317321
def list_folders(kwargs=None, call=None):
    '''
    
    '''
    if call != 'function':
        raise SaltCloudSystemExit(
            'The list_folders function must be called with '
            '-f or --function.'
        )

    return {'Folders': salt.utils.vmware.list_folders(_get_si())}
598977
def available():
    '''
    
    '''
    ret = []

    mod_dir = os.path.join('/lib/modules/', os.uname()[2])

    built_in_file = os.path.join(mod_dir, 'modules.builtin')
    if os.path.exists(built_in_file):
        with salt.utils.files.fopen(built_in_file, 'r') as f:
            for line in f:
                # Strip .ko from the basename
                ret.append(os.path.basename(line)[:-4])

    for root, dirs, files in salt.utils.path.os_walk(mod_dir):
        for fn_ in files:
            if '.ko' in fn_:
                ret.append(fn_[:fn_.index('.ko')].replace('-', '_'))

    if 'Arch' in __grains__['os_family']:
        # Sadly this path is relative to kernel major version but ignores minor version
        mod_dir_arch = '/lib/modules/extramodules-' + os.uname()[2][0:3] + '-ARCH'
        for root, dirs, files in salt.utils.path.os_walk(mod_dir_arch):
            for fn_ in files:
                if '.ko' in fn_:
                    ret.append(fn_[:fn_.index('.ko')].replace('-', '_'))

    return sorted(list(ret))
241414
def show_image(kwargs, call=None):
    '''
    
    '''
    if call != 'function':
        raise SaltCloudSystemExit(
            'The show_image action must be called with -f or --function.'
        )

    params = {'ImageId.1': kwargs['image'],
              'Action': 'DescribeImages'}
    result = aws.query(params,
                       setname='tagSet',
                       location=get_location(),
                       provider=get_provider(),
                       opts=__opts__,
                       sigver='4')
    log.info(result)

    return result