Print out the list of stacks deployed at AWS cloud.

    :param awsclient:
    :return:
764003
def list_stacks(awsclient):
    
    client_cf = awsclient.get_client('cloudformation')
    response = client_cf.list_stacks(
        StackStatusFilter=[
            'CREATE_IN_PROGRESS', 'CREATE_COMPLETE', 'ROLLBACK_IN_PROGRESS',
            'ROLLBACK_COMPLETE', 'DELETE_IN_PROGRESS', 'DELETE_FAILED',
            'UPDATE_IN_PROGRESS', 'UPDATE_COMPLETE_CLEANUP_IN_PROGRESS',
            'UPDATE_COMPLETE', 'UPDATE_ROLLBACK_IN_PROGRESS',
            'UPDATE_ROLLBACK_FAILED',
            'UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS',
            'UPDATE_ROLLBACK_COMPLETE',
        ]
    )
    result = {}
    stack_sum = 0
    for summary in response['StackSummaries']:
        result['StackName'] = summary["StackName"]
        result['CreationTime'] = summary['CreationTime']
        result['StackStatus'] = summary['StackStatus']
        print(json2table(result))
        stack_sum += 1
    print('listed %s stacks' % str(stack_sum))
767571
def deployments_list(resource_group, **kwargs):
    '''
    

    '''
    result = {}
    resconn = __utils__['azurearm.get_client']('resource', **kwargs)
    try:
        deployments = __utils__['azurearm.paged_object_to_list'](
            resconn.deployments.list_by_resource_group(
                resource_group_name=resource_group
            )
        )

        for deploy in deployments:
            result[deploy['name']] = deploy
    except CloudError as exc:
        __utils__['azurearm.log_cloud_error']('resource', str(exc), **kwargs)
        result = {'error': str(exc)}

    return result
441235
def get_s3_buckets(api_client, s3_info, s3_params):
    
    manage_dictionary(s3_info, 'buckets', {})
    buckets = api_client[get_s3_list_region(s3_params['selected_regions'])].list_buckets()['Buckets']
    targets = []
    for b in buckets:
        # Abort if bucket is not of interest
        if (b['Name'] in s3_params['skipped_buckets']) or (len(s3_params['checked_buckets']) and b['Name'] not in s3_params['checked_buckets']):
            continue
        targets.append(b)
    s3_info['buckets_count'] = len(targets)
    s3_params['api_clients'] = api_client
    s3_params['s3_info'] = s3_info
    thread_work(targets, get_s3_bucket, params = s3_params, num_threads = 30)
    show_status(s3_info)
    s3_info['buckets_count'] = len(s3_info['buckets'])
    return s3_info
116496
def fetch_current_cloudformation_template(service_name, environment, cf_client):
    
    stack_name = get_stack_name(environment, service_name)
    logger.debug('Fetching template for `%s`', stack_name)
    result = cf_client.get_template(StackName=stack_name)
    return jsonify(result['TemplateBody'])
586937
def delete_stack(awsclient, conf, feedback=True):
    
    client_cf = awsclient.get_client('cloudformation')
    stack_name = _get_stack_name(conf)
    last_event = _get_stack_events_last_timestamp(awsclient, stack_name)

    request = {}
    dict_selective_merge(request, conf['stack'], ['StackName', 'RoleARN'])

    response = client_cf.delete_stack(**request)

    if feedback:
        return _poll_stack_events(awsclient, stack_name, last_event)
225038
def output_deployment_diagnostics(awsclient, deployment_id, log_group, start_time=None):
    
    headline = False
    for instance_id in _list_deployment_instances(awsclient, deployment_id):
        diagnostics = _get_deployment_instance_diagnostics(
            awsclient, deployment_id, instance_id)
        #if error_code != 'Success':
        if diagnostics is not None:
            error_code, script_name, message, log_tail = diagnostics
            # header
            if not headline:
                headline = True
                log.info('\ndeployment diagnostics:')
            # event logs
            log.info('Instance ID: %s', Fore.MAGENTA + instance_id + Fore.RESET)
            log.info('Error Code:  %s', error_code)
            log.info('Script Name: %s', script_name)
            log.info('Message:     %s', message)
            log.info('Log Tail:    %s', log_tail)
            # cloudwatch logs
            if check_log_stream_exists(awsclient, log_group, instance_id):
                logentries = get_log_events(
                    awsclient, log_group, instance_id,
                    datetime_to_timestamp(start_time))
                if logentries:
                    log.info('instance %s logentries', instance_id)
                    for e in logentries:
                        log.info(e['message'].strip())
1290378
def list_loadbalancers(call=None):
    '''
    
    '''
    if call == 'action':
        raise SaltCloudSystemExit(
            'The avail_images function must be called with '
            '-f or --function, or with the --list-loadbalancers option'
        )

    ret = {}
    conn = get_conn()
    datacenter = get_datacenter(conn)

    for item in conn.list_loadbalancers(datacenter['id'])['items']:
        lb = {'id': item['id']}
        lb.update(item['properties'])
        ret[lb['name']] = lb

    return ret
