Launch Your First EC2 Instance with AWS CLI
By the end of this guide you will have a real EC2 instance running on AWS, connected to via SSH, and safely cleaned up. Every command is copy-paste safe and explained before you run it.
This is a CLI-first guide for people new to EC2 or AWS. It covers what EC2 is, why each step exists, and what to watch out for on cost and security. If you prefer the AWS Console, this guide will still help you understand what is happening behind the clicks.
What is EC2?
Amazon EC2 (Elastic Compute Cloud) is AWS’s virtual machine service. When you launch an instance, you are renting a slice of a physical server in an AWS data centre. You get a full operating system, CPU, RAM, and storage, and you pay by the hour while it is running.
Think of launching an EC2 instance like booking a hotel room. You pick the room type (instance type), the building (availability zone), the floor plan layout (AMI), set who can knock on your door (security group), and get a key card (key pair). When you check out (terminate), the room is cleaned and reassigned.
A few terms you will see throughout this guide:
- AMI (Amazon Machine Image): the OS template your instance boots from. Think of it as a pre-made disk snapshot. AMI IDs are region-specific. See the AMIs guide.
- Instance type: determines how much CPU and RAM you get.
t3.microis a small, low-cost option for learning. See EC2 instance types explained. - Security group: a firewall rule set that controls which traffic can reach your instance. See security groups explained.
- Subnet: a partition of a VPC network. Whether the subnet is public or private determines whether the instance gets a routable IP. See subnets in AWS.
- Key pair: a public/private key for SSH access. AWS stores the public key on the instance; you download the private key once and keep it safe.
How launching an EC2 instance works
Before you run any commands, here is the dependency chain. Each step in this guide maps to one of these:
- AMI: pick an OS image. The ID is region-specific.
- Instance type: choose the size (CPU and RAM).
- Network: the instance launches into a VPC and subnet. Most accounts have a default VPC with public subnets already configured.
- Security group: controls what traffic is allowed in and out.
- Access method: either a key pair for SSH, or Session Manager (no key pair needed).
- Launch: AWS provisions the hardware, boots the OS, and assigns an IP address.
- Connect: SSH in (or use Session Manager) once the instance is running.
Nothing in the launch command is magic. You are assembling these pieces and telling AWS exactly what you want.
When to use EC2
EC2 is a strong choice when you need:
- A persistent server that runs continuously
- Full control over the OS, installed packages, or system configuration
- Long-running processes (more than 15 minutes)
- Applications that are difficult to containerise or have unusual system-level requirements
- A learning environment where you want direct shell access to a Linux machine
EC2 is not the best fit for every workload. If your use case is event-driven and short-lived, Lambda or containers are likely cheaper and simpler to operate. See choosing between EC2, Lambda, and containers if you are unsure which to use.
CLI vs Console
Both the AWS CLI and the AWS Management Console can launch EC2 instances. This guide uses the CLI because:
- Commands are reproducible and scriptable
- You see exactly which parameters you are setting
- You can save the commands and repeat them in different environments
The Console is easier for one-off exploration but hides the underlying API calls. Learning the CLI first means the Console will make more sense when you use it later.
Before you start
You will need:
- An AWS account. The AWS account setup guide covers this.
- The AWS CLI installed and configured with credentials. See the AWS CLI guide.
- An IAM user or role with permissions to create EC2 resources: at minimum
ec2:RunInstances,ec2:CreateKeyPair,ec2:CreateSecurityGroup, and related actions. Review the IAM overview if you are unsure. - A terminal (macOS Terminal, Linux bash, or Windows WSL).
AMI IDs, subnet IDs, and other resource IDs are region-specific. Decide which region you will use before you start and set it as your CLI default:
aws configure set region us-east-1Replace us-east-1 with your preferred region. All commands on this page assume a single consistent region.
Small instance types like t3.micro are low-cost options commonly used for learning. AWS offers a Free Tier that may cover some usage depending on your account age and region. Check the AWS Free Tier guide and verify current eligibility for your specific account before assuming free usage.
Step 1: Find an AMI ID
An AMI is the operating system image your instance boots from. AMI IDs are region-specific: the same OS has a different ID in us-east-1 versus eu-west-1. Do not hardcode IDs from other tutorials. They expire or belong to a different region.
AWS publishes the latest official AMI IDs via SSM Parameter Store. This means you can always look up the current ID programmatically without visiting the Console or copying from a tutorial.
Look up the latest Amazon Linux 2023 AMI ID in your configured region:
aws ssm get-parameter \
--name "/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64" \
--query "Parameter.Value" \
--output textThis returns an ID like ami-0abc1234567890def. Copy it for the launch command in Step 5.
For Ubuntu 22.04 LTS, filter by Canonical’s official owner ID to avoid unofficial images:
aws ec2 describe-images \
--owners 099720109477 \
--filters "Name=name,Values=ubuntu/images/hvm-ssd/ubuntu-jammy-22.04-amd64-server-*" \
--query "sort_by(Images, &CreationDate)[-1].ImageId" \
--output textThe owner ID 099720109477 is Canonical’s AWS account. Always filter by a trusted owner when searching public AMIs.
Step 2: Create a key pair
A key pair is how you SSH into the instance. AWS stores the public key on the instance; you download and keep the private key. If you plan to use Session Manager for access instead of SSH, you can skip this step entirely.
A key pair works like a padlock you mail to AWS. You keep the only key. They bolt the padlock onto your instance’s front door. Anyone who holds the .pem file can unlock it, which is why losing it is a real problem.
aws ec2 create-key-pair \
--key-name my-first-key \
--query "KeyMaterial" \
--output text > my-first-key.pemThen restrict permissions on the file. SSH refuses to use a private key that other users can read:
chmod 400 my-first-key.pemAWS gives you the private key only once, at creation time. Store my-first-key.pem somewhere safe. If you lose it, you will need to replace the instance or recover access via Session Manager. There is no way to retrieve a lost private key from AWS.
Step 3: Create a security group
A security group is a stateful firewall attached to your instance. By default it blocks all inbound traffic. You need to explicitly allow SSH (port 22) from your IP before you can connect.
A security group works like a doorman with a guest list. The default rule is to turn everyone away. You write rules that say: let this specific person in through this specific door. Port 22 is the SSH door. Your IP address is the specific person.
First, find your default VPC ID:
aws ec2 describe-vpcs \
--filters "Name=isDefault,Values=true" \
--query "Vpcs[0].VpcId" \
--output textCreate a security group inside that VPC. Replace vpc-0abc12345def67890 with your VPC ID:
aws ec2 create-security-group \
--group-name my-first-sg \
--description "Security group for my first EC2 instance" \
--vpc-id vpc-0abc12345def67890The output includes a security group ID like sg-0abc12345def67890. Now add an SSH inbound rule restricted to your IP. Find your current public IP first:
curl -s https://checkip.amazonaws.comThen add the rule, replacing YOUR_IP with the address printed above:
aws ec2 authorize-security-group-ingress \
--group-id sg-0abc12345def67890 \
--protocol tcp \
--port 22 \
--cidr YOUR_IP/32Opening SSH to the entire internet means automated bots will start brute-force login attempts within minutes of launch. Always use YOUR_IP/32 to restrict access to only your machine. The /32 means exactly one IP address: yours.
Step 4: Find a subnet ID
Instances launch into a subnet inside a VPC. For this guide, you want a public subnet so the instance receives a routable IP address. Find public subnets in your default VPC:
aws ec2 describe-subnets \
--filters "Name=vpc-id,Values=vpc-0abc12345def67890" \
--query "Subnets[?MapPublicIpOnLaunch==\`true\`].[SubnetId,AvailabilityZone]" \
--output tablePick any subnet ID from the output, for example subnet-0abc12345def67890. If no results appear, your VPC may not have public subnets configured. See default vs custom VPCs.
Step 5: Launch the instance
Replace the placeholder values below with the AMI ID from Step 1, the security group ID from Step 3, and the subnet ID from Step 4:
aws ec2 run-instances \
--image-id ami-0abc1234567890def \
--instance-type t3.micro \
--key-name my-first-key \
--security-group-ids sg-0abc12345def67890 \
--subnet-id subnet-0abc12345def67890 \
--associate-public-ip-address \
--tag-specifications 'ResourceType=instance,Tags=[{Key=Name,Value=my-first-instance}]' \
--count 1The output is a JSON object. Find the InstanceId field. It looks like i-0abc12345def67890. Copy it.
Wait for the instance to reach the running state. This usually takes 30 to 90 seconds:
aws ec2 wait instance-running --instance-ids i-0abc12345def67890Once the command returns, get the public IP address:
aws ec2 describe-instances \
--instance-ids i-0abc12345def67890 \
--query "Reservations[0].Instances[0].PublicIpAddress" \
--output textThe instance is running and billing has started. Your EBS root volume is attached and will accrue storage charges even if you stop the instance later. Terminate when you are done.
Step 6: Connect via SSH
The default SSH username depends on the AMI you used:
- Amazon Linux 2023:
ec2-user - Ubuntu:
ubuntu - RHEL / CentOS:
ec2-userorroot - Windows: connect via RDP, not SSH
# Amazon Linux 2023
ssh -i my-first-key.pem ec2-user@YOUR_PUBLIC_IP
# Ubuntu
ssh -i my-first-key.pem ubuntu@YOUR_PUBLIC_IPReplace YOUR_PUBLIC_IP with the address from Step 5.
If you see WARNING: UNPROTECTED PRIVATE KEY FILE, run chmod 400 my-first-key.pem and retry. If the connection times out rather than refusing, check that the security group allows port 22 from your IP and that the instance is in a public subnet.
Once inside, confirm the instance is working:
# Check OS version
cat /etc/os-release
# Check available disk space
df -h
# Update packages (Amazon Linux)
sudo dnf update -yFor detailed SSH troubleshooting and key management, see the SSH access to EC2 guide.
Optional: Run a startup script with user data
You can pass a shell script via the —user-data flag. AWS runs it automatically on first boot, before you connect. This is useful for installing software without logging in manually.
aws ec2 run-instances \
--image-id ami-0abc1234567890def \
--instance-type t3.micro \
--key-name my-first-key \
--security-group-ids sg-0abc12345def67890 \
--subnet-id subnet-0abc12345def67890 \
--associate-public-ip-address \
--user-data '#!/bin/bash
dnf install -y nginx
systemctl enable nginx
systemctl start nginx'To expose Nginx on port 80, add a second inbound rule to your security group allowing TCP port 80. The user data scripts guide covers how to write, debug, and view logs from startup scripts.
Common mistakes
Forgetting chmod 400 on the .pem file. SSH rejects private keys with open permissions. The error is
WARNING: UNPROTECTED PRIVATE KEY FILE. Runchmod 400 my-first-key.pemand retry.Launching into a private subnet. A private subnet has no direct route from the internet, so SSH times out silently. Check that your chosen subnet has
MapPublicIpOnLaunch: true. See subnets in AWS for the difference between public and private subnets.Opening SSH to 0.0.0.0/0. This exposes port 22 to the entire internet. Automated bots begin brute-force attempts within minutes. Always restrict to
YOUR_IP/32.Using the wrong SSH username. Amazon Linux uses
ec2-user, Ubuntu usesubuntu, RHEL usesec2-user. The wrong username causes the connection to close immediately. It looks like an SSH key problem but is not.Hardcoding an AMI ID from a tutorial. AMI IDs are region-specific and expire when AWS deprecates old images. Always look up the current ID via SSM Parameter Store as shown in Step 1.
Forgetting to terminate test instances. A stopped instance does not charge for compute, but its EBS volume continues to accrue storage charges. Terminate anything you no longer need.
Costs and cleanup
EC2 billing starts the moment an instance enters the running state. The attached EBS volume accrues storage charges separately. This continues even when the instance is stopped.
Stop (pause compute billing)
Stops the instance. The EBS root volume is preserved and you can start it again later. Compute billing pauses, but EBS storage billing continues.
aws ec2 stop-instances --instance-ids i-0abc12345def67890
aws ec2 wait instance-stopped --instance-ids i-0abc12345def67890Terminate (permanent deletion)
Permanently deletes the instance and the root EBS volume by default. This cannot be undone.
aws ec2 terminate-instances --instance-ids i-0abc12345def67890Make sure you have everything you need from the instance before terminating. The root volume is deleted by default and there is no recovery option.
Also clean up the other resources you created. They continue to exist and may incur charges even after the instance is gone:
# Delete the key pair record from AWS (does not delete your local .pem file)
aws ec2 delete-key-pair --key-name my-first-key
# Delete the security group (only works after the instance is terminated)
aws ec2 delete-security-group --group-id sg-0abc12345def67890The AWS Free Tier guide explains what usage may be covered for your account. The how billing works guide covers setting up a billing alarm so unexpected charges alert you before they grow.
Better access options
SSH with a key pair is straightforward, but it requires an open inbound port and careful key management. Two alternatives are worth knowing about.
EC2 Instance Connect
AWS pushes a temporary public key to the instance for a short window. You do not need to manage a key pair yourself. This works from the Console or CLI, but still requires port 22 to be open in the security group.
AWS Systems Manager Session Manager
Session Manager gives you an interactive shell through the SSM Agent running on the instance. No inbound ports need to be open. The agent connects outbound to the SSM service, which makes it possible to reach instances in private subnets without a bastion host or VPN.
Session logging to S3 or CloudWatch Logs is supported but requires explicit configuration. It is not enabled automatically. If your organisation requires an audit trail of shell sessions, configure this in the Session Manager preferences before relying on it for compliance purposes.
To use Session Manager, the instance needs the SSM Agent installed (included in Amazon Linux 2023 and recent Ubuntu AMIs by default) and an IAM instance profile with the AmazonSSMManagedInstanceCore policy attached. The Session Manager guide covers the setup steps.
Summary
- EC2 provides virtual machines you rent by the hour, with full control over the OS and installed software.
- Use
aws ec2 run-instanceswith an AMI ID, instance type, key pair, security group, and subnet to launch. - Look up AMI IDs via SSM Parameter Store rather than hardcoding them. They are region-specific and expire.
- Always restrict SSH (port 22) to your own IP in the security group. Never open it to
0.0.0.0/0. - Run
chmod 400on the.pemfile before using it with SSH. - Stopping an instance pauses compute billing but keeps the EBS volume. Terminating removes everything permanently.
- Session Manager is a more secure access option that requires no open inbound ports and no key pair.
- Verify AWS Free Tier eligibility for your account before assuming any instance type is free to run.
Frequently asked questions
What is the minimum you need to launch an EC2 instance?
You need an AMI ID, an instance type, a security group, and a subnet. A key pair is optional if you plan to use Session Manager for access instead of SSH. The aws ec2 run-instances command accepts all of these as flags.
Do I need a key pair if I use Session Manager?
No. Session Manager gives you a shell session through the AWS Systems Manager service with no inbound ports required. You can skip the key pair entirely if you configure the SSM Agent and attach an appropriate IAM role to the instance.
Why can't I SSH into my instance?
The most common causes are: the security group does not allow port 22 from your IP; the instance is in a private subnet with no route to the internet; the .pem file does not have restricted permissions (chmod 400); or you are using the wrong username for the AMI (ec2-user for Amazon Linux, ubuntu for Ubuntu).
What is the difference between stopping and terminating an EC2 instance?
Stopping pauses the instance and preserves the EBS root volume. You can start it again. Terminating permanently deletes the instance and its root volume by default. Termination cannot be undone.
How do I avoid surprise charges after testing?
Terminate the instance (not just stop it) when you are done. Also delete any EBS snapshots, Elastic IP addresses, and unattached volumes you created. Set up a billing alarm in CloudWatch to notify you if charges exceed a threshold.