List running ec2 instances.
344627
def list_cloudfront(region, filter_by_kwargs):
    """"""
    conn = boto.connect_cloudfront()
    instances = conn.get_all_distributions()
    return lookup(instances, filter_by=filter_by_kwargs)
1241457
def get_ec2_info(instance_id,
                 region,
                 access_key_id,
                 secret_access_key,
                 username):
    
    conn = connect_to_ec2(region, access_key_id, secret_access_key)
    instance = conn.get_only_instances(
        filters={'instance_id': instance_id}
        )[0]

    data = {}
    data['public_dns_name'] = instance.public_dns_name
    data['id'] = instance.id
    data['instance_type'] = instance.instance_type
    data['ip_address'] = instance.ip_address
    data['architecture'] = instance.architecture
    data['state'] = instance.state
    data['region'] = region
    data['cloud_type'] = 'ec2'
    data['username'] = username

    # find out the distribution running on the instance
    if username is not None:
        wait_for_ssh(data['ip_address'])
        with settings(host_string=username + '@' + data['ip_address']):
            data['distribution'] = linux_distribution(username,
                                                      data['ip_address'])
            data['os_release'] = os_release(username,
                                            data['ip_address'])

    try:
        volume = conn.get_all_volumes(
            filters={'attachment.instance-id': instance.id})[0].id
        data['volume'] = volume
    except:
        data['volume'] = ''
    return data
550115
def list_nodes_full(call=None):
    '''
    
    '''
    if call == 'action':
        raise SaltCloudSystemExit(
            'The list_nodes_full function must be called with -f or --function.'
        )

    zone = _get_specified_zone()

    params = {
        'action': 'DescribeInstances',
        'zone': zone,
        'status': ['pending', 'running', 'stopped', 'suspended'],
    }
    items = query(params=params)

    log.debug('Total %s instances found in zone %s', items['total_count'], zone)

    result = {}

    if items['total_count'] == 0:
        return result

    for node in items['instance_set']:
        normalized_node = _show_normalized_node(node)
        node.update(normalized_node)

        result[node['instance_id']] = node

    provider = __active_provider_name__ or 'qingcloud'
    if ':' in provider:
        comps = provider.split(':')
        provider = comps[0]

    __opts__['update_cachedir'] = True
    __utils__['cloud.cache_node_list'](result, provider, __opts__)

    return result
100881
def get_instances(name, lifecycle_state="InService", health_status="Healthy",
                  attribute="private_ip_address", attributes=None, region=None,
                  key=None, keyid=None, profile=None):
    '''
    

    '''
    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
    ec2_conn = _get_ec2_conn(region=region, key=key, keyid=keyid, profile=profile)
    retries = 30
    while True:
        try:
            asgs = conn.get_all_groups(names=[name])
            break
        except boto.exception.BotoServerError as e:
            if retries and e.code == 'Throttling':
                log.debug('Throttled by AWS API, retrying in 5 seconds...')
                time.sleep(5)
                retries -= 1
                continue
            log.error(e)
            return False
    if len(asgs) != 1:
        log.debug("name '%s' returns multiple ASGs: %s", name, [asg.name for asg in asgs])
        return False
    asg = asgs[0]
    instance_ids = []
    # match lifecycle_state and health_status
    for i in asg.instances:
        if lifecycle_state is not None and i.lifecycle_state != lifecycle_state:
            continue
        if health_status is not None and i.health_status != health_status:
            continue
        instance_ids.append(i.instance_id)
    # get full instance info, so that we can return the attribute
    instances = ec2_conn.get_only_instances(instance_ids=instance_ids)
    if attributes:
        return [[_convert_attribute(instance, attr) for attr in attributes] for instance in instances]
    else:
        # properly handle case when not all instances have the requested attribute
        return [_convert_attribute(instance, attribute) for instance in instances if getattr(instance, attribute)]
140044
def _stop_ec2_instances(awsclient, ec2_instances, wait=True):
    
    if len(ec2_instances) == 0:
        return
    client_ec2 = awsclient.get_client('ec2')

    # get running instances
    running_instances = all_pages(
        client_ec2.describe_instance_status,
        {
            'InstanceIds': ec2_instances,
            'Filters': [{
                'Name': 'instance-state-name',
                'Values': ['pending', 'running']
            }]
        },
        lambda r: [i['InstanceId'] for i in r.get('InstanceStatuses', [])],
    )

    if running_instances:
        log.info('Stopping EC2 instances: %s', running_instances)
        client_ec2.stop_instances(InstanceIds=running_instances)

        if wait:
            # wait for instances to stop
            waiter_inst_stopped = client_ec2.get_waiter('instance_stopped')
            waiter_inst_stopped.wait(InstanceIds=running_instances)
