Describes the EC2 instances

        :return: dict containing EC2 instance data
        :raises: EC2UtilError
546631
def get_ec2_instances(self):
        
        log = logging.getLogger(self.cls_logger + '.get_ec2_instances')
        log.info('Describing EC2 instances...')
        try:
            response = self.client.describe_instances()
        except ClientError:
            _, ex, trace = sys.exc_info()
            msg = '{n}: There was a problem describing EC2 instances\n{e}'.format(n=ex.__class__.__name__, e=str(ex))
            raise EC2UtilError, msg, trace
        return response
343488
def retrieve_instance_links(self):
        
        instance_links = {}
        self.log.debug("LINKS IS %s", LINKS)
        for key, value in LINKS.items():
            if value not in self.pipeline_config['instance_links'].values():
                instance_links[key] = value
        return instance_links
519940
public static List<Image> describeAllImages() {
        // pass any credentials as aws-mock does not authenticate them at all
        AWSCredentials credentials = new BasicAWSCredentials("foo", "bar");
        AmazonEC2Client amazonEC2Client = new AmazonEC2Client(credentials);

        // the mock endpoint for ec2 which runs on your computer
        String ec2Endpoint = "http://localhost:8000/aws-mock/ec2-endpoint/";
        amazonEC2Client.setEndpoint(ec2Endpoint);

        // describe all AMIs in aws-mock.
        DescribeImagesResult result = amazonEC2Client.describeImages();

        return result.getImages();
    }
1291859
def http_get_instance_env():
  
  try:
    info = json.loads(http_get_metadata('iam/info'))
  except Exception as error:
    raise IOError("Error looking up metadata:iam/info: " + repr(error))
  return info["InstanceProfileArn"].split(":")[5].split("/")[1].split("-",1)[0]
76719
def print_ec2_info(region,
                   instance_id,
                   access_key_id,
                   secret_access_key,
                   username):
    
    data = get_ec2_info(instance_id=instance_id,
                        region=region,
                        access_key_id=access_key_id,
                        secret_access_key=secret_access_key,
                        username=username)

    log_green("region: %s" % data['region'])
    log_green("Instance_type: %s" % data['instance_type'])
    log_green("Instance state: %s" % data['state'])
    log_green("Public dns: %s" % data['public_dns_name'])
    log_green("Ip address: %s" % data['ip_address'])
    log_green("volume: %s" % data['volume'])
    log_green("user: %s" % data['username'])
    log_green("ssh -i %s %s@%s" % (env.key_filename,
                                   username,
                                   data['ip_address']))
746354
def get_info(cls):
        
        return '\n'.join(
            [str(cls._instances[key]) for key in cls._instances]
        )
326538
def get_vpc_dict():
  """"""

  client = get_ec2_client()
  response = client.describe_vpcs()
  assert is_good_response(response)

  result = OrderedDict()
  ec2 = get_ec2_resource()
  for vpc_response in response['Vpcs']:
    key = get_name(vpc_response.get('Tags', []))
    if not key or key == EMPTY_NAME:  # skip VPC's that don't have a name assigned
      continue

    if key in result:
      util.log(f"Warning: Duplicate VPC group {key} in {response}")
      if DUPLICATE_CHECKING:
        assert False
    result[key] = ec2.Vpc(vpc_response['VpcId'])

  return result
1340620
def _get_instance_state(self):
        
        instance = self._get_instance()
        state = None

        try:
            state = instance.state['Name']
        except Exception:
            raise EC2CloudException(
                'Instance with id: {instance_id}, '
                'cannot be found.'.format(
                    instance_id=self.running_instance_id
                )
            )

        return state
