Searches for existing server instances with matching tags.  To match,
        the existing instances must also be "running".
439188
def find_existing(self):
        
        instances = self.consul.find_servers(self.tags)
        maxnames = len(instances)
        while instances:
            i = instances.pop(0)
            server_id = i[A.server.ID]
            if self.namespace.add_if_unique(server_id):
                log.info('Found existing server, %s' % server_id)
                self.server_attrs = i
                break
            if len(self.namespace.names) >= maxnames:
                break
            instances.append(i)
784708
def query_instances(session, client=None, **query):
    
    if client is None:
        client = session.client('ec2')
    p = client.get_paginator('describe_instances')
    results = p.paginate(**query)
    return list(itertools.chain(
        *[r["Instances"] for r in itertools.chain(
            *[pp['Reservations'] for pp in results])]))
116983
public static boolean hasSisterTagAfter(Tag tag, String nameToFind) {
	Body body = (Body) tag.getParent();
	List<Statement> stats = body.getStatements();
	Iterator<Statement> it = stats.iterator();
	Statement other;

	boolean isAfter = false;
	while (it.hasNext()) {
	    other = it.next();

	    if (other instanceof Tag) {
		if (isAfter) {
		    if (((Tag) other).getTagLibTag().getName().equals(nameToFind)) return true;
		}
		else if (other == tag) isAfter = true;
	    }
	}
	return false;
    }
1267756
def instances
      @instances ||= begin
        if $DEBUG
          puts 'Entering instance_ids'
          puts "Search Term: #{search_terms.inspect}"
        end

        instance_ids = search_terms.each_with_object([]) do |search_term, m|
          if (/^i-/ =~ search_term) && !(/\./ =~ search_term)
            m << search_term
          else
            ec2.servers.each do |server|
              next unless server.tags.key?('Name') \
                && (server.tags['Name'] != '') \
                && (/#{search_term}/i =~ server.tags['Name'])

              m << server.id
            end
          end
        end

        if instance_ids.empty?
          puts 'No instances by that Name/ID in this account'
          exit 1
        end

        puts "Found instances: #{instance_ids.inspect}" if $DEBUG

        ec2.servers.all 'instance-id' => instance_ids
      end
    end
1315507
def group_instances(self, zones=None):
        ''''''
        groups = {}
        meta = {}
        meta["hostvars"] = {}

        for node in self.list_nodes():

            # This check filters on the desired instance states defined in the
            # config file with the instance_states config option.
            #
            # If the instance_states list is _empty_ then _ALL_ states are returned.
            #
            # If the instance_states list is _populated_ then check the current
            # state against the instance_states list
            if self.instance_states and not node.extra['status'] in self.instance_states:
                continue

            name = node.name

            meta["hostvars"][name] = self.node_to_dict(node)

            zone = node.extra['zone'].name

            # To avoid making multiple requests per zone
            # we list all nodes and then filter the results
            if zones and zone not in zones:
                continue

            if zone in groups: groups[zone].append(name)
            else: groups[zone] = [name]

            tags = node.extra['tags']
            for t in tags:
                if t.startswith('group-'):
                    tag = t[6:]
                else:
                    tag = 'tag_%s' % t
                if tag in groups: groups[tag].append(name)
                else: groups[tag] = [name]

            net = node.extra['networkInterfaces'][0]['network'].split('/')[-1]
            net = 'network_%s' % net
            if net in groups: groups[net].append(name)
            else: groups[net] = [name]

            machine_type = node.size
            if machine_type in groups: groups[machine_type].append(name)
            else: groups[machine_type] = [name]

            image = node.image and node.image or 'persistent_disk'
            if image in groups: groups[image].append(name)
            else: groups[image] = [name]

            status = node.extra['status']
            stat = 'status_%s' % status.lower()
            if stat in groups: groups[stat].append(name)
            else: groups[stat] = [name]

        groups["_meta"] = meta

        return groups
738340
def thread_matches? t, query
    t.subj =~ query || t.snippet =~ query || t.participants.any? { |x| x.longname =~ query }
  end
784036
def find(self, tag_name, params=None, fn=None, case_sensitive=False):
        
        return [
            x for x in self.findAll(tag_name, params, fn, case_sensitive)
            if not x.isEndTag()
        ]
1295575
def matches(self, tag, id, classes):
        
        element = self.elements[0]
        unmatched_ids = [name[1:] for name in element.names if name.startswith('#')]
        unmatched_classes = [name[1:] for name in element.names if name.startswith('.')]
        unmatched_tags = [name for name in element.names if name is not '*' and not name.startswith('#') and not name.startswith('.')]
        
        if tag and tag in unmatched_tags:
            unmatched_tags.remove(tag)

        if id and id in unmatched_ids:
            unmatched_ids.remove(id)

        for class_ in classes:
            if class_ in unmatched_classes:
                unmatched_classes.remove(class_)
        
        if unmatched_tags or unmatched_ids or unmatched_classes:
            return False

        else:
            return True
1134253
def _tag_matches(tags, filter):
        """"""
        for tag_name, tag_value in filter.items():
            # using _sentinel as I'm not sure that "None"
            # could be used, because it could be a valid
            # series_tags value : when a series has no such tag
            # then I think it's set to /null/None/.. TBC..
            series_tag_value = tags.get(tag_name, _sentinel)
            if series_tag_value != tag_value:
                return False

        return True
1147766
def exists(name, tags=None, region=None, key=None, keyid=None, profile=None):
    '''
    
    '''
    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)

    try:
        rds = conn.describe_db_instances(DBInstanceIdentifier=name)
        return {'exists': bool(rds)}
    except ClientError as e:
        return {'error': __utils__['boto3.get_error'](e)}
1165576
def tag_exists(self, version):
        
        for tag in self.available_tags():
            if tag == version:
                return True
        return False
1341484
def findB(self, tag_name, params=None, fn=None, case_sensitive=False):
        
        return [
            x for x in self.findAllB(tag_name, params, fn, case_sensitive)
            if not x.isEndTag()
        ]
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
217496
def check_unique_tags(tag_list):
  """"""
  frozen_tags_seen = set()
  for tags in tag_list:
    frozen_tags = frozenset(tags)
    if frozen_tags in frozen_tags_seen:
      raise ValueError("Tags %r used repeatedly" % tags)
    frozen_tags_seen.add(frozen_tags)
188277
def find_db_instance(self, name, running=True):
        
        found = None
        for i in self.provider.reddwarf_client.instances.list():
            if i.name == name:
                if not running:  # don't care if it's running or not
                    found = i
                if i.status == 'running':
                    found = i
        if found:
            log.info("Found existing db, %s (%s)" % (found.name, found.id))
            return db_to_dict(found)
399273
def find_servers
      # need a run_context to find anything in
      return nil unless run_context
      # If there are already servers in attribs use those
      return node[:etcd][:servers] if node.key?(:etcd) &&
                                      node[:etcd].key?(:servers)

      # if we have already searched in this run use those
      return node.run_state[:etcd_servers] if node.run_state.key? :etcd_servers

      # find nodes and build array of ip's
      etcd_nodes = search(:node, search_query)
      servers = etcd_nodes.map { |n| n[:ipaddress] }

      # store that in the run_state
      node.run_state[:etcd_servers] = servers
    end
1102359
def DeleteInstanceTags(r, instance, tags, dry_run=False):
    

    query = {
        "tag": tags,
        "dry-run": dry_run,
    }

    return r.request("delete", "/2/instances/%s/tags" % instance, query=query)