856241
def list_instances(self, machine_state):
        
        if not isinstance(machine_state, CloudMachineState):
            raise TypeError("machine_state can only be an instance of type CloudMachineState")
        (return_ids, return_names) = self._call("listInstances",
                     in_p=[machine_state])
        return (return_ids, return_names)
1015002
def is_instance_running(self, instance_id):
        
        self._restore_from_storage(instance_id)
        if self._start_failed:
            raise Exception('is_instance_running for node %s: failing due to'
                            ' previous errors.' % instance_id)
        try:
            v_m = self._qualified_name_to_vm(instance_id)
            if not v_m:
                raise Exception("Can't find instance_id %s" % instance_id)
        except Exception:
            log.error(traceback.format_exc())
            raise
        return v_m._power_state == 'Started'
795360
def _list_machines(self):
        
        try:
            req = self.request(self.mist_client.uri+'/clouds/'+self.id+'/machines')
            machines = req.get().json()
        except:
            # Eg invalid cloud credentials
            machines = {}

        if machines:
            for machine in machines:
                self._machines[machine['machine_id']] = Machine(machine, self)
        else:
            self._machines = {}
1169224
def _find_usage_instances(self):
        """"""
        paginator = self.conn.get_paginator('describe_db_instances')
        for page in paginator.paginate():
            for instance in page['DBInstances']:
                self.limits['Read replicas per master']._add_current_usage(
                    len(instance['ReadReplicaDBInstanceIdentifiers']),
                    aws_type='AWS::RDS::DBInstance',
                    resource_id=instance['DBInstanceIdentifier']
                )
217526
def _start_ec2_instances(awsclient, ec2_instances, wait=True):
    
    if len(ec2_instances) == 0:
        return
    client_ec2 = awsclient.get_client('ec2')

    # get stopped instances
    stopped_instances = all_pages(
        client_ec2.describe_instance_status,
        {
            'InstanceIds': ec2_instances,
            'Filters': [{
                'Name': 'instance-state-name',
                'Values': ['stopping', 'stopped']
            }],
            'IncludeAllInstances': True
        },
        lambda r: [i['InstanceId'] for i in r.get('InstanceStatuses', [])],
    )

    if stopped_instances:
        # start all stopped instances
        log.info('Starting EC2 instances: %s', stopped_instances)
        client_ec2.start_instances(InstanceIds=stopped_instances)

        if wait:
            # wait for instances to come up
            waiter_inst_running = client_ec2.get_waiter('instance_running')
            waiter_inst_running.wait(InstanceIds=stopped_instances)

            # wait for status checks
            waiter_status_ok = client_ec2.get_waiter('instance_status_ok')
            waiter_status_ok.wait(InstanceIds=stopped_instances)
182362
def _instance_usage(self):
        
        # On-Demand instances by type
        ondemand = {}
        for t in self._instance_types():
            ondemand[t] = 0
        az_to_inst = {}
        logger.debug("Getting usage for on-demand instances")
        for inst in self.resource_conn.instances.all():
            if inst.spot_instance_request_id:
                logger.info("Spot instance found (%s); skipping from "
                            "Running On-Demand Instances count", inst.id)
                continue
            if inst.state['Name'] in ['stopped', 'terminated']:
                logger.debug("Ignoring instance %s in state %s", inst.id,
                             inst.state['Name'])
                continue
            if inst.placement['AvailabilityZone'] not in az_to_inst:
                az_to_inst[
                    inst.placement['AvailabilityZone']] = deepcopy(ondemand)
            try:
                az_to_inst[
                    inst.placement['AvailabilityZone']][inst.instance_type] += 1
            except KeyError:
                logger.error("ERROR - unknown instance type '%s'; not "
                             "counting", inst.instance_type)
        return az_to_inst
