TExcelTAD
Home › AWS Cloud › Amazon EC2

Amazon EC2

Amazon Elastic Compute Cloud (EC2) rents you virtual servers called instances. You choose the hardware size, the operating system and the network; AWS runs it on its physical hosts. EC2 is the classic IaaS service and the foundation many other AWS services are built on.

The parts of an instance

Part What it is
AMI (Amazon Machine Image) The template: OS + preinstalled software (Amazon Linux, Ubuntu, Windows, your own image)
Instance type The hardware size: vCPUs, memory, network (e.g. t3.micro, m7g.large)
Key pair SSH key for logging in to Linux instances (or use Session Manager with no key at all)
Security group A stateful firewall around the instance
Storage EBS volumes (network disks) and sometimes instance store (local, temporary disks)
Network The VPC and subnet it lives in, private and optional public IP
IAM role Permissions for software on the instance (via an instance profile)
User data A script that runs at first boot

Launching an instance

bash
aws ec2 run-instances \
    --image-id ami-0abcdef1234567890 \
    --instance-type t3.micro \
    --key-name ada-key \
    --security-group-ids sg-0123456789abcdef0 \
    --subnet-id subnet-0aa11bb22cc33dd44 \
    --user-data file://install-web.sh \
    --tag-specifications 'ResourceType=instance,Tags=[{Key=Name,Value=web-1}]' \
    --query "Instances[0].[InstanceId,State.Name,PrivateIpAddress]"

Sample output:

text
[
    "i-0f1e2d3c4b5a69788",
    "pending",
    "10.0.1.27"
]

A typical user data script installs a web server at first boot:

bash
#!/bin/bash
dnf install -y nginx
echo "<h1>Hello from $(hostname)</h1>" > /usr/share/nginx/html/index.html
systemctl enable --now nginx

The instance lifecycle

An instance moves through states. Only some transitions are possible, and billing depends on the state: you pay for compute while it is running, and for attached EBS volumes in every state until they are deleted.

python · try it yourself
TRANSITIONS = {
    "pending":       {"boot finished": "running"},
    "running":       {"stop": "stopping", "reboot": "running", "terminate": "shutting-down"},
    "stopping":      {"stopped": "stopped"},
    "stopped":       {"start": "pending", "terminate": "shutting-down"},
    "shutting-down": {"gone": "terminated"},
    "terminated":    {},
}
BILLED_COMPUTE = {"running"}

def run(events, state="pending"):
    for ev in events:
        nxt = TRANSITIONS[state].get(ev)
        if nxt is None:
            print(f"  {state:<13} --{ev}--> rejected (IncorrectInstanceState)")
            continue
        print(f"  {state:<13} --{ev}--> {nxt:<13} compute billed: {nxt in BILLED_COMPUTE}")
        state = nxt
    return state

final = run(["boot finished", "stop", "stopped", "reboot", "start", "boot finished",
             "terminate", "gone", "start"])
print("final state:", final)
  pending       --boot finished--> running       compute billed: True
  running       --stop--> stopping      compute billed: False
  stopping      --stopped--> stopped       compute billed: False
  stopped       --reboot--> rejected (IncorrectInstanceState)
  stopped       --start--> pending       compute billed: False
  pending       --boot finished--> running       compute billed: True
  running       --terminate--> shutting-down compute billed: False
  shutting-down --gone--> terminated    compute billed: False
  terminated    --start--> rejected (IncorrectInstanceState)
final state: terminated

Note: Stop keeps the instance and its EBS root volume (you can start it again later, usually on a different host and with a new public IP). Terminate deletes it; by default the root volume is deleted too.

Model: billing per second

Linux instances are billed per second with a one-minute minimum; some other operating systems are billed per hour. With an example price of $0.0416 per hour:

python · try it yourself
import math

price_per_hour = 0.0416   # example on-demand price

def cost_per_second(seconds):
    billed = max(seconds, 60)               # one-minute minimum
    return billed * price_per_hour / 3600

def cost_per_hour(seconds):
    return math.ceil(seconds / 3600) * price_per_hour

for seconds in (30, 600, 3_601, 8 * 3600):
    print(f"{seconds:>6} s: per-second ${cost_per_second(seconds):.4f}"
          f"   per-hour ${cost_per_hour(seconds):.4f}")
    30 s: per-second $0.0007   per-hour $0.0416
   600 s: per-second $0.0069   per-hour $0.0416
  3601 s: per-second $0.0416   per-hour $0.0832
 28800 s: per-second $0.3328   per-hour $0.3328

Per-second billing makes short jobs (tests, batch work) cheap: you don't pay for a whole hour when a job runs for ten minutes.

Connecting to an instance

  • SSH with your key pair: ssh -i ada-key.pem ec2-user@<public-ip> (port 22 must be open in the security group).
  • EC2 Instance Connect: pushes a short-lived key, works from the console.
  • AWS Systems Manager Session Manager: a shell through the AWS API, no open inbound port and no key pair. This is the most secure option.

Instance metadata

Software on an instance can ask about itself at the link-local address 169.254.169.254 (IMDS). With IMDSv2 a session token is required first:

bash
TOKEN=$(curl -s -X PUT http://169.254.169.254/latest/api/token \
    -H "X-aws-ec2-metadata-token-ttl-seconds: 300")
curl -s -H "X-aws-ec2-metadata-token: $TOKEN" \
    http://169.254.169.254/latest/meta-data/placement/availability-zone

Sample output:

text
eu-west-1b

Go further: Instance Metadata: IMDSv1, IMDSv2 and Hop Limits explains which SSRF bugs can reach instance credentials and how IMDSv2 stops them.

Test yourself

What does an AMI provide?

  1. The hardware size
  2. The template with the operating system and software
  3. The firewall rules
  4. The billing plan

Which action deletes an instance permanently?

  1. Stop
  2. Reboot
  3. Terminate
  4. Hibernate

Which way of connecting needs no open inbound port and no SSH key?

  1. SSH
  2. RDP
  3. Systems Manager Session Manager
  4. FTP