def lookup_instance(name: str, instance_type: str = '', image_name: str = '',
                    states: tuple = ('running', 'stopped', 'initializing')):
  ec2 = get_ec2_resource()
  instances = ec2.instances.filter(
    Filters=[{'Name': 'instance-state-name', 'Values': states}])
  prefix = get_prefix()
  username = get_username()
  result = []
  for i in instances.all():
    instance_name = get_name(i)
    if instance_name != name:
      continue
    seen_prefix, seen_username = parse_key_name(i.key_name)
    if prefix != seen_prefix:
      print(f"Found {name} launched under {seen_prefix}, ignoring")
      continue
    if username != seen_username:
      print(f"Found {name} launched by {seen_username}, ignoring")
      continue
    if instance_type:
      assert i.instance_type == instance_type, f"Found existing instance for job {name} but different instance type ({i.instance_type}) than requested ({instance_type}), terminate {name} first or use new task name."
    if image_name:
      assert i.image.name == image_name, f"Found existing instance for job {name} but launched with different image ({i.image.name}) than requested ({image_name}), terminate {name} first or use new task name."
    result.append(i)
    assert len(result) < 2, f"Found two instances with name {name}"
    if not result:
      return None
    else:
      return result[0]