358094
def response(self):
        
        describe_request_params = {}
        if self.filter is not None:
            if type(self.filter) is not dict:
                try:
                    filters = json.loads(self.filter)
                except TypeError:
                    filters = self._parse_cli_filters(self.filter)
            else:
                filters = self.filter

            describe_request_params['Filters'] = filters
        if self.vpc_ids is not None:
            if 'Filters' not in describe_request_params:
                describe_request_params['Filters'] = []
            describe_request_params['Filters'].append({
                'Name': 'vpc-id',
                'Values': self.vpc_ids.split(',')
            })
        reservations = self.session().client('ec2').describe_instances(**describe_request_params)

        return self._process_reservations(reservations)
348628
def read_creds_from_ec2_instance_metadata():
    
    creds = init_creds()
    try:
        has_role = requests.get('http://169.254.169.254/latest/meta-data/iam/security-credentials', timeout = 1)
        if has_role.status_code == 200:
            iam_role = has_role.text
            credentials = requests.get('http://169.254.169.254/latest/meta-data/iam/security-credentials/%s/' %
                                       iam_role.strip()).json()
            for c in ['AccessKeyId', 'SecretAccessKey']:
                creds[c] = credentials[c]
            creds['SessionToken'] = credentials['Token']
        return creds
    except Exception as e:
        return False
584151
def describe(self):
        """"""
        if isinstance(self._plugin, list):
            pl = [p.name for p in self._plugin]
        elif isinstance(self._plugin, dict):
            pl = {k: classname(v) for k, v in self._plugin.items()}
        else:
            pl = self._plugin if isinstance(self._plugin, str) else self._plugin.name
        return {
            'name': self._name,
            'container': self._container,
            'plugin': pl,
            'description': self._description,
            'direct_access': self._direct_access,
            'user_parameters': [u.describe() for u in self._user_parameters],
            'metadata': self._metadata,
            'args': self._open_args
        }
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)
558438
def list_instances(self):
        
        # Server does not do pagination on listings of this resource.
        # Return an iterator anyway for similarity with other API methods
        response = self.get_proto(path='/instances')
        message = rest_pb2.ListInstancesResponse()
        message.ParseFromString(response.content)
        instances = getattr(message, 'instance')
        return iter([Instance(instance) for instance in instances])
824410
def ec2_table(instances):
    
    t = prettytable.PrettyTable(['ID', 'State', 'Monitored', 'Image', 'Name', 'Type', 'SSH key', 'DNS'])
    t.align = 'l'
    for i in instances:
        name = i.tags.get('Name', '')
        t.add_row([i.id, i.state, i.monitored, i.image_id, name, i.instance_type, i.key_name, i.dns_name])
    return t
1119816
def get_ec2_info(connection,
                 instance_id,
                 region,
                 username=None):
    
    instance = connection.get_only_instances(
        filters={'instance_id': instance_id}
        )[0]

    data = instance.__dict__
    data['state'] = instance.state
    data['cloud_type'] = 'ec2'

    try:
        volume = connection.get_all_volumes(
            filters={'attachment.instance-id': instance.id}
        )[0].id
        data['volume'] = volume
    except:
        data['volume'] = ''
    return data
805932
def show_instance(name, call=None):
    '''
    
    '''
    if call != 'action':
        raise SaltCloudSystemExit(
            'The show_instance action must be called with -a or --action.'
        )
    try:
        node = list_nodes_full('function')[name]
    except KeyError:
        log.debug('Failed to get data for node \'%s\'', name)
        node = {}

    __utils__['cloud.cache_node'](node, __active_provider_name__, __opts__)

    return node
309555
def describe(self):
        
        response = {
            'TransformJobStatus': self.state,
            'ModelName': self.model_name,
            'TransformJobName': self.name,
            'TransformJobArn': _UNUSED_ARN,
            'TransformEndTime': self.end_time,
            'CreationTime': self.start_time,
            'TransformStartTime': self.start_time,
            'Environment': {},
            'BatchStrategy': self.batch_strategy,
        }

        if self.transform_resources:
            response['TransformResources'] = self.transform_resources

        if self.output_data:
            response['TransformOutput'] = self.output_data

        if self.input_data:
            response['TransformInput'] = self.input_data

        return response