EC2 – Run Instances – InstanceId

So you are creating EC2 instances from the AWS CLI and\or Python using BOTO 3 and you want to get the InstanceId afterwards.  Below are the method(s) I use in each scenario.

Create 1 EC2 Instance with AWS CLI:

Example Command:

aws ec2 run-instances --profile <value> --image-id <value> --security-group-ids <value> --count 1 --instance-type <value> --subnet-id <value> --query 'Instances[0].InstanceID'

Create multiple EC2 Instances with Python\Boto3:

Example Command:

ec2_session_client = session.client('ec2')
response = ec2_session_client.run_instances(ImageID="value",SecurityGroupIds=["value"],MaxCount=value,MinCount=value,InstanceType="value",SubnetId="value")
for instance in response["Instances"]:
   if 'InstanceId' in instance"
      print (instance['InstanceId'])

So these are just a couple ways to grab the InstanceId for use later in your script.

aws_instanceid.png