a method to discover the list of subnets on AWS EC2

        :param tag_values: [optional] list of tag values
        :return: list of strings with subnet ids
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
624975
def list_subnets(self, retrieve_all=True, **_params):
        """"""
        return self.list('subnets', self.subnets_path, retrieve_all,
                         **_params)
1199304
def list_nodes(call=None):
    '''
    
    '''
    if call == 'action':
        raise SaltCloudSystemExit(
            'The list_nodes function must be called with -f or --function.'
        )

    ret = {}
    items = query(action='ve')

    for item in items:
        name = item.attrib['name']
        node = show_instance(name, call='action')

        ret[name] = {
            'id': node['id'],
            'image': node['platform']['template-info']['name'],
            'state': node['state'],
        }
        if 'private-ip' in node['network']:
            ret[name]['private_ips'] = [node['network']['private-ip']]
        if 'public-ip' in node['network']:
            ret[name]['public_ips'] = [node['network']['public-ip']]

    return ret
783969
def get_subnets():
        
        LOGGER.debug("SubnetService.get_subnets")
        args = {'http_operation': 'GET', 'operation_path': ''}
        response = SubnetService.requester.call(args)
        ret = None
        if response.rc == 0:
            ret = []
            for subnet in response.response_content['subnets']:
                ret.append(Subnet.json_2_subnet(subnet))
        elif response.rc != 404:
            err_msg = 'SubnetService.get_subnets - Problem while getting subnets. ' \
                      '. Reason: ' + str(response.response_content) + '-' + str(response.error_message) + \
                      " (" + str(response.rc) + ")"
            LOGGER.warning(err_msg)
        return ret
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());
        }

    }
113265
def view_all_tags(ctx, param, value):
    
    # To make sure this function executed only when the flag was called
    if not value or ctx.resilient_parsing:
        return
    avail_tags = dict()
    print("\nMultiQC Available module tag groups:\n")
    for mod_dict in filter(lambda mod:isinstance(mod, dict), config.module_order):
        mod_key, mod_val = list(mod_dict.items())[0]
        tags = list(mod_val.get('module_tag', []))
        for t in tags:
            if t not in avail_tags:
                avail_tags[t] = []
            avail_tags[t].append(mod_key)
    for t in sorted(avail_tags.keys(), key=lambda s: s.lower()):
        print (" - {}:".format(t))
        for ttgs in avail_tags[t]:
            print ("   - {}".format(ttgs))
    ctx.exit()
913929
def list_nictags(include_etherstubs=True):
    '''
    
    '''
    ret = {}
    cmd = 'nictagadm list -d "|" -p{0}'.format(
        ' -L' if not include_etherstubs else ''
    )
    res = __salt__['cmd.run_all'](cmd)
    retcode = res['retcode']
    if retcode != 0:
        ret['Error'] = res['stderr'] if 'stderr' in res else 'Failed to get list of nictags.'
    else:
        header = ['name', 'macaddress', 'link', 'type']
        for nictag in res['stdout'].splitlines():
            nictag = nictag.split('|')
            nictag_data = {}
            for field in header:
                nictag_data[field] = nictag[header.index(field)]
            ret[nictag_data['name']] = nictag_data
            del ret[nictag_data['name']]['name']
    return ret
757352
public List<Tag> getInstanceTags() {
    final DescribeInstancesResult response = ec2
        .describeInstances(new DescribeInstancesRequest()
            .withInstanceIds(Collections.singletonList(instanceIdentity.instanceId)));

    return response.getReservations().stream()
        .flatMap(reservation -> reservation.getInstances().stream())
        .flatMap(instance -> instance.getTags().stream())
        .collect(Collectors.toList());

  }
1180175
def tags(instance)
      return [] if instance.groupSet.nil? || instance.groupSet.item.empty?
      instance.groupSet.item.collect{|g| g.groupId }.select {|s| s.start_with? "#poolparty"}
    end
