Amazon EC2 Explained: Instance Types, AMIs, Storage, User Data, Key Pairs and Purchasing Options
What Is EC2?
Amazon Elastic Compute Cloud (EC2) gives you virtual servers (instances) in minutes. You choose the CPU, memory, storage, network and operating system, and you pay while the instance runs.
Instance Type Names
text
m7g.xlarge
│││ └── size: nano, micro, small, medium, large, xlarge, 2xlarge ...
││└──── g = Graviton (ARM) processor. i = Intel, a = AMD, d = local NVMe disk, n = faster network
│└───── generation (higher is newer and usually better value)
└────── family: m = general purpose
| Family | Optimized for | Examples | Use for |
| T (burstable) | Low baseline CPU with bursts | t3, t4g | Dev/test, small sites, low-traffic apps |
| M (general purpose) | Balanced CPU and memory | m6i, m7g | Web and app servers, small databases |
| C (compute optimized) | High CPU | c6i, c7g | Batch, gaming, media encoding, HPC |
| R / X / z (memory optimized) | Lots of RAM | r6i, x2idn | In-memory databases, large caches, SAP HANA |
| I / D / H (storage optimized) | Fast local disk, high IOPS | i4i, d3 | NoSQL, data warehouses, log processing |
| P / G / Inf / Trn (accelerated) | GPUs and ML chips | p5, g5, inf2 | Machine learning, graphics |
Tip: Graviton (ARM) instances usually give better price and performance, if your software supports ARM. Use burstable T instances for light, spiky workloads.
AMI: Amazon Machine Image
An AMI is the template used to start an instance: operating system, software and settings. Sources: AWS (Amazon Linux, Windows), AWS Marketplace, community, or your own custom AMI.
- An AMI belongs to a Region. To use it elsewhere, copy it to that Region
- A custom AMI is made from an instance (it creates EBS snapshots). Use it for faster, consistent launches (golden image)
- Use EC2 Image Builder to build and patch AMIs automatically
- Share AMIs with other accounts or the organization by changing permissions
bash
aws ec2 create-image --instance-id i-0abc123 --name web-golden-2026-11 --no-reboot
aws ec2 copy-image --source-image-id ami-0123 --source-region ap-south-1 --region eu-west-1 --name web-golden-2026-11
aws ec2 describe-images --owners self --query 'Images[].[ImageId,Name,CreationDate]' --output table
Launch an Instance (CLI)
bash
# Find the latest Amazon Linux 2023 AMI from the public SSM parameter
AMI=$(aws ssm get-parameter --name /aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64 --query Parameter.Value --output text)
aws ec2 create-key-pair --key-name lab-key --query KeyMaterial --output text > lab-key.pem && chmod 400 lab-key.pem
aws ec2 run-instances \
--image-id $AMI --instance-type t3.micro --key-name lab-key \
--security-group-ids sg-0abc1234 --subnet-id subnet-0abc1234 \
--iam-instance-profile Name=AppS3Read \
--metadata-options HttpTokens=required,HttpEndpoint=enabled \
--user-data file://user-data.sh \
--tag-specifications 'ResourceType=instance,Tags=[{Key=Name,Value=web-1},{Key=Project,Value=learning}]'
aws ec2 describe-instances --filters Name=tag:Name,Values=web-1 --query 'Reservations[].Instances[].[InstanceId,State.Name,PublicIpAddress]' --output table
ssh -i lab-key.pem ec2-user@PUBLIC_IP
User Data: Bootstrap on First Boot
bash
#!/bin/bash
dnf update -y
dnf install -y nginx
systemctl enable --now nginx
echo "Hello from $(hostname -f) in $(curl -s -H "X-aws-ec2-metadata-token: $(curl -s -X PUT http://169.254.169.254/latest/api/token -H 'X-aws-ec2-metadata-token-ttl-seconds: 60')" http://169.254.169.254/latest/meta-data/placement/availability-zone)" > /usr/share/nginx/html/index.html
- User data runs once at first launch, as root, up to 16 KB
- Good for installing packages and starting services. For heavy setup, bake an AMI
- Output is in
/var/log/cloud-init-output.log
Instance Metadata Service (IMDS)
From inside an instance, http://169.254.169.254/latest/meta-data/ returns instance ID, AZ, IAM role credentials and more. Use IMDSv2 (token required, HttpTokens=required) to protect against SSRF attacks.
Key Pairs and Access
- A key pair is a public key stored by AWS and a private key you keep. Linux login uses SSH with the private key. Never share or commit the
.pem file
- Instead of opening port 22, use Systems Manager Session Manager: no inbound ports, no keys, full audit. Attach a role with
AmazonSSMManagedInstanceCore
- EC2 Instance Connect pushes a temporary key for a short time
bash
aws ssm start-session --target i-0abc123 # shell without SSH or open port
Storage for EC2
| Option | Persistence | Notes |
| EBS volume | Persists independently of the instance | Network block storage, in one AZ, snapshots to S3 |
| Instance store | Lost when the instance stops, terminates or hardware fails | Very fast local disk. Buffers, caches, temporary data |
| EFS / FSx | Persistent shared file systems | Mounted over the network by many instances |
IP Addresses
| Type | Behavior |
| Private IPv4 | Fixed inside the VPC for the life of the instance |
| Public IPv4 | Changes if you stop and start the instance. Billed hourly now |
| Elastic IP | A static public IPv4 you own until you release it. Billed, so release unused ones. Max 5 per Region by default |
| IPv6 | Globally unique, no NAT needed |
Placement Groups
| Strategy | What it does | Use for |
| Cluster | Packs instances close in one AZ | Lowest latency and high throughput (HPC) |
| Spread | Puts each instance on separate hardware, max 7 per AZ per group | A few critical instances that must not fail together |
| Partition | Groups on separate racks (partitions) | Large distributed systems: Hadoop, Cassandra, Kafka |
Instance Lifecycle
| State | Billing | Notes |
pending → running | Billed per second (min 60 s) for Linux | Instance is active |
stopping → stopped | Not billed for compute, but EBS volumes and Elastic IPs still cost | Keeps EBS data and private IP |
hibernate | RAM saved to EBS, quick resume | Needs an encrypted root volume and enough space |
terminated | Not billed. Instance and (by default) root volume deleted | Cannot be restarted |
Purchasing Options
| Option | How it works | Savings | Best for |
| On-Demand | Pay per second, no commitment | None (baseline) | Short, unpredictable, first-time workloads |
| Savings Plans | Commit to dollars per hour for 1 or 3 years. Compute SP is flexible across instance family, Region and Lambda/Fargate. EC2 Instance SP is tied to a family and Region | Up to about 72 percent | Steady usage with some flexibility |
| Reserved Instances | Commit to a specific instance configuration for 1 or 3 years. Convertible RIs can change attributes | Up to about 72 percent (up to about 66 percent for Convertible) | Steady, known workloads |
| Spot Instances | Use spare capacity at a big discount. AWS can reclaim with a 2-minute notice | Up to about 90 percent | Fault-tolerant, stateless, batch, CI, big data |
| Dedicated Hosts | A whole physical server for you. Visibility of sockets and cores | Varies | Per-core or per-socket software licenses, compliance |
| Dedicated Instances | Instances on hardware not shared with other accounts | — | Isolation without host control |
| Capacity Reservations | Reserve capacity in an AZ (no discount by itself) | None (combine with SP) | Guarantee that capacity exists, for example for events or DR |
Percentages are approximate Discounts depend on instance type, Region and term. Use the pricing pages and Cost Explorer recommendations for real numbers.
Spot Instance Practices
- Design apps to be stateless or checkpoint often
- Use Auto Scaling groups with mixed instances and a diversified list of types and AZs
- Handle the interruption notice (2 minutes) through instance metadata or EventBridge
- Use for CI workers, batch, rendering, analytics clusters (EMR), containers worker nodes
EC2 Security Basics
- Attach an IAM role instead of keys
- Control traffic with security groups (you will learn them in the VPC lesson)
- Use IMDSv2 only
- Patch with Systems Manager Patch Manager
- Turn on EBS encryption
- Use Inspector for vulnerability scans
Practice Tasks
- Launch a
t3.micro with a user data script that installs a web server and open it in a browser
- Connect with Session Manager instead of SSH
- Create an AMI from your configured instance and launch a second instance from it
- Compare the hourly price of
m7g.large and m6i.large in your Region
- Stop the instance, then start it, and note which IP changed
Conclusion
EC2 gives virtual servers from an AMI with a chosen instance type, user data bootstrap, IAM role and security group. Use Session Manager and IMDSv2 for safe access, EBS for persistent disks, and combine On-Demand with Savings Plans for steady load and Spot for fault-tolerant work.
Quick Summary: instance families + naming; AMI copy/share; run-instances CLI + user data; IMDSv2; Session Manager; EBS vs instance store; Elastic IP; placement groups; lifecycle billing; purchasing options table.