a method to retrieve the list of instances on AWS EC2

        :param tag_values: [optional] list of tag values
        :return: list of strings with instance AWS ids
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
1368525
def tag_instance(instance_id, **tags):
    """"""
    logger.debug("Got request to add tags %s to instance %s."
                 % (str(tags), instance_id))
    ec2 = boto3.resource('ec2')
    instance = ec2.Instance(instance_id)

    # Remove None's from `tags`
    filtered_tags = {k: v for k, v in tags.items() if v and k}

    # Check for existing tags
    if instance.tags is not None:
        existing_tags = {tag.get('Key'): tag.get('Value')
                         for tag in instance.tags}
        logger.debug("Ignoring existing tags; %s" % str(existing_tags))
        for tag_key in existing_tags.keys():
            filtered_tags.pop(tag_key, None)

    # If we have new tags to add, add them.
    tag_list = [{'Key': k, 'Value': v} for k, v in filtered_tags.items()]
    if len(tag_list):
        logger.info('Adding project tags "%s" to instance %s'
                    % (filtered_tags, instance_id))
        instance.create_tags(Tags=tag_list)
    else:
        logger.info('No new tags from: %s' % str(tags))
    return
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
803282
def instances(exp=".*"):
    ""
    expression = re.compile(exp)
    instances = []
    for node in ec2_instances():
        if node.tags and ip(node):
            try:
                if expression.match(node.tags.get("Name")):
                    instances.append(node)
            except TypeError:
                pass
    return instances
664249
def query_tag_values(self, metric_type=None, **tags):
        
        tagql = self._transform_tags(**tags)

        return self._get(self._get_metrics_tags_url(self._get_url(metric_type)) + '/{}'.format(tagql))
709772
def list_ec2(region, filter_by_kwargs):
    """"""
    conn = boto.ec2.connect_to_region(region)
    instances = conn.get_only_instances()
    return lookup(instances, filter_by=filter_by_kwargs)
220345
private void tagResources(List<String> resources, List<Tag> tags) {
        // Create a tag request.
        CreateTagsRequest createTagsRequest = new CreateTagsRequest();
        createTagsRequest.setResources(resources);
        createTagsRequest.setTags(tags);

        // Try to tag the Spot request submitted.
        try {
            ec2.createTags(createTagsRequest);
        } catch (AmazonServiceException e) {
            // Write out any exceptions that may have occurred.
            System.out.println("Error terminating instances");
            System.out.println("Caught Exception: " + e.getMessage());
            System.out.println("Reponse Status Code: " + e.getStatusCode());
            System.out.println("Error Code: " + e.getErrorCode());
            System.out.println("Request ID: " + e.getRequestId());
        }

    }
347732
def list_subnets(self, tag_values=None):

        '''
            
        '''

        title = '%s.list_subnets' % 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 subnets%s.' % (self.iam.region_name, tag_text))
        subnet_list = []
        try:
            if kw_args:
                response = self.connection.describe_subnets(**kw_args)
            else:
                response = self.connection.describe_subnets()
        except:
            raise AWSConnectionError(title)
        response_list = []
        if 'Subnets' in response:
            response_list = response['Subnets']

    # construct list of subnets from response
        for sub_dict in response_list:
            subnet_list.append(sub_dict['SubnetId'])

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

        return subnet_list
179861
def tag_instance(self, instance_id, tag_list):

        '''
            
        '''

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

    # validate inputs
        input_fields = {
            'instance_id': instance_id,
            'tag_list': tag_list
        }
        for key, value in input_fields.items():
            object_title = '%s(%s=%s)' % (title, key, str(value))
            self.fields.validate(value, '.%s' % key, object_title)
    
    # retrieve tag list of instance
        self.iam.printer_on = False
        instance_details = self.read_instance(instance_id)
        self.iam.printer_on = True
        old_tags = instance_details['tags']
    
    # determine tags to remove
        delete_list = []
        tag_map = {}
        for tag in tag_list:
            tag_map[tag['key']] = tag['value']
        for tag in old_tags:
            if tag['key'] not in tag_map.keys():
                delete_list.append(tag)
            elif tag['value'] != tag_map[tag['key']]:
                delete_list.append(tag)

    # convert tag list to camelcase
        delete_list = self.iam.prepare(delete_list)
        tag_list = self.iam.prepare(tag_list)
    
    # remove tags from instance
        if delete_list:
            try:
                delete_kwargs = {
                    'Resources': [ instance_id ],
                    'Tags': delete_list
                }
                self.connection.delete_tags(**delete_kwargs)
            except:
                AWSConnectionError(title)
            
    # tag instance with updated tags
        try:
            create_kwargs = {
                'Resources': [ instance_id ],
                'Tags': tag_list
            }
            response = self.connection.create_tags(**create_kwargs)
        except:
            raise AWSConnectionError(title)
        
        return response
725909
def _get_current_tags(name, runas=None):
    '''
    
    '''
    try:
        return list(__salt__['rabbitmq.list_users'](runas=runas)[name])
    except CommandExecutionError as err:
        log.error('Error: %s', err)
        return []
21384
def add_tags(self):
        
        session = boto3.session.Session(profile_name=self.env, region_name=self.region)
        resource = session.resource('ec2')
        group_id = get_security_group_id(self.app_name, self.env, self.region)
        security_group = resource.SecurityGroup(group_id)

        try:
            tag = security_group.create_tags(
                DryRun=False,
                Tags=[{
                    'Key': 'app_group',
                    'Value': self.group
                }, {
                    'Key': 'app_name',
                    'Value': self.app_name
                }])
            self.log.debug('Security group has been tagged: %s', tag)
        except botocore.exceptions.ClientError as error:
            self.log.warning(error)

        return True
1298595
def get_values(self, *args, **kwargs):
        
        if isinstance(args[0], list):
            raise ValueError("Can only get_values() for a single tag.")

        response = self.get_datapoints(*args, **kwargs)
        for value in response['tags'][0]['results'][0]['values']:
            yield [datetime.datetime.utcfromtimestamp(value[0]/1000),
                   value[1],
                   value[2]]
566464
def ls(ctx, name, list_formatted):
    """"""
    session = create_session(ctx.obj['AWS_PROFILE_NAME'])
    ec2 = session.resource('ec2')
    if name == '*':
        instances = ec2.instances.filter()
    else:
        condition = {'Name': 'tag:Name', 'Values': [name]}
        instances = ec2.instances.filter(Filters=[condition])
    out = format_output(instances, list_formatted)
    click.echo('\n'.join(out))
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
571197
def list_tags(self, pattern=None):
        
        request_url = "{}tags".format(self.create_basic_url())

        params = None
        if pattern:
            params = {'pattern': pattern}

        return_value = self._call_api(request_url, params=params)
        return return_value['tags']
1196976
def tag_value(self, p_key, p_default=None):
        
        return self.tag_values(p_key)[0] if p_key in self.fields['tags'] else p_default
687100
def start_instances(self, instance_ids=None):
        
        params = {}
        if instance_ids:
            self.build_list_params(params, instance_ids, 'InstanceId')
        return self.get_list('StartInstances', params,
                             [('item', Instance)], verb='POST')