751154
def create_subnet_group(name, description, subnet_ids, tags=None,
                        region=None, key=None, keyid=None, profile=None):
    '''
    
    '''
    res = __salt__['boto_rds.subnet_group_exists'](name, tags, region, key,
                                                 keyid, profile)
    if res.get('exists'):
        return {'exists': bool(res)}

    try:
        conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
        if not conn:
            return {'results': bool(conn)}

        taglist = _tag_doc(tags)
        rds = conn.create_db_subnet_group(DBSubnetGroupName=name,
                                          DBSubnetGroupDescription=description,
                                          SubnetIds=subnet_ids, Tags=taglist)

        return {'created': bool(rds)}
    except ClientError as e:
        return {'error': __utils__['boto3.get_error'](e)}
773114
def _taglist(self, other_model=None, queryset=None):
        
        from taggit.models import TaggedItem
        filter = None
        if queryset is not None:
            filter = set()
            for item in queryset.all():
                filter.update(item.tags.all())
            filter = set([tag.id for tag in filter])
        elif other_model is not None:
            filter = set(TaggedItem.objects.filter(
                content_type__model=other_model.__name__.lower()
            ).values_list('tag_id', flat=True))
        tags = set(TaggedItem.objects.filter(
            content_type__model=self.model.__name__.lower()
        ).values_list('tag_id', flat=True))
        if filter is not None:
            tags = tags.intersection(filter)
        return list(tags)
1370187
def count_by_tag(stack, descriptor):
    
    ec2_conn = boto.ec2.connection.EC2Connection()
    resses = ec2_conn.get_all_instances(
                    filters={
                        'tag:stack': stack,
                        'tag:descriptor': descriptor
                    })
    instance_list_raw = list()
    [[instance_list_raw.append(x) for x in res.instances] for res in resses]
    instance_list = [x for x in instance_list_raw if state_filter(x)]
    instances = len(instance_list)
    return instances
582241
def list_tags(Name,
           region=None, key=None, keyid=None, profile=None):
    '''
    

    '''

    try:
        conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
        rid = _get_trail_arn(Name,
                             region=region, key=key, keyid=keyid,
                             profile=profile)
        ret = conn.list_tags(ResourceIdList=[rid])
        tlist = ret.get('ResourceTagList', []).pop().get('TagsList')
        tagdict = {}
        for tag in tlist:
            tagdict[tag.get('Key')] = tag.get('Value')
        return {'tags': tagdict}
    except ClientError as e:
        return {'error': __utils__['boto3.get_error'](e)}
820446
def get_network_stats(self, tags):
        

        # FIXME: (aaditya) Check all networks defaults to true
        # until we can reliably assign agents to networks to monitor
        if is_affirmative(self.init_config.get('check_all_networks', True)):
            all_network_ids = set(self.get_all_network_ids())

            # Filter out excluded networks
            network_ids = [
                network_id
                for network_id in all_network_ids
                if not any([re.match(exclude_id, network_id) for exclude_id in self.exclude_network_id_rules])
            ]
        else:
            network_ids = self.init_config.get('network_ids', [])

        if not network_ids:
            self.warning(
                "Your check is not configured to monitor any networks.\n"
                + "Please list `network_ids` under your init_config"
            )

        for nid in network_ids:
            self.get_stats_for_single_network(nid, tags)
328698
def get_instances_by_tag(self, tags):
        

        try:
            c = ec2.connect_to_region(self._region,
                                      aws_access_key_id=self._aws_access_key_id,
                                      aws_secret_access_key=self._aws_secret_access_key)

            # select instance by list of tags (OR used)
            reservations = c.get_all_reservations(filters=SergentSsh.tags_to_dict(tags))
            instances = list()

            for r in reservations:
                # for each instance launched by this reservation
                for instance in r.instances:
                    # we need only running instances
                    if instance.state.lower() == 'running':
                        instances.append(instance)

            return instances
        except NoAuthHandlerFound:
            raise SergentSshException('Boto said that you should check your credentials')
565326
def list(self, **kwds):
        
        tags = self._client.get("/tags/list.json", **kwds)["result"]
        tags = self._result_to_list(tags)
        return [Tag(self._client, tag) for tag in tags]
803194
function listSubnets(vpcId) {
    const params = {
        Filters: [
            {
                Name: 'vpc-id',
                Values: [vpcId]
            },
            {
                Name: 'state',
                Values: ['available']
            }
        ]
    };
    return spinner(
        ec2
            .describeSubnets(params)
            .promise()
            .then(data => data.Subnets)
    );
}