def precheck_ami_id(context):
  """
  Is the AMI in service the same as the AMI marked current in the version records?
  This tool won't update records unless the world state is coherent.
  Args:
    context: a populated EFVersionContext object
  Returns:
    True if ok to proceed
  Raises:
    RuntimeError if not ok to proceed
  """
  # get the current AMI
  key = "{}/{}".format(context.env, context.service_name)
  print_if_verbose("precheck_ami_id with key: {}".format(key))
  current_ami = context.versionresolver.lookup("ami-id,{}".format(key))
  print_if_verbose("ami found: {}".format(current_ami))

  # If bootstrapping (this will be the first entry in the version history)
  # then we can't check it vs. running version
  if current_ami is None:
    print_if_verbose("precheck passed without check because current AMI is None")
    return True

  # Otherwise perform a consistency check
  # 1. get IDs of instances running the AMI - will find instances in all environments
  instances_running_ami = context.aws_client("ec2").describe_instances(
      Filters=[{
          'Name': 'image-id',
          'Values': [current_ami]
      }]
  )["Reservations"]
  if instances_running_ami:
    instances_running_ami = [resv["Instances"][0]["InstanceId"] for resv in instances_running_ami]
  print_if_verbose("instances running ami {}:\n{}".format(current_ami, repr(instances_running_ami)))

  # 2. Get IDs of instances running as <context.env>-<context.service_name>
  env_service = "{}-{}".format(context.env, context.service_name)
  instances_running_as_env_service = context.aws_client("ec2").describe_instances(
      Filters=[{
          'Name': 'iam-instance-profile.arn',
          'Values': ["arn:aws:iam::*:instance-profile/{}-{}".format(context.env, context.service_name)]
      }]
  )["Reservations"]
  if instances_running_as_env_service:
    instances_running_as_env_service = \
        [resv["Instances"][0]["InstanceId"] for resv in instances_running_as_env_service]
  print_if_verbose("instances running as {}".format(env_service))
  print_if_verbose(repr(instances_running_as_env_service))

  # 3. Instances running as env-service should be a subset of instances running the AMI
  for instance_id in instances_running_as_env_service:
    if instance_id not in instances_running_ami:
      raise RuntimeError("Instance: {} not running expected ami: {}".format(instance_id, current_ami))

  # Check passed - all is well
  return True