624517
def run_instances(self, image_id, min_count, max_count,
        security_groups=None, key_name=None, instance_type=None,
        user_data=None, availability_zone=None, kernel_id=None,
        ramdisk_id=None, subnet_id=None, security_group_ids=None):
        
        params = {"ImageId": image_id, "MinCount": str(min_count),
                  "MaxCount": str(max_count)}
        if key_name is not None:
            params["KeyName"] = key_name
        if subnet_id is not None:
            params["SubnetId"] = subnet_id
            if security_group_ids is not None:
                for i, id in enumerate(security_group_ids):
                    params["SecurityGroupId.%d" % (i + 1)] = id
            else:
                msg = "You must specify the security_group_ids with the subnet_id"
                raise ValueError(msg)
        elif security_groups is not None:
            for i, name in enumerate(security_groups):
                params["SecurityGroup.%d" % (i + 1)] = name
        else:
            msg = ("You must specify either the subnet_id and "
                   "security_group_ids or security_groups")
            raise ValueError(msg)
        if user_data is not None:
            params["UserData"] = b64encode(user_data)
        if instance_type is not None:
            params["InstanceType"] = instance_type
        if availability_zone is not None:
            params["Placement.AvailabilityZone"] = availability_zone
        if kernel_id is not None:
            params["KernelId"] = kernel_id
        if ramdisk_id is not None:
            params["RamdiskId"] = ramdisk_id
        query = self.query_factory(
            action="RunInstances", creds=self.creds, endpoint=self.endpoint,
            other_params=params)
        d = query.submit()
        return d.addCallback(self.parser.run_instances)
220046
def show_instance(name, call=None):
    '''
    
    '''
    response = _query('grid', 'server/get', args={'name': name})
    ret = {}
    for item in response['list']:
        name = item['name']
        ret[name] = item

        ret[name]['image_info'] = item['image']
        ret[name]['image'] = item['image']['friendlyName']
        ret[name]['size'] = item['ram']['name']
        ret[name]['public_ips'] = [item['ip']['ip']]
        ret[name]['private_ips'] = []
        ret[name]['state_info'] = item['state']
        if 'active' in item['state']['description']:
            ret[name]['state'] = 'RUNNING'
    return ret
882251
def watch_instances(self, flag):
        """"""
        lib.EnvSetDefclassWatchInstances(self._env, int(flag), self._cls)
762819
def list_instances(self, tag_values=None):

        '''
            
        '''

        title = '%s.list_instances' % self.__class__.__name__

    # validate inputs
        input_fields = {
            'tag_values': tag_values
        }
        for key, value in input_fields.items():
            if value:
                object_title = '%s(%s=%s)' % (title, key, str(value))
                self.fields.validate(value, '.%s' % key, object_title)
            
    # add tags to method arguments
        kw_args = {}
        tag_text = ''
        if tag_values:
            kw_args = {
                'Filters': [ { 'Name': 'tag-value', 'Values': tag_values } ]
            }
            from labpack.parsing.grammar import join_words
            plural_value = ''
            if len(tag_values) > 1:
                plural_value = 's'
            tag_text = ' with tag value%s %s' % (plural_value, join_words(tag_values))
            
    # request instance details from AWS
        self.iam.printer('Querying AWS region %s for instances%s.' % (self.iam.region_name, tag_text))
        instance_list = []
        try:
            if tag_values:
                response = self.connection.describe_instances(**kw_args)
            else:
                response = self.connection.describe_instances()
        except:
            raise AWSConnectionError(title)

    # repeat request if any instances are currently pending
        response_list = response['Reservations']
        for instance in response_list:
            instance_info = instance['Instances'][0]
            if instance_info['State']['Name'] == 'pending':
                self.check_instance_state(instance_info['InstanceId'])
                try:
                    if tag_values:
                        response = self.connection.describe_instances(**kw_args)
                    else:
                        response = self.connection.describe_instances()
                except:
                    raise AWSConnectionError(title)
                response_list = response['Reservations']

    # populate list of instances with instance details
        for instance in response_list:
            instance_info = instance['Instances'][0]
            state_name = instance_info['State']['Name']
            if state_name not in ('shutting-down', 'terminated'):
                instance_list.append(instance_info['InstanceId'])

    # report results and return details
        if instance_list:
            print_out = 'Found instance'
            if len(instance_list) > 1:
                print_out += 's'
            from labpack.parsing.grammar import join_words
            print_out += ' %s.' % join_words(instance_list)
            self.iam.printer(print_out)
        else:
            self.iam.printer('No instances found.')

        return instance_list
1148818
def list_records(self, file_const=None):
        """"""
        for r in self._dataset.files:
            if file_const and r.minor_type != file_const:
                continue
            yield self.instance_from_name(r.path)
328917
def _list_deployment_instances(awsclient, deployment_id):
    
    client_codedeploy = awsclient.get_client('codedeploy')

    instances = []
    next_token = None

    # TODO refactor generic exhaust_function from this
    while True:
        request = {
            'deploymentId': deployment_id
        }
        if next_token:
            request['nextToken'] = next_token
        response = client_codedeploy.list_deployment_instances(**request)
        instances.extend(response['instancesList'])
        if 'nextToken' not in response:
            break
        next_token = response['nextToken']
    return instances