code: def launch_ec2_instance(region, instance_type, ami_id):
      """
      Note: This function relies on CODEBUILD environment variables. If this function is used outside of CODEBUILD,
      modify the function accordingly.
      Spins up an ec2 instance, clones the current Github Pull Request commit id on the instance, and runs sanity test on it.
      Prints the output of the command executed.
      """
      github_repo = os.environ.get(
          "CODEBUILD_SOURCE_REPO_URL",
          "https://github.com/pytorch/serve.git",
      ).strip()
      github_pr_commit_id = os.environ.get(
          "CODEBUILD_RESOLVED_SOURCE_VERSION", "HEAD"
      ).strip()
      github_hookshot = os.environ.get(
          "CODEBUILD_SOURCE_VERSION", "job-local"
      ).strip()
      github_hookshot = github_hookshot.replace("/", "-")
  
      # Extract the PR number or use the last 6 characters of the commit id
      github_pull_request_number = (
          github_hookshot.split("-")[1]
          if "-" in github_hookshot
          else github_hookshot[-6:]
      )
  
      ec2_client = boto3.client(
          "ec2",
          config=Config(retries={"max_attempts": 10}),
          region_name=region,
      )
      random.seed(
          f"{datetime.datetime.now().strftime('%Y%m%d%H%M%S%f')}"
      )
      ec2_key_name = (
          f"{github_hookshot}-ec2-instance-{random.randint(1, 1000)}"
      )
  
      # Spin up ec2 instance and run tests
      try:
          key_file = ec2_utils.generate_ssh_keypair(
              ec2_client, ec2_key_name
          )
          instance_details = ec2_utils.launch_instance(
              ami_id,
              instance_type,
              ec2_key_name=ec2_key_name,
              region=region,
              user_data=None,
              iam_instance_profile_name=ec2_utils.EC2_INSTANCE_ROLE_NAME,
              instance_name=ec2_key_name,
          )
  
          instance_id = instance_details["InstanceId"]
          ip_address = ec2_utils.get_public_ip(
              instance_id, region=region
          )
  
          LOGGER.info(f"*** Waiting on instance checks to complete...")
          ec2_utils.check_instance_state(
              instance_id, state="running", region=region
          )
          ec2_utils.check_system_state(
              instance_id,
              system_status="ok",
              instance_status="ok",
              region=region,
          )
          LOGGER.info(
              f"*** Instance checks complete. Running commands on instance."
          )
  
          # Create a fabric connection to the ec2 instance.
          ec2_connection = ec2_utils.get_ec2_fabric_connection(
              instance_id, key_file, region
          )
  
          # Wait for a few minutes before running any command since ubuntu runs background updates.
          time.sleep(300)
  
          LOGGER.info(
              f"Running update command. This could take a while."
          )
          ec2_connection.run(f"sudo apt update")
  
          time.sleep(300)
  
          with ec2_connection.cd("/home/ubuntu"):
              LOGGER.info(
                  f"*** Cloning the PR related to {github_hookshot} on the ec2 instance."
              )
              ec2_connection.run(f"git clone {github_repo}")
              if "pr" in github_hookshot:
                  ec2_connection.run(
                      f"cd serve && git fetch origin pull/{github_pull_request_number}/head:pull && git checkout pull"
                  )
              else:
                  ec2_connection.run(
                      f"cd serve && git fetch origin {github_pull_request_number}"
                  )
  
              ec2_connection.run(
                  f"sudo apt-get install -y python3.8-dev python3.8-distutils python3.8-venv"
              )
              # update alternatives doesn't seem to work
              ec2_connection.run(
                  f"sudo ln -fs /usr/bin/python3.8 /usr/bin/python"
              )
              # Following is necessary on Base Ubuntu DLAMI because the default python is python2
              # This will NOT fail for other AMI where default python is python3
              ec2_connection.run(
                  f"curl -O https://bootstrap.pypa.io/get-pip.py && python get-pip.py",
                  warn=True,
              )
  
          is_gpu = True if instance_type[:2] in GPU_INSTANCES else False
  
          command_return_value_map = run_commands_on_ec2_instance(
              ec2_connection, is_gpu
          )
  
          if any(command_return_value_map.values()):
              raise ValueError(
                  f"*** One of the commands executed on ec2 returned a non-zero value."
              )
          else:
              LOGGER.info(
                  f"*** All commands executed successfully on ec2. command:return_value map is as follows:"
              )
              LOGGER.info(command_return_value_map)
  
      except ValueError as e:
          LOGGER.error(f"*** ValueError: {e}")
          LOGGER.error(
              f"*** Following commands had the corresponding return value:"
          )
          LOGGER.error(command_return_value_map)
          raise e
      except Exception as e:
          LOGGER.error(f"*** Exception occured. {e}")
          raise e
      finally:
          LOGGER.warning(
              f"*** Terminating instance-id: {instance_id} with name: {ec2_key_name}"
          )
          ec2_utils.terminate_instance(instance_id, region)
          LOGGER.warning(f"*** Destroying ssh key_pair: {ec2_key_name}")
          ec2_utils.destroy_ssh_keypair(ec2_client, ec2_key_name)
  
file_path: serve/ci/launcher/launch_test.py
imports: import argparse
  import boto3
  import datetime
  import random
  import subprocess
  import os
  import time
  from botocore.config import Config
  from fabric2 import Connection
  from invoke import run
  from utils import LOGGER, GPU_INSTANCES
  from utils import ec2
label_desc: Use image node_id 2 for calling a global function with example usage: launch_ec2_instance(region, instance_type, ami_id) without return types