162301
def printStack(self,wrappedStack,include=None,filters=["*"]):
        """"""
        rawStack = wrappedStack['rawStack']
        print "==== Stack {} ====".format(rawStack.name)
        print "Status: {} {}".format(rawStack.stack_status,defaultify(rawStack.stack_status_reason,''))

        for resourceType, resources in wrappedStack['resourcesByTypeIndex'].items():
            if resourceType in AwsProcessor.resourceTypeAliases:
                resourceType = AwsProcessor.resourceTypeAliases[resourceType];
            if (None == include or resourceType in include) and len(resources):
                print "== {}:".format(resourceType)
                logicalIdWidth = 1
                resourceStatusWidth = 1
                resourceStatusReasonWidth = 1
                for index, resource in resources.items():
                    logicalIdWidth = max(logicalIdWidth,len(resource.logical_id))
                    resourceStatusWidth = min(50,max(resourceStatusWidth,len(resource.resource_status)))
                    resourceStatusReasonWidth = min(50,max(resourceStatusReasonWidth,len(defaultify(resource.resource_status_reason,''))))
                frm = "    {{0:3d}}: {{1:{0}}} {{2:{1}}} {{3}}".format(logicalIdWidth,resourceStatusWidth)
                for index, resource in resources.items():
                    if fnmatches(resource.logical_id.lower(),filters):
                        print frm.format(index,resource.logical_id,
                                         elipsifyMiddle(repr(resource.resource_status),50),
                                         elipsifyMiddle(repr(defaultify(resource.resource_status_reason,'')),150))
1103787
def generate_listall_output(lines, resources, aws_config, template, arguments, nodup = False):
    
    for line in lines:
        output = []
        for resource in resources:
            current_path = resource.split('.')
            outline = line[1]
            for key in line[2]:
                outline = outline.replace('_KEY_('+key+')', get_value_at(aws_config['services'], current_path, key, True))
            output.append(outline)
        output = '\n'.join(line for line in sorted(set(output)))
        template = template.replace(line[0], output)
    for (i, argument) in enumerate(arguments):
        template = template.replace('_ARG_%d_' % i, argument)
    return template
992093
def list_regions(service):
    
    for region in service.regions():
        print '%(name)s: %(endpoint)s' % {
            'name': region.name,
            'endpoint': region.endpoint,
        }
158752
def list_tasks(collector):
    """"""
    print("Usage: aws_syncr <environment> <task>")
    print("")
    print("Available environments to choose from are")
    print("-----------------------------------------")
    print("")
    for environment in os.listdir(collector.configuration_folder):
        location = os.path.join(collector.configuration_folder, environment)
        if os.path.isdir(location) and not environment.startswith("."):
            print("\t{0}".format(environment))

    print("")
    print("Available tasks to choose from are:")
    print("-----------------------------------")
    print("")
    keygetter = lambda item: item[1].label
    tasks = sorted(available_actions.items(), key=keygetter)
    sorted_tasks = sorted(list(tasks), key=lambda item: len(item[0]))
    max_length = max(len(name) for name, _ in sorted_tasks)
    for key, task in sorted_tasks:
        desc = dedent(task.__doc__ or "").strip().split('\n')[0]
        print("\t{0}{1} :-: {2}".format(" " * (max_length-len(key)), key, desc))
    print("")
708812
def avail_locations(call=None):
    '''
    
    '''
    if call == 'action':
        raise SaltCloudSystemExit(
            'The avail_locations function must be called with '
            '-f or --function, or with the --list-locations option'
        )

    ret = {}

    params = {'Action': 'DescribeRegions'}
    result = aws.query(params,
                       location=get_location(),
                       provider=get_provider(),
                       opts=__opts__,
                       sigver='4')

    for region in result:
        ret[region['regionName']] = {
            'name': region['regionName'],
            'endpoint': region['regionEndpoint'],
        }

    return ret
1307782
def list_buckets(self):

        '''
            
        '''

        title = '%s.list_buckets' % self.__class__.__name__
        
        bucket_list = []
        
    # send request to s3
        try:
            response = self.connection.list_buckets()
        except:
            raise AWSConnectionError(title)

    # create list from response
        for bucket in response['Buckets']:
            bucket_list.append(bucket['Name'])

        self.bucket_list = bucket_list
        
        return self.bucket_list
1036470
def list(self):
        
        self._initialize_list()
        interested = True

        response = self._cloudFormation.list_stacks()
        print('Stack(s):')
        while interested:
            if 'StackSummaries' in response:
                for stack in response['StackSummaries']:
                    stack_status = stack['StackStatus']
                    if stack_status != 'DELETE_COMPLETE':
                        print('    [{}] - {}'.format(stack['StackStatus'], stack['StackName']))

            next_token = response.get('NextToken', None)
            if next_token:
                response = self._cloudFormation.list_stacks(NextToken=next_token)
            else:
                interested = False

        return True
1090915
def get_log_events(awsclient, log_group_name, log_stream_name, start_ts=None):
    
    client_logs = awsclient.get_client('logs')

    request = {
        'logGroupName': log_group_name,
        'logStreamName': log_stream_name
    }
    if start_ts:
        request['startTime'] = start_ts

    # TODO exhaust the events!
    # TODO use all_pages !
    response = client_logs.get_log_events(**request)

    if 'events' in response and response['events']:
        return [{'timestamp': e['timestamp'], 'message': e['message']}
                for e in response['events']]
1157868
def ls(ctx, name, list_instances):
    """"""
    session = create_session(ctx.obj['AWS_PROFILE_NAME'])

    client = session.client('elb')
    inst = {'LoadBalancerDescriptions': []}
    if name == '*':
        inst = client.describe_load_balancers()
    else:
        try:
            inst = client.describe_load_balancers(LoadBalancerNames=[name])
        except ClientError as e:
            click.echo(e, err=True)

    for i in inst['LoadBalancerDescriptions']:
        click.echo(i['LoadBalancerName'])
        if list_instances:
            for ec2 in i['Instances']:
                health = client.describe_instance_health(
                    LoadBalancerName=name,
                    Instances=[ec2]
                )
                click.echo('{0}\t{1}'.format(ec2['InstanceId'], health['InstanceStates'][0]['State']))
535267
def service_list():
    '''
    
    '''
    r = salt.utils.http.query(DETAILS['url']+'service/list', decode_type='json', decode=True)
    return r['dict']