Skip to Content

EC2: Instances, AMIs, Security Groups

When to use

Launch a virtual server with full OS / runtime control.

Analogy

EC2 is renting a private office. AMI is the office furniture and layout. Security Group is the receptionist. Subnet is the floor.

Data-flow diagram

  AMI (image) + Instance Type (size)
       + Key Pair (SSH) + Security Group (firewall)
       + User Data (boot script)
              v
        EC2 Instance
        - EBS (root volume)
        - ENI (in Subnet)
        - Private / Public IP

Deep explanation

Amazon EC2 provides resizable virtual servers. Pick an AMI (Amazon Linux 2023, Ubuntu 22.04, Windows Server, or your own), an Instance Type (CPU/RAM/network shape), a Key Pair for SSH, a Security Group (stateful virtual firewall), optional User Data (a cloud-init shell script). Security Groups default-deny inbound; you add ‘allow’ rules by port + source (CIDR or another SG).

Examples

Example 1

aws ec2 run-instances \
  --image-id ami-0abcdef1234567890 \
  --instance-type t3.small \
  --key-name my-key \
  --security-group-ids sg-0123abcdef \
  --user-data file://setup.sh

launches a t3.small with this AMI; user-data runs at boot via cloud-init.

Example 2

aws ec2 authorize-security-group-ingress \
  --group-id sg-0123abcdef \
  --protocol tcp --port 22 --cidr 203.0.113.0/24

opens SSH from a single corporate CIDR. NEVER 0.0.0.0/0 on 22.

Example 3

aws ec2 create-image --instance-id i-0123 \
  --name 'myapp-baseline-2024-01-15' \
  --description 'post-patching baseline'

snapshots the running instance as an AMI you can re-launch.

Common mistake

0.0.0.0/0 on port 22 plus a weak password - script kiddies own it in hours. Also forgetting SGs are stateful (response traffic auto-allowed inbound) while NACLs are stateless.

Key takeaway

Restrict SG ingress to specific CIDRs; use SSM Session Manager instead of SSH; put stateful instances in private subnets with a NAT Gateway for egress.

Production Failure Playbook

Failure scenario 1: open-ssh-to-the-world

Failure scenario 2: instance-store-reboots-clean