Complete Guide: Setting up EC2 Instances Using AWS CLI
This guide explains how to launch, manage, and connect to EC2 instances using the AWS CLI.
Step 0 — Prerequisites
- AWS Account
- AWS CLI Installed & Configured
bash
aws configure
- Enter your Access Key ID, Secret Access Key, region, and output format (json)
- Key Pair for SSH Access
- You will need a key pair to connect via SSH.
Step 1 — Create a Key Pair
bash
aws ec2 create-key-pair --key-name MyKeyPair --query 'KeyMaterial' --output text > MyKeyPair.pem
- Make the key private:
bash
chmod 400 MyKeyPair.pem
Step 2 — Choose an AMI (Amazon Machine Image)
- List available AMIs:
bash
aws ec2 describe-images --owners amazon --filters "Name=name,Values=amzn2-ami-hvm-*-x86_64-gp2" --query 'Images[*].[ImageId,Name]' --output table
- Note the
ImageIdyou want (e.g.,ami-0abcdef1234567890).
Step 3 — Create a Security Group
bash
aws ec2 create-security-group --group-name MySecurityGroup --description "My EC2 security group"
- Add inbound rule to allow SSH:
bash
aws ec2 authorize-security-group-ingress --group-name MySecurityGroup --protocol tcp --port 22 --cidr 0.0.0.0/0
- Add inbound rule for HTTP (optional):
bash
aws ec2 authorize-security-group-ingress --group-name MySecurityGroup --protocol tcp --port 80 --cidr 0.0.0.0/0
Step 4 — Launch an EC2 Instance
bash
aws ec2 run-instances \
--image-id ami-0abcdef1234567890 \
--count 1 \
--instance-type t2.micro \
--key-name MyKeyPair \
--security-groups MySecurityGroup
Options:
--count→ number of instances--instance-type→ instance size (t2.micro is free tier eligible)
After launching, note the InstanceId.
Step 5 — Describe Instances
bash
aws ec2 describe-instances --query 'Reservations[*].Instances[*].[InstanceId,State.Name,PublicIpAddress]' --output table
- Check Public IP to connect via SSH.
Step 6 — Connect via SSH
bash
ssh -i "MyKeyPair.pem" ec2-user@<Public-IP>
- For Amazon Linux, default username is
ec2-user. - For Ubuntu, use
ubuntu.
Step 7 — Stop, Start, and Terminate Instances
Stop an instance
bash
aws ec2 stop-instances --instance-ids i-0123456789abcdef0
Start an instance
bash
aws ec2 start-instances --instance-ids i-0123456789abcdef0
Terminate an instance
bash
aws ec2 terminate-instances --instance-ids i-0123456789abcdef0
Step 8 — Optional: Tagging Resources
bash
aws ec2 create-tags --resources i-0123456789abcdef0 --tags Key=Name,Value=MyEC2Instance
- Helps identify instances in AWS console.
Step 9 — Summary Workflow
aws ec2 create-key-pair→ create key for SSHaws ec2 describe-images→ choose AMIaws ec2 create-security-group→ allow SSH/HTTPaws ec2 run-instances→ launch instanceaws ec2 describe-instances→ get Public IPssh -i→ connectstop/start/terminate→ manage instance lifecycle
✅ Tips
- Use t2.micro for free tier testing.
- Security groups are like firewall rules; restrict SSH to your IP for safety.
- Always terminate instances when done to avoid charges.
- Combine AWS CLI with scripts for automation.