def lookup_instances(fragment, verbose=True, filter_by_key=True):
  """Returns ec2.Instance object whose name contains fragment, in reverse order of launching (ie,
  most recent intance first). Optionally filters by key, only including instances launched with
  key_name matching current username.

  args:
    verbose: print information about all matching instances found

    filter_by_key  if True, ignore instances that are not launched with current
        user's default key
  """

  def vprint(*args):
    if verbose:
      print(*args)

  region = get_region()
  client = get_ec2_client()
  ec2 = get_ec2_resource()
  response = client.describe_instances()
  assert is_good_response(response)

  instance_list = []
  for instance in ec2.instances.all():
    if instance.state['Name'] != 'running':
      continue

    name = get_name(instance)
    if (fragment in name or fragment in str(instance.public_ip_address) or
            fragment in str(instance.id) or fragment in str(instance.private_ip_address)):
      instance_list.append((util.toseconds(instance.launch_time), instance))

  sorted_instance_list = reversed(sorted(instance_list, key=itemgetter(0)))
  filtered_instance_list = []  # filter by key
  vprint("Using region ", region)
  for (ts, instance) in sorted_instance_list:
    if filter_by_key and instance.key_name != get_keypair_name():
      vprint(f"Got key {instance.key_name}, expected {get_keypair_name()}")
      continue
    filtered_instance_list.append(instance)
  return filtered_instance_list
Returns ec2.Instance object whose name contains fragment, in reverse order of launching (ie,
  most recent intance first). Optionally filters by key, only including instances launched with
  key_name matching current username.

  args:
    verbose: print information about all matching instances found

    filter_by_key  if True, ignore instances that are not launched with current
        user's default key