Hands-on AWS knowledge base for developers Managed Ops
Talk to Us

How to Launch an EC2 Instance Step by Step (CLI + Console)

Export PDF Print-friendly layout with a copyright watermark; choose Save as PDF in the print dialog
How to Launch an EC2 Instance Step by Step (CLI + Console)

TL;DR

  • Launching an EC2 instance is four objects: an AMI, an instance type + subnet, a key pair, and a security group. Get the security group and subnet route wrong and everything else is wasted effort.
  • The CLI path (aws ec2 run-instances + aws ec2 wait instance-running) is faster and repeatable than clicking through the console, and gives you the exact command to re-run next time.
  • Verify in three layers: instance state → both status checks passing → actual SSH/HTTP reachability. “Running” in the console only means the hypervisor booted it, not that your app works.

Prerequisites: what you actually need before step 1

You need an AWS account with permission to create EC2 resources, a default VPC (most accounts have one), and AWS CLI v2 configured.

aws --version
aws sts get-caller-identity   # confirm you are in the right account
aws configure list            # confirm region; EC2 is regional


Set a default region explicitly so you don't launch in `us-east-1` by accident:

```bash
export AWS_REGION=ap-southeast-1


Pricing varies by region and instance type, so pick the region where your users (or your other services) live. Cross-region latency between your EC2 box and an RDS instance in another region will hurt later.

## Step-by-step: launch an instance from the CLI

**1. Create a key pair** (skip if you already have one in this region):

```bash
aws ec2 create-key-pair --key-name awsgood-demo 
  --query 'KeyMaterial' --output text > awsgood-demo.pem
chmod 400 awsgood-demo.pem


**2. Find the latest Amazon Linux 2023 AMI** — never hardcode an AMI ID, they rotate:

```bash
AMI_ID=$(aws ec2 describe-images --owners amazon 
  --filters "Name=name,Values=al2023-ami-2023.*-x86_64" "Name=state,Values=available" 
  --query 'sort_by(Images,&CreationDate)[-1].ImageId' --output text)
echo $AMI_ID


**3. Create a security group and open only what you need.** Lock SSH to your own IP:

```bash
VPC_ID=$(aws ec2 describe-vpcs --filters Name=is-default,Values=true 
  --query 'Vpcs[0].VpcId' --output text)

SG_ID=$(aws ec2 create-security-group --group-name awsgood-web 
  --description "ssh from office, http public" --vpc-id $VPC_ID 
  --query 'GroupId' --output text)

