Lab 006: Launch EC2 Instance
Requirements
The Nautilus DevOps team is strategizing the migration of a portion of their infrastructure to the AWS cloud. Recognizing the scale of this undertaking, they have opted to approach the migration in incremental steps rather than as a single massive transition. To achieve this, they have segmented large tasks into smaller, more manageable units.
For this task, create an EC2 instance with following requirements:
-
The name of the instance must be datacenter-ec2.
-
You can use the Amazon Linux AMI to launch this instance.
-
The Instance type must be t2.micro.
-
Create a new RSA key pair named datacenter-kp.
-
Attach the default (available by default) security group.
-
Create the instance in us-east-1 region.
This page keeps the original requirement statement and provides one deterministic AWS CLI workflow to launch the instance.
Prerequisites
- AWS CLI is installed and authenticated on
aws-client. - Credentials are available (use
showcredswhen required). - The active identity can create key pairs and launch EC2 instances in
us-east-1.
Steps
For the AWS credentials, enter showcreds command on aws-client host to retrieve the credentials. For further details, check out the Project Nautilus documentation.
To create a EC2 instance with specified requirements using the AWS CLI, you can follow these steps:
#!/bin/bash
# Step 1: Create Key Pair
aws ec2 create-key-pair --key-name datacenter-kp --query 'KeyMaterial' --output text > datacenter-kp.pem
chmod 400 datacenter-kp.pem
# Step 2: Retrieve the Amazon Linux AMI ID
AMI_ID=$(aws ec2 describe-images \
--region us-east-1 \
--filters "Name=name,Values=amzn2-ami-hvm-2.0.????????-x86_64-gp2" \
"Name=state,Values=available" \
--query "Images | sort_by(@, &CreationDate)[-1].ImageId" \
--output text)
# Step 3: Get Default Security Group
SECURITY_GROUP_ID=$(aws ec2 describe-security-groups \
--region us-east-1 \
--filters "Name=group-name,Values=default" \
--query 'SecurityGroups[0].GroupId' \
--output text)
# Step 4: Launch EC2 Instance
INSTANCE_ID=$(aws ec2 run-instances \
--region us-east-1 \
--image-id $AMI_ID \
--instance-type t2.micro \
--key-name datacenter-kp \
--security-group-ids $SECURITY_GROUP_ID \
--tag-specifications 'ResourceType=instance,Tags=[{Key=Name,Value=datacenter-ec2}]' \
--query 'Instances[0].InstanceId' \
--output text)
# Step 5: Verify Instance
echo "Instance launched with ID: $INSTANCE_ID"
aws ec2 describe-instances \
--region us-east-1 \
--instance-ids $INSTANCE_ID \
--query 'Reservations[0].Instances[0].[InstanceId,State.Name,KeyName,Tags]' \
--output table
Verification
- Confirm the instance named
datacenter-ec2is inrunningstate. - Confirm instance type is
t2.microand key pair isdatacenter-kp.
aws ec2 describe-instances \
--region us-east-1 \
--filters "Name=tag:Name,Values=datacenter-ec2" \
--query "Reservations[0].Instances[0].{InstanceId:InstanceId,State:State.Name,InstanceType:InstanceType,KeyName:KeyName}" \
--output table