iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

EC2

EC2 is virtual machines on demand. Pick an AMI + instance type + storage + security group; pay per second. The foundation underneath every higher-level AWS compute service.

Launch, SSH, security groups, types

EXAMPLE
# 1) Launch an instance (CLI)
aws ec2 run-instances \
    --image-id ami-0c7217cdde317cfec \           # Amazon Linux 2023 AMI
    --instance-type t3.small \
    --key-name my-keypair \
    --security-group-ids sg-0abc123 \
    --subnet-id subnet-0def456 \
    --associate-public-ip-address \
    --iam-instance-profile Name=ec2-app-role \
    --block-device-mappings '[{"DeviceName":"/dev/xvda","Ebs":{"VolumeSize":30,"VolumeType":"gp3","DeleteOnTermination":true}}]' \
    --user-data file://userdata.sh \
    --tag-specifications 'ResourceType=instance,Tags=[{Key=Name,Value=web-1},{Key=Env,Value=prod}]'

# Returns: 'InstanceId': 'i-abc123...'

# 2) SSH in
chmod 400 my-keypair.pem
ssh -i my-keypair.pem ec2-user@<public-ip>

# Better: use AWS Systems Manager Session Manager (no SSH port open, no keys)
aws ssm start-session --target i-abc123

# 3) Instance type families
# General      : t3 / t4g (burstable, cheap), m6i / m7g (balanced)
# Compute      : c6i / c7g (CPU-heavy)
# Memory       : r6i / x2gd (RAM-heavy DBs)
# Storage      : i4i (NVMe), d3 (HDD)
# GPU          : g5 / g6 (graphics, ML inference), p4d (training)
# Inferentia   : inf2 (cheap ML inference)
# Burst        : t* family — sustained CPU > baseline burns credits

# Graviton (g suffix) = ARM, ~20% cheaper than x86 equivalents; supported by most modern stacks.

# 4) Choosing size
# Tools:
#   - aws ec2 describe-instance-types --filters Name=processor-info.supported-architecture,Values=arm64 --query 'InstanceTypes[].[InstanceType, VCpuInfo.DefaultVCpus, MemoryInfo.SizeInMiB]'
#   - https://instances.vantage.sh — searchable comparison
#   - CloudWatch metrics on existing instances → CPU 90th percentile → next size up

# 5) Storage (EBS)
# gp3 (default)  — general SSD, baseline 3000 IOPS, scale IOPS + throughput independently
# gp2            — older general SSD; gp3 is cheaper + more flexible
# io2            — provisioned IOPS, high durability (databases)
# st1 / sc1      — cold HDD (sequential workloads, backups)
# Instance store — local NVMe, FAST but EPHEMERAL (lost on stop/terminate)

# Snapshot — point-in-time backup to S3
aws ec2 create-snapshot --volume-id vol-abc --description 'before upgrade'

# 6) Security group — stateful firewall (one per instance / role)
aws ec2 create-security-group --group-name web-sg --description 'web tier' --vpc-id vpc-abc

# Allow HTTPS from anywhere, SSH only from your IP
aws ec2 authorize-security-group-ingress --group-id sg-web --protocol tcp --port 443 --cidr 0.0.0.0/0
aws ec2 authorize-security-group-ingress --group-id sg-web --protocol tcp --port 22  --cidr 203.0.113.42/32

# Reference other SGs (preferred over IP ranges inside VPC)
aws ec2 authorize-security-group-ingress --group-id sg-app --protocol tcp --port 5432 --source-group sg-web

# 7) User data — bootstrap script
# userdata.sh
#!/bin/bash
set -euxo pipefail
dnf update -y
dnf install -y nginx
systemctl enable --now nginx
echo 'Hello from $(hostname)' > /usr/share/nginx/html/index.html

# 8) IAM role — give the instance permissions WITHOUT keys
aws iam create-role --role-name ec2-app-role --assume-role-policy-document '{
    "Version":"2012-10-17",
    "Statement":[{
        "Effect":"Allow",
        "Principal":{"Service":"ec2.amazonaws.com"},
        "Action":"sts:AssumeRole"
    }]
}'
aws iam attach-role-policy --role-name ec2-app-role --policy-arn arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore
aws iam create-instance-profile --instance-profile-name ec2-app-role
aws iam add-role-to-instance-profile --instance-profile-name ec2-app-role --role-name ec2-app-role

# Code inside the instance uses the SDK's default credential chain — picks up role automatically.

# 9) Lifecycle
aws ec2 stop-instances --instance-ids i-abc      # stops (no compute charge; EBS still costs)
aws ec2 start-instances --instance-ids i-abc
aws ec2 reboot-instances --instance-ids i-abc
aws ec2 terminate-instances --instance-ids i-abc # delete

# 10) Cost levers
# On-Demand      — pay per second
# Reserved Instances / Savings Plans — 1 or 3 year commit; up to 72% off
# Spot Instances — bid for spare capacity; ~70% off; interruptible
# Auto Scaling Group — scale based on metrics; pay only for what you use

# Spot — for stateless, fault-tolerant workloads (rendering, batch, CI)
aws ec2 run-instances --instance-market-options 'MarketType=spot,SpotOptions={MaxPrice=0.04}' ...

# 11) Auto Scaling Group + Launch Template
# Maintain N healthy instances, replace failed ones
aws ec2 create-launch-template --launch-template-name web-template --launch-template-data file://template.json
aws autoscaling create-auto-scaling-group \
    --auto-scaling-group-name web-asg \
    --launch-template LaunchTemplateName=web-template,Version='$Latest' \
    --min-size 2 --max-size 10 --desired-capacity 3 \
    --vpc-zone-identifier 'subnet-1,subnet-2,subnet-3' \
    --target-group-arns arn:aws:elasticloadbalancing:...

# 12) Load balancer in front
# Application Load Balancer (ALB) — HTTP/HTTPS, path/host routing, WAF integration
# Network Load Balancer (NLB)    — TCP/UDP, ultra-low latency, static IP
# AutoScaling registers instances with the ALB target group automatically.

# 13) Observability
# CloudWatch Agent on instance → CPU, memory, disk metrics + custom app metrics
# /var/log/messages → CloudWatch Logs via the agent
# CloudTrail → every API call (audit)
# AWS Systems Manager Inventory → installed packages, OS info

# 14) When to use EC2 vs alternatives
# EC2          — full control, any OS, legacy software, custom kernels
# ECS/Fargate  — containers without managing instances
# EKS          — managed Kubernetes
# Lambda       — short-lived event-driven code
# Lightsail    — small VMs with simpler pricing (dev/test, side projects)

# 15) Best practices
#   • Use IMDSv2 (default on new AMIs) — protects against SSRF metadata service abuse
#   • IAM role over access keys — always
#   • SSM Session Manager over SSH (no public port 22, audit logged)
#   • Tag everything (Name, Env, Team, CostCenter) — billing depends on tags
#   • Encrypt EBS volumes (default-on at the account level)
#   • Patches — AWS Systems Manager Patch Manager for scheduled updates
#   • Backups — automated EBS snapshots via Data Lifecycle Manager

Why it matters

Use SSM Session Manager + IAM roles + IMDSv2 + ASG instead of SSH + access keys + manual launches. EC2 is the building block; the layered managed services are usually a better starting point.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
# Virtual machines. SSH in, install software, run apps.
aws ec2 describe-instances
Try it Yourself »

Exercise

List your EC2 instances.

aws ec2

Test yourself

Q1. EC2 provides…
Q2. For burstable cheap instances pick…
Q3. You SSH into a Linux EC2 using…

Discussion

Loading…