MY_IP=$(curl -s https://checkip.amazonaws.com)
aws ec2 authorize-security-group-ingress --group-id $SG_ID 
  --protocol tcp --port 22 --cidr ${MY_IP}/32
aws ec2 authorize-security-group-ingress --group-id $SG_ID 
  --protocol tcp --port 80 --cidr 0.0.0.0/0


**4. Write a user-data script** so the instance boots ready to serve:

```bash
cat > user-data.sh <<'EOF'
#!/bin/bash
set -euxo pipefail
dnf update -y
dnf install -y httpd
systemctl enable --now httpd
echo "hello from $(hostname -f)" > /var/www/html/index.html
EOF


**5. Launch it**, enforcing IMDSv2-only metadata access:

```bash
INSTANCE_ID=$(aws ec2 run-instances 
  --image-id $AMI_ID 
  --instance-type t3.micro 
  --key-name awsgood-demo 
  --security-group-ids $SG_ID 
  --count 1 
  --metadata-options HttpTokens=required,HttpEndpoint=enabled 
  --block-device-mappings 'DeviceName=/dev/xvda,Ebs={VolumeSize=16,VolumeType=gp3,Encrypted=true,DeleteOnTermination=true}' 
  --tag-specifications 'ResourceType=instance,Tags=[{Key=Name,Value=awsgood-demo},{Key=Env,Value=dev}]' 
  --user-data file://user-data.sh 
  --query 'Instances[0].InstanceId' --output text)
echo $INSTANCE_ID


**6. Wait for running state, then grab the public IP:**

```bash
aws ec2 wait instance-running --instance-ids $INSTANCE_ID
PUBLIC_IP=$(aws ec2 describe-instances --instance-ids $INSTANCE_ID 
  --query 'Reservations[0].Instances[0].PublicIpAddress' --output text)
echo $PUBLIC_IP


Console equivalent: EC2 → Launch instance → same four choices (AMI, type, key pair, network settings) → Advanced details → paste user data → Launch. The CLI just makes it repeatable.

## Key parameters and recommended values

| Parameter | Meaning | Recommended for SMB / dev |
|---|---|---|
| AMI | Base image with OS + boot volume | Latest Amazon Linux 2023 or Ubuntu LTS; resolve dynamically |
| Instance type | vCPU/RAM/network envelope | `t3.micro` / `t3.small` for web + cron; `t4g` if ARM is fine (cheaper) |
| Key pair | SSH public key injected at first boot | One key per environment; rotate, don't share |
| Subnet | Where the ENI lives; determines routing | Public subnet (route `0.0.0.0/0` → IGW) if it needs inbound internet |
| Security group | Stateful virtual firewall | Deny by default; SSH from your IP `/32` only |
| User data | Bootstrap script, runs once on first boot | Install + configure app; log to `/var/log/cloud-init-output.log` |
| EBS volume | Persistent block storage | `gp3`, encrypted, `DeleteOnTermination=true` for throwaways |
| IMDS options | Instance metadata service auth | `HttpTokens=required` (IMDSv2 only) |
| Tags | Billing/lifecycle metadata | At minimum `Name`, `Env`, `Owner` |
| Purchase option | On-Demand / Spot / RI / Savings Plan | On-Demand to start; Savings Plan once usage is steady |

## How to verify the instance actually works

Don't trust the console's green dot. Check status checks, which reflect the hypervisor and the guest OS:

```bash
aws ec2 describe-instance-status --instance-ids $INSTANCE_ID --include-all-instances 
  --query 'InstanceStatuses[0].[InstanceState.Name,InstanceStatus.Status,SystemStatus.Status]' 
  --output table


Both `ok` means the kernel booted and networking responds. Then test the real thing:

```bash
ssh -i awsgood-demo.pem ec2-user@$PUBLIC_IP 'systemctl is-active httpd; cat /var/log/cloud-init-output.log | tail -n 20'
curl -s http://$PUBLIC_IP/


If user data failed, the cloud-init log is the only place that says why. `aws ec2 get-console-output --instance-id $INSTANCE_ID` shows serial console output (useful for boot loops and GRUB errors), but it will not show your script's stderr.

## Security and cost notes

- **Never** open port 22 to `0.0.0.0/0`. If you need browser SSH, use Session Manager with an instance profile instead of exposing SSH at all.
- Enforce IMDSv2 (shown above). IMDSv1 is the standard pivot path for SSRF-style credential theft.
- A **stopped** instance still bills for its EBS volumes and any attached Elastic IP. Terminate dev boxes; stop only what you'll restart.
- `t3`/`t4g` are burstable — CPU credits run out under sustained load and throughput drops. Check `CPUCreditBalance` before blaming the app.
- Tag everything from day one. Cost Explorer filtering by `Env` is the difference between a clean bill and an afternoon of archaeology.
- Pricing varies by region and instance type; compare your actual region in the pricing calculator rather than trusting blog numbers.

## Common pitfalls (and one lesson I learned the hard way)

**The 2am lesson:** an instance launched fine, `describe-instance-status` showed both checks `ok`, but SSH timed out and `curl` hung. My first instinct — "security group" — was wrong; the SG was correct. The real cause: the console had pre-selected a subnet in a **private** subnet of a non-default VPC, so there was no route to the internet gateway, and the instance had no public IP at all. I verified it in two commands rather than guessing:

```bash
aws ec2 describe-instances --instance-ids $INSTANCE_ID 
  --query 'Reservations[0].Instances[0].SubnetId' --output text
aws ec2 describe-route-tables --filters Name=association.subnet-id,Values=<subnet-id> 
  --query 'RouteTables[0].Routes'


No `0.0.0.0/0 → igw-*` route confirmed it. Fix: launch into a public subnet, or attach a NAT gateway if the box genuinely belongs in private. Since then I always print `SubnetId` and `PublicIpAddress` immediately after launch, and I run Reachability Analyzer when a path "should" work.

Other recurring traps:

- `Permissions 0644 for 'x.pem' are too open` — fix with `chmod 400`.
- Picking an `arm64` AMI with an `x86_64`-only binary (or vice versa) — instant boot failure.
- Editing user data on a running instance and wondering why nothing changed — it only runs on first boot (or after `--force` in a new launch).
- Forgetting that instance store volumes are wiped on stop/start.
- Deleting the key pair from the console does not remove access; the key stays on the instance.

If you'd rather not babysit key pairs, security group drift and cost tags across a handful of accounts, that's the kind of routine work awsgood.com handles for small teams.

Sources

FAQ

How long does it take to launch an EC2 instance step by step?

The API call returns in seconds, but the instance usually takes 30–90 seconds to reach `running` and another 1–3 minutes before both status checks pass. User data that runs `dnf update` or installs packages can add several minutes. Use `aws ec2 wait instance-running` plus a poll on `describe-instance-status` rather than guessing.

Do I need a key pair to launch an EC2 instance?

No. You can launch without one and connect later via EC2 Instance Connect, AWS Systems Manager Session Manager, or by attaching a key pair to the instance (Linux only, via the console or CLI). For production, Session Manager with an IAM instance profile is the safer default because it removes inbound SSH entirely.

Why is my EC2 instance running but I can't connect?

Work through it in order: (1) does the instance have a public IP and is it in a subnet whose route table points `0.0.0.0/0` at an internet gateway; (2) does the security group allow your current IP on the right port — home IPs change; (3) is the OS firewall (firewalld/ufw) blocking it; (4) is the service actually listening (`ss -tlnp`). Check status checks first — if the system status check fails, it's a host-level problem, not your firewall.

Leave a Reply

Your email address will not be published. Required fields are marked *