# EC2: your first server in the cloud

Launch a real server in the console step by step: pick an AMI and instance type, a key pair and a firewall, bootstrap it with user data, SSH in, then terminate it so it stops costing money.

Course: [AWS for DevOps](https://devops.rajeev.pro/courses/aws), lesson 3. About 40 minutes, intermediate. Source: https://devops.rajeev.pro/courses/aws/03-ec2

## What you will learn

- Choose an AMI and an instance type, and read what the type costs
- Launch an instance in the console with a key pair, a security group and user data
- Allow SSH only from your own IP, and know why 0.0.0.0/0 on port 22 is a bad idea
- Connect with SSH or Session Manager, and read instance metadata with IMDSv2
- Pick a purchasing option (On-Demand, Spot, Savings Plans) and terminate what you don't need

## What you're building

Before cloud consoles, getting a Linux server meant choosing hardware, installing an operating system and
configuring remote access before an app could serve its first page. A cloud instance is faster to create, but
the wizard still asks for choices that affect access, storage and cost. One open SSH rule can expose a server;
one forgotten instance can keep billing.

An EC2 instance is a virtual server assembled from an Amazon Machine Image, an instance type, network rules
and storage. AWS places it on its infrastructure; you configure and operate the guest operating system.
This lesson creates one small Linux server in Mumbai (`ap-south-1`), serves a page, connects only from a
restricted source, and then removes the practice resources. The red numbered boxes show the console steps.
You'll also inspect metadata and estimate which parts of the setup can cost money.

Open **EC2 → Instances → Launch instances**. It's one long page; work down it.

## Name and AMI

> **Figure.** Launch an instance page. (1) Name: academy-web. (2) Amazon Machine Image: Quick Start tiles for Amazon Linux (selected), macOS, Ubuntu, Windows, Red Hat, SUSE and Debian, with Amazon Linux 2023 kernel-6.18 AMI chosen. The summary on the right shows the AMI, t3.micro, a new security group and one 8 GiB volume.
>
> (1) A name, which becomes the instance's Name tag. (2) The AMI: Amazon Linux 2023, free tier eligible.

An **AMI** (Amazon Machine Image) is the disk the server boots from: an operating system plus anything already
installed. Amazon Linux 2023 is AWS's own distribution, tuned for EC2 and using `dnf`. Ubuntu and Debian work
the same way; their default user is `ubuntu` or `admin` instead of `ec2-user`. Teams often build their own AMI
with the app preinstalled so new servers start in seconds.

## Instance type

> **Figure.** Instance type section: t3.micro, family t3, 2 vCPU, 1 GiB memory, with On-Demand prices per hour for Linux, SUSE, Windows, Ubuntu Pro and RHEL. Below, the Key pair section with academy-key selected and a Create new key pair link.
>
> (1) t3.micro: 2 vCPU, 1 GiB, with its hourly price per OS. (2) The key pair you'll log in with.

The name says what you get: `t3.micro` is **family** t, **generation** 3, **size** micro.

| Family                  | For                                                | Example                 |
| ----------------------- | -------------------------------------------------- | ----------------------- |
| **t** (burstable)       | small or spiky workloads: dev servers, small sites | `t3.micro`, `t4g.small` |
| **m** (general purpose) | balanced apps and APIs                             | `m7i.large`             |
| **c** (compute)         | CPU-heavy work: builds, encoding                   | `c7i.xlarge`            |
| **r** (memory)          | databases, caches                                  | `r7i.large`             |
| **i**, **d** (storage)  | fast local disks                                   | `i4i.large`             |

**Burstable** t-types earn CPU credits while idle and spend them in bursts. A t-instance busy all day runs out
and either slows down or, in the default _unlimited_ mode, costs extra. A **g** in the name (`t4g`, `m7g`) means
**Graviton**, AWS's Arm processor: usually cheaper for the same work, if your software has an Arm build.

## Key pair

> **Figure.** The key pair dropdown open, with Proceed without a key pair (Not recommended), another existing key (blurred) and academy-key, type ed25519.
>
> Choose a key pair you hold the private half of, or create one. AWS keeps only the public half.

A **key pair** is an SSH key: AWS puts the public key on the server and you keep the private `.pem` file.
**Create new key pair** downloads it exactly once; lose it and you can't log in with it again. From the CLI:

```sh
$ aws ec2 create-key-pair --key-name academy-key --key-type ed25519 \
    --query KeyMaterial --output text > academy-key.pem
$ chmod 400 academy-key.pem
```

## Firewall: the security group

> **Figure.** Network settings: default VPC and subnet, auto-assign public IP enabled. (1) Create security group selected. (2) Allow SSH traffic from: My IP, with the IP blurred. (3) Allow HTTP traffic from the internet ticked; HTTPS unticked.
>
> (1) A new security group. (2) SSH only from My IP. (3) HTTP from anywhere, for the web page.

A **security group** is a firewall around the instance. It's **stateful**: allow a request in and its reply is
allowed out automatically. By default nothing comes in and everything goes out. The wizard writes these
rules for you:

| Port      | Source        | Why                             |
| --------- | ------------- | ------------------------------- |
| 22 (SSH)  | your IP `/32` | only you can even try to log in |
| 80 (HTTP) | `0.0.0.0/0`   | the web page is public          |

> **Never 0.0.0.0/0 on port 22.** The wizard's default for SSH is **Anywhere**. Bots scan every public IP for port 22 within minutes. Restrict it to your IP, and when your home IP changes, update the rule. Better: open no SSH port and use Session Manager.

## Storage and user data

> **Figure.** Configure storage: 1 volume of 8 GiB gp3, root volume, 3000 IOPS, not encrypted, with an Add new volume button.
>
> The root disk: an 8 GiB gp3 EBS volume.

The root disk is an **EBS volume**: network storage that survives a stop and start, and is deleted on terminate
by default. Some types also have an **instance store**: fast local disks that are wiped when the instance
stops. Never keep data there that you can't lose. Lesson 7 covers storage in depth.

Under **Advanced details**, the last field is **User data**: a script that runs once, as root, on first boot:

> **Figure.** Advanced details, User data field containing a bash script: install nginx with dnf, write a Hello from hostname page to /usr/share/nginx/html/index.html, and enable and start nginx. Above it, metadata settings show IMDSv2 token required.
>
> The user data script installs and starts nginx with a page showing the server's hostname.

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

Its output goes to `/var/log/cloud-init-output.log` on the instance: look there first when a server comes up
without your software.

## Launch

> **Figure.** The Summary panel at the right: Amazon Linux 2023 AMI, t3.micro, new security group, one 8 GiB volume, and the Launch instance button highlighted.
>
> Check the summary, then Launch instance.

> **Figure.** Green success banner: Successfully initiated launch of instance i-0fc778d720d76ed3c, with next steps below.
>
> Launched. The instance ID starts with i-.

> **Figure.** Instances list with academy-web, state Running, type t3.micro, status checks, Availability Zone and public IP.
>
> (1) academy-web. (2) Running. Status checks take a minute or two to pass.

> **Video.** [Getting Started with EC2](https://www.youtube.com/watch?v=nJ-djerESW0) (AWS Developers)

## What you just made

> **Figure.** Instance summary for academy-web: instance ID, public IPv4 address 65.0.6.35, private IPv4 172.31.14.88, state Running, public DNS, instance type t3.micro, VPC and subnet IDs, IAM role none, IMDSv2 Required. The Connect button is highlighted.
>
> (1) The public IPv4 address. (2) Connect shows every way in.

The instance has a **private IP** inside the VPC (lesson 4) and a **public IP** from AWS's pool. The public IP
changes every time the instance stops and starts. An **Elastic IP** is a public address you keep, but AWS
charges for every public IPv4 address, so release the ones you don't use.

> **Figure.** The instance academy-web, a t3.micro, in the middle. Around it: the AMI, Amazon Linux 2023, the image it boots from; the instance type t3.micro, 2 vCPUs and 1 GiB of memory; the key pair academy-key, whose public half is on the server and private half on your laptop; the security group, allowing SSH on port 22 only from your IP and HTTP on port 80; the EBS root volume, an 8 GiB gp3 disk; user data, a script that installs nginx on first boot; and a public IP address. Stopping or terminating the instance does not delete the key pair or the security group.
>
> The instance plus six separate parts. Terminating it deletes the root volume, not the key pair or security group.

## Connect

> **Figure.** Connect to Linux instance, In web browser tab: EC2 Instance Connect (selected), EC2 Instance Connect Endpoint, SSM Session Manager (Maximum security, IAM authentication) and EC2 Serial Console. The In SSH client tab is highlighted.
>
> (1) Instance Connect: SSH from the browser. (2) Session Manager: no open ports at all. (3) In SSH client, for your own terminal.

> **Figure.** In SSH client tab: key pair academy-key, public DNS, username ec2-user, then How to connect steps: (1) chmod 400 academy-key.pem and (2) ssh -i academy-key.pem ec2-user at the public DNS name.
>
> (1) Lock down the key file. (2) The exact SSH command for this instance.

**Session Manager** (part of AWS Systems Manager) opens a shell through the SSM agent and IAM, with no port 22,
no key and every session logged. It needs the instance to have a role with `AmazonSSMManagedInstanceCore`
(lesson 2's instance profile). For production it's the better default.

## Inside the server

> **Figure.** Terminal: ssh -i academy-key.pem to the instance. whoami prints ec2-user. systemctl is-active nginx prints active. A PUT to 169.254.169.254 gets an IMDSv2 token; a request with the token returns t3.micro; the same request without a token returns HTTP 401. df shows an 8 GiB root disk, 1.7 GiB used. Finally curl from the laptop returns Hello from ip-172-31-14-88.ap-south-1.compute.internal.
>
> A real session: nginx is running, IMDSv2 needs a token, and the page answers from the internet.

`169.254.169.254` is the **instance metadata service**: the instance asks it who it is, what type it is, and
for its role's temporary credentials. With **IMDSv2** (required on this instance, as the details page showed)
every request needs a token from a `PUT` first, so a request without one gets **HTTP 401**. That stops attacks
that trick an app into fetching a URL and leaking the credentials.

> **Figure.** A browser at the instance's public IP showing Hello from ip-172-31-14-88.ap-south-1.compute.internal.
>
> The page user data created, served by nginx from the instance.

## What it costs

An EC2 instance is billed while it is in a billable running state, but the instance is only one part of the
total. Public IPv4 addresses, attached storage, snapshots and data transfer may also add charges. The table
below compares purchase options for compute; it does not include those attached resources.

Estimate the full workload in AWS Pricing Calculator before launching it. Check the Region, operating system,
instance size, expected hours and storage. Stop an instance when you do not need its compute capacity, but
remember that stopping does not delete its EBS volumes or snapshots. For a short practice exercise, terminate
the instance and remove the resources you created. A common mistake is to read the hourly instance price as
the complete monthly bill.

The instance type page showed the price: about **$0.0112 an hour** for a Linux t3.micro in Mumbai, around
$8 a month if left on. Free tier offers depend on when your account was created; check **Billing → Free Tier**
before relying on them.

| Option                 | Pay                                                              | Good for                                          |
| ---------------------- | ---------------------------------------------------------------- | ------------------------------------------------- |
| **On-Demand**          | per second, no commitment                                        | testing, unpredictable load                       |
| **Spot**               | up to 90% less, but AWS can take it back with a 2-minute warning | batch jobs, CI runners, anything that can restart |
| **Savings Plans**      | lower rate for committing to $/hour for 1 or 3 years             | steady production load                            |
| **Reserved Instances** | discount for committing to one instance type                     | older alternative to Savings Plans                |

## Clean up

**Instance state → Terminate (delete) instance:**

> **Figure.** The Instance state menu open: Stop instance, Start instance, Reboot instance, Hibernate instance and Terminate (delete) instance, with Stop and Terminate highlighted.
>
> (1) Stop keeps the disk; you still pay for EBS. (2) Terminate deletes the instance.

> **Figure.** Terminate (delete) instance dialog: a warning that the root EBS volume is deleted on termination, the instance ID with termination protection Disabled, a Skip OS shutdown option, and the Terminate (delete) button.
>
> Terminating can't be undone. Turn on termination protection for servers you must not lose.

A terminated instance leaves its security group and key pair behind; delete those too:

```sh
$ aws ec2 terminate-instances --instance-ids i-0fc778d720d76ed3c
$ aws ec2 wait instance-terminated --instance-ids i-0fc778d720d76ed3c
$ aws ec2 delete-security-group --group-id sg-01ff1639efcb487b9
$ aws ec2 delete-key-pair --key-name academy-key
```

> **In production.** Nobody clicks through this wizard for production. Servers come from a launch template or Terraform (lesson 16), run in private subnets behind a load balancer (lessons 4 and 5), get an IAM role instead of keys, are reached through Session Manager, and are replaced rather than patched by hand.

## Mission: A web server from one command

Launch the same server from the CLI: a key pair, a security group with SSH from your IP and HTTP from anywhere, and a t3.micro running Amazon Linux 2023 with the nginx user data. Prove the page answers and that IMDSv2 rejects a request without a token, then delete everything.

- You need: An AWS account and the AWS CLI configured for ap-south-1
- You'll have: curl showing Hello from the instance, HTTP 401 without a metadata token, then no instance, security group or key pair left

```sh
$ MYIP=$(curl -s https://checkip.amazonaws.com)
$ 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 academy-key --key-type ed25519 --query KeyMaterial --output text > academy-key.pem && chmod 400 academy-key.pem
$ SG=$(aws ec2 create-security-group --group-name academy-web --description "SSH from me, HTTP from all" --query GroupId --output text)
$ aws ec2 authorize-security-group-ingress --group-id $SG --protocol tcp --port 22 --cidr $MYIP/32
$ aws ec2 authorize-security-group-ingress --group-id $SG --protocol tcp --port 80 --cidr 0.0.0.0/0
$ printf '#!/bin/bash\ndnf install -y nginx\necho "<h1>Hello from $(hostname)</h1>" > /usr/share/nginx/html/index.html\nsystemctl enable --now nginx\n' > user-data.sh
$ ID=$(aws ec2 run-instances --image-id $AMI --instance-type t3.micro --key-name academy-key --security-group-ids $SG \
    --user-data file://user-data.sh --metadata-options HttpTokens=required \
    --tag-specifications 'ResourceType=instance,Tags=[{Key=Name,Value=academy-web}]' --query 'Instances[0].InstanceId' --output text)
$ aws ec2 wait instance-status-ok --instance-ids $ID
$ IP=$(aws ec2 describe-instances --instance-ids $ID --query 'Reservations[0].Instances[0].PublicIpAddress' --output text)
$ curl -s http://$IP
$ ssh -o StrictHostKeyChecking=accept-new -i academy-key.pem ec2-user@$IP 'curl -s -o /dev/null -w "%{http_code}\n" http://169.254.169.254/latest/meta-data/instance-type'
401
$ aws ec2 terminate-instances --instance-ids $ID && aws ec2 wait instance-terminated --instance-ids $ID
$ aws ec2 delete-security-group --group-id $SG && aws ec2 delete-key-pair --key-name academy-key && rm academy-key.pem
```

`instance-status-ok` waits until both status checks pass, which can take a few minutes. The whole mission costs
a cent or two at On-Demand prices, nothing within the free tier.

## Try it

- Launch a t3.micro with Amazon Linux 2023 and the user data script from this lesson.
- Open the instance's public IP in a browser and find the hostname in the page.
- SSH in and read the instance type from the metadata service with an IMDSv2 token.
- Try the same metadata request without a token and note the HTTP status.
- Look at the security group: which source is allowed on port 22?
- Terminate the instance, then delete its security group and key pair.

## Quiz

1. What is an AMI?
   - The size of the server
   - **The template the instance boots from: an operating system image plus any preinstalled software** (answer)
   - The firewall
   - The billing plan
   Why: Amazon Linux 2023, Ubuntu and Windows are AMIs. You can also build your own with your app already installed.

2. Why set the SSH rule's source to My IP instead of Anywhere (0.0.0.0/0)?
   - It is faster
   - **Port 22 open to the whole internet gets password and key-guessing attempts within minutes; My IP lets only you try** (answer)
   - AWS requires it
   Why: Better still, open no port at all and connect with Session Manager.

3. What runs the user data script?
   - You, after logging in
   - **cloud-init, once, as root, on the instance's first boot** (answer)
   - AWS Lambda
   Why: That's how the instance installed and started nginx before anyone logged in.

4. A request to 169.254.169.254 without a token returns HTTP 401. Why?
   - The metadata service is down
   - **The instance requires IMDSv2, so requests need a session token from a PUT first** (answer)
   - The instance has no IAM role
   Why: IMDSv2 blocks a whole class of attacks where a vulnerable app is tricked into fetching credentials from the metadata service.

5. What is the difference between stopping and terminating an instance?
   - None
   - **Stop shuts it down and keeps the disk (you still pay for EBS); terminate deletes the instance and, by default, its root volume** (answer)
   - Terminate can be undone for 24 hours
   Why: The terminate dialog says so, and it cannot be undone. Turn on termination protection for servers you must not lose.

## Resources

- [Amazon EC2 user guide](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/concepts.html) (AWS Docs)
- [Amazon EC2 instance types](https://aws.amazon.com/ec2/instance-types/) (AWS)
- [Use IMDSv2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/configuring-IMDS-existing-instances.html) (AWS Docs)
- [Run commands when you launch an instance (user data)](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/user-data.html) (AWS Docs)
- [AWS Systems Manager Session Manager](https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager.html) (AWS Docs)
