Launch your first EC2 instance (Linux)

This is where you run a real server. One command is enough to launch EC2 instance web01 into saat-public-a, a start-up script installs a web server on it, and you open the page in your browser. After that you connect over SSH the careful way, from your own IP address only.

Along the way you’ll see how reboot, stop and terminate differ, and that difference shows up on every AWS bill.

TimeYou needBy the end you can
60 minutessaat-vpc with saat-web-sg (Lessons 8 to 10), your laptop signed in with aws login --profile saat-admin, and the OpenSSH client (built into Windows 10 and 11). Cost: about USD 0.05 if you terminate within two hours.Launch an EC2 instance from the CLI with an AMI, type, subnet, security groups, key pair and user data; connect with SSH; read instance metadata; and know what stop and terminate keep.

What it is, in one line

To launch an EC2 instance is to rent a virtual server: you pick the image, size, network, firewall and key, and AWS starts it in seconds.

In Simple Words

Renting a car at the airport

At the airport rental desk you pick the model (the instance type), the car comes with everything already fitted (the AMI), and they hand you a key (the key pair). You also choose which car park you’ll collect it from (the subnet).

You pay by the hour for as long as you have it. Parking it back in the lot with the engine off is “stop”, and you still pay for the parking space (the disk), while handing back the keys for good is “terminate”.

If you leave a note on the dashboard saying “first thing, put the radio on my station”, that’s the user data script, and it runs once, the first time you start the car.

Engineer's View

What an instance really is

An EC2 instance is a virtual machine running on AWS’s Nitro hypervisor, and its instance type fixes the CPU, memory and network speed. t3.micro, for example, has 2 vCPUs and 1 GiB of RAM and is burstable: it earns CPU credits while idle and spends them under load (Lesson 61 covers what happens when they run out).

The AMI (Amazon Machine Image) is the starting disk. AWS publishes the latest Amazon Linux 2023 AMI ID in a public Systems Manager parameter, so your scripts don’t need to hard-code an AMI ID that goes stale. The root disk is an EBS volume, which Lesson 14 covers.

A key pair is an SSH key: AWS stores the public half and puts it on the instance at first boot, and you keep the private key. User data is a script that cloud-init runs once, as root, at first boot. Instance metadata at 169.254.169.254 is how the instance learns about itself, and you should require IMDSv2 (token-based) at launch because it blocks a whole class of attacks.

On billing, you’re charged per second while the instance runs (Linux has a 60-second minimum), plus the EBS volume all the time and the public IPv4 address for as long as it has one. On new accounts all of this comes out of your credits.

How it works, step by step

Whether you use the console or the CLI, every launch comes down to the same six choices.

1Find the image

Read the AMI ID for the current Amazon Linux 2023 from a public SSM parameter in your Region.

Launch EC2 instance: the six choices in one run-instances command

2Prepare access

Create a key pair once and protect the private key file. SSH should be open only from your own public IP, and only through a separate, temporary security group.

3Prepare the first-boot script

The user data script installs nginx and writes a page. It has to use Linux line endings, and on Windows that matters more than you’d think (Break It shows why).

4Launch, wait, test

run-instances comes back in a second, but the instance needs a minute or two to boot and pass its status checks. After that you test it from outside (HTTP) and from inside (SSH).

When you finish for the day, pick carefully between these three.

Launch EC2 instance: reboot, stop and terminate compared

“Stop” is the one people misunderstand most. A stopped instance has no compute charge, but its disks still cost money, and when you start it again it usually comes up with a different public IP, so anything pointing at the old IP breaks.

✅ Checkpoint: You can list the six launch choices and say what reboot, stop and terminate keep and charge.

Hands-on lab: launch EC2 instance web01 from the CLI

Before you run any command, double-check it

Read every command twice before you press Enter. Check the target: the system or account, the IDs, the names and the sizes. These commands are for learning and were tested in our lab, not on your system. At work, run the read-only list commands first, follow your change process, make sure a backup exists, and ask a second person to check anything that changes or deletes data. You run them at your own risk.

Start as usual and load the network:

cd C:\aws-lab
aws login --profile saat-admin
$env:AWS_PROFILE = 'saat-admin'
$v = Get-Content C:\aws-lab\saat-vpc.json | ConvertFrom-Json

1Find the latest Amazon Linux 2023 image

Run this:

$ami = aws ssm get-parameter --name /aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64 --query Parameter.Value --output text
$ami

You should see something like this (the ID changes as AWS publishes updates):

ami-0a3c14e1ddbe7f23c

2Create a key pair and lock down the key file

Paste this whole block:

$key = aws ec2 create-key-pair --key-name saat-key --key-type ed25519 --key-format pem --tag-specifications 'ResourceType=key-pair,Tags=[{Key=course,Value=saatvedha-aws},{Key=lesson,Value=11}]' --query KeyMaterial --output text
[IO.File]::WriteAllText('C:\aws-lab\saat-key.pem', (($key -join "`n") + "`n"))
icacls C:\aws-lab\saat-key.pem /inheritance:r /grant:r "$($env:USERNAME):(R)"

The last command should end with:

Successfully processed 1 files; Failed processing 0 files

AWS shows you the private key only once. WriteAllText keeps Linux line endings, and icacls takes away everyone else’s access, which SSH insists on.

3Allow SSH from your IP only

Paste this whole block:

$myip = (Invoke-RestMethod https://checkip.amazonaws.com).Trim()
$sshSg = aws ec2 create-security-group --group-name saat-ssh-temp --description "SSH from one admin IP (temporary)" --vpc-id $v.VpcId --tag-specifications 'ResourceType=security-group,Tags=[{Key=Name,Value=saat-ssh-temp},{Key=course,Value=saatvedha-aws},{Key=lesson,Value=11}]' --query GroupId --output text
aws ec2 authorize-security-group-ingress --group-id $sshSg --protocol tcp --port 22 --cidr "$myip/32" | Out-Null
"SSH allowed from $myip"

4Write the user data script with Linux line endings

Paste this whole block:

$ud = @'
#!/bin/bash
dnf install -y nginx
echo "<h1>Hello from web01</h1>" > /usr/share/nginx/html/index.html
systemctl enable --now nginx
'@
[IO.File]::WriteAllText('C:\aws-lab\web01-userdata.sh', ($ud -replace "`r`n", "`n"))

5Launch web01

Paste this whole block (the wait line takes two to three minutes):

$id = aws ec2 run-instances --image-id $ami --instance-type t3.micro --key-name saat-key --subnet-id $v.PublicA --security-group-ids $v.WebSg $sshSg --user-data file://web01-userdata.sh --metadata-options HttpTokens=required --tag-specifications 'ResourceType=instance,Tags=[{Key=Name,Value=web01},{Key=course,Value=saatvedha-aws},{Key=lesson,Value=11},{Key=owner,Value=yourname.admin}]' 'ResourceType=volume,Tags=[{Key=course,Value=saatvedha-aws},{Key=lesson,Value=11}]' --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
aws ec2 describe-instances --instance-ids $id --query "Reservations[0].Instances[0].[InstanceId,State.Name,InstanceType,Placement.AvailabilityZone,PublicIpAddress]" --output text

You should see something like this:

i-0d1e2f3a4b5c6d7e8       running t3.micro        ap-south-1a     13.204.91.17

6Open the page and connect with SSH

Run this:

(Invoke-WebRequest "http://$ip" -UseBasicParsing).Content
ssh -i C:\aws-lab\saat-key.pem ec2-user@$ip "grep PRETTY /etc/os-release; ec2-metadata --availability-zone"

Type yes the first time SSH asks about the host key, and you should see something like this:

<h1>Hello from web01</h1>
PRETTY_NAME="Amazon Linux 2023.9.20251014"
placement: ap-south-1a

You can also paste http:// plus the IP into your browser. ec2-metadata reads instance metadata for you and handles the IMDSv2 token itself.

Launch EC2 instance lab: web01 running, web page and SSH check
web01 running, its page and an SSH check. Something like this.

7Stop and start: watch the IP change

Paste this whole block (about two minutes):

aws ec2 stop-instances --instance-ids $id | Out-Null
aws ec2 wait instance-stopped --instance-ids $id
aws ec2 start-instances --instance-ids $id | Out-Null
aws ec2 wait instance-running --instance-ids $id
$ip2 = aws ec2 describe-instances --instance-ids $id --query "Reservations[0].Instances[0].PublicIpAddress" --output text
"Before: $ip   After: $ip2"

You should see two different addresses, something like this:

Before: 13.204.91.17   After: 3.110.42.205

Lesson 19 puts a DNS name in front of servers and Lesson 20 adds a load balancer, so nothing depends on an IP that can change.

✅ Checkpoint: web01 is running, the page says “Hello from web01”, SSH worked only with your protected key, and the public IP changed after stop and start. Keep web01 for the break lab; cleanup is at its end.

Break It, Then Fix It

These two catch almost every Windows user who launches Linux servers.

1Break it: a private key anyone can read

Give the Users group read access again, then connect:

$ip = aws ec2 describe-instances --instance-ids $id --query "Reservations[0].Instances[0].PublicIpAddress" --output text
icacls C:\aws-lab\saat-key.pem /grant "Users:(R)"
ssh -i C:\aws-lab\saat-key.pem ec2-user@$ip

You’ll get this error (something like this):

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@         WARNING: UNPROTECTED PRIVATE KEY FILE!          @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
Permissions for 'C:\\aws-lab\\saat-key.pem' are too open.
It is required that your private key files are NOT accessible by others.
This private key will be ignored.
Load key "C:\\aws-lab\\saat-key.pem": bad permissions
ec2-user@13.204.91.17: Permission denied (publickey,gssapi-keyex,gssapi-with-mic).

SSH won’t use a key that other people can read, so it tries other methods and then fails. Fix: lock the file down again with the icacls line from lab step 2.

2Break it: user data with Windows line endings

Launch a second server with a script saved the usual PowerShell way (Set-Content writes CRLF line endings):

$ud | Set-Content C:\aws-lab\web02-userdata.sh
$id2 = aws ec2 run-instances --image-id $ami --instance-type t3.micro --key-name saat-key --subnet-id $v.PublicA --security-group-ids $v.WebSg $sshSg --user-data file://web02-userdata.sh --metadata-options HttpTokens=required --tag-specifications 'ResourceType=instance,Tags=[{Key=Name,Value=web02},{Key=course,Value=saatvedha-aws},{Key=lesson,Value=11}]' --query "Instances[0].InstanceId" --output text
aws ec2 wait instance-status-ok --instance-ids $id2
$ip2 = aws ec2 describe-instances --instance-ids $id2 --query "Reservations[0].Instances[0].PublicIpAddress" --output text
Invoke-WebRequest "http://$ip2" -UseBasicParsing
ssh -i C:\aws-lab\saat-key.pem ec2-user@$ip2 "sudo grep -m1 interpreter /var/log/cloud-init-output.log"

You’ll get these errors (something like this):

Invoke-WebRequest : Unable to connect to the remote server
/var/lib/cloud/instance/scripts/part-001: /bin/bash^M: bad interpreter: No such file or directory
Launch EC2 instance break lab: open key permissions and CRLF user data
Both errors from this break lab, something like this.

The instance shows “running” and passes its status checks, but nothing got installed. The first line of the script ended with an invisible carriage return (^M), so Linux went looking for a program called bash plus that character. Fix: always write user data with -replace "`r`n", "`n" as in lab step 4, and whenever user data “didn’t run”, check /var/log/cloud-init-output.log.

Because user data only runs at first boot, fixing it means launching a new instance.

3Clean up

Paste this whole block:

aws ec2 terminate-instances --instance-ids $id $id2 | Out-Null
aws ec2 wait instance-terminated --instance-ids $id $id2
aws ec2 delete-security-group --group-id $sshSg
.\Find-LabResources.ps1

Keep the key pair saat-key and saat-key.pem, because they cost nothing and Lesson 12 uses them. The finder should list only the things you’re keeping (the VPC parts, security groups, endpoint and key pair).

✅ Checkpoint: You fixed key permissions, found a CRLF user data failure in the cloud-init log, and terminated both instances.

This happened at work

The partner integration that broke after maintenance

This one happened at a payments company that ran a small “callback” server on EC2. A bank partner had whitelisted its public IP address and sent payment confirmations to it. Every Sunday the operations team stopped non-production servers to save money, and one weekend someone added this server to that list by mistake.

It came back up on Monday morning with a new public IP, so the bank’s confirmations were going to an address the company no longer owned. For six hours customers saw their payments as “pending”, and the support team was answering hundreds of calls.

The fix was an Elastic IP address, which stays the same across stop and start, and that’s what the partner got. The team also tagged every server with schedule=never-stop or schedule=office-hours so the shutdown script could only touch the right ones, and new integrations now go through a load balancer or a NAT gateway with a fixed address instead of a plain instance IP.

Common mistakes and troubleshooting

MistakeWhat happensWhat to do
Opening SSH to 0.0.0.0/0Thousands of login attempts within hoursYour IP only now; Session Manager with no port 22 from Lesson 13
Losing the .pem fileNo SSH access to that instanceKeep it safe; Lesson 13 shows access without keys
Key file readable by others“UNPROTECTED PRIVATE KEY FILE”, bad permissionsicacls ... /inheritance:r /grant:r "$($env:USERNAME):(R)"
User data saved with CRLFbad interpreter, nothing installedWrite with LF; check /var/log/cloud-init-output.log
Hard-coding an AMI IDOld, unpatched images or “AMI not found” in another RegionRead the public SSM parameter each time
Stopping instead of terminating test serversDisks keep charging every monthTerminate what you don’t need; snapshot first if unsure
Depending on a public IPIt changes after stop and startElastic IP, DNS name or load balancer

Interview questions

Click a question to open it. Each one is phrased the way an interviewer would put it, with a note on why they ask and one way you could answer, in your own words.

Fresher level

1. Can you explain in simple words what an AMI is?

Why they ask this: It’s a basic EC2 vocabulary check, because you can’t launch or rebuild a server well if you don’t understand images.

How you might answer: An AMI, an Amazon Machine Image, is a template that holds the operating system and software plus settings like the root volume, and I launch instances from it.

Amazon Linux, Windows Server and the images I build myself are all AMIs.

2. A teammate wants to save money over the weekend. Should they stop the instance or terminate it? What’s the difference?

Why they ask this: They want to see that you think about cost and data together, since terminating by mistake is a classic beginner disaster.

How you might answer: Stopping powers it off. There’s no compute charge, but the EBS disks are kept and still charged, and the public IP usually changes.

Terminating deletes the instance, and by default its root volume too, and there’s no starting it again. For a weekend break I’d tell them to stop it.

3. How would you explain user data to a new team member?

Why they ask this: They’re checking you know the basics of automating a server at launch, which tells them whether you build servers by hand or by script.

How you might answer: I’d tell them user data is a script or cloud-init config you pass in at launch, and it runs once, at first boot, as root.

We use it to install software and set up the server automatically, so nobody has to log in and do it by hand.

2–5 years experience

4. You launch a Linux instance with a user data script, but the software never got installed. How do you find out why?

Why they ask this: They want to see how you troubleshoot first boot, and knowing where the logs are saves a lot of guessing.

How you might answer: First I’d connect and read /var/log/cloud-init-output.log and cloud-init.log. Usually it’s Windows line endings, a missing shebang, or package installs failing because the instance has no internet access.

I’ve also seen scripts that call the instance metadata service and fail because IMDSv2 tokens are required.

5. Your security team wants IMDSv2 required on every instance. Can you explain why it matters?

Why they ask this: It’s about security awareness around instance credentials, since this one setting blocks a well-known attack path.

How you might answer: With IMDSv2 you need a session token from a PUT request before the metadata service returns anything. That stops server-side request forgery attacks, where a plain GET request could otherwise read the instance role’s credentials.

I’d set HttpTokens=required at launch, or change it later on instances that are already running.

6. A team asks you which instance type they should use for a new app. How would you decide?

Why they ask this: It tests practical sizing, and whether you measure after launch instead of guessing once and moving on.

How you might answer: I’d start from the workload: CPU, memory, network, and whether it’s steady or bursty. T types suit small or spiky loads, M is general purpose, C is for CPU-heavy work and R for memory-heavy work.

After a week I’d look at the CloudWatch metrics and right-size, and if the software runs on Arm, Graviton types are often cheaper.

Senior level

7. How would you make sure nobody launches instances without the required tags, or with public IPs in private subnets?

Why they ask this: They want to hear that you’d build guardrails instead of relying on people remembering, because at senior level you’re expected to make the safe way the easy way.

How you might answer: I’d use tag policies and SCPs that deny RunInstances without the required tags, plus IAM conditions on ec2:CreateTags, and launch templates to set the approved settings.

AWS Config rules would catch public IPs and unencrypted volumes, and infrastructure code would be the normal way to launch anything.

8. It’s 2 a.m. and an instance is running but failing its status checks. What does that tell you, and what do you do?

Why they ask this: They want to know you understand the two kinds of status checks, because each points to a different fix and reading them right saves time.

How you might answer: If the system status check fails, it’s a problem with the AWS host, so I’d stop and start the instance to move it to new hardware. If the instance status check fails, the OS itself is unhealthy, say bad network config, a full disk or a kernel panic.

In that case I’d read the system log and use the serial console, then either fix the instance or replace it.

Quick quiz

Q1. Which is the safest way to find the current Amazon Linux 2023 AMI ID in a script?

  1. Copy it from a blog
  2. Read the public SSM parameter
  3. Use the oldest AMI
  4. Ask AWS Support
Show answer

B. AWS updates the public SSM parameter every time it releases a new AMI.

Q2. What happens to the public IP when you stop and start an instance without an Elastic IP?

  1. It stays the same
  2. It usually changes
  3. It becomes private
  4. The instance loses its network
Show answer

B. The instance gets a new public IP when it starts again.

Q3. SSH says “UNPROTECTED PRIVATE KEY FILE”. What is wrong?

  1. The key is expired
  2. Other users can read the key file
  3. Port 22 is closed
  4. The instance is stopped
Show answer

B. OpenSSH refuses keys with open permissions, so lock the file down with icacls.

Q4. User data fails with “/bin/bash^M: bad interpreter”. Why?

  1. bash isn’t installed
  2. The script has Windows (CRLF) line endings
  3. IMDSv2 blocked it
  4. The AMI is wrong
Show answer

B. The ^M is the carriage return left by CRLF line endings.

Q5. What keeps charging after you stop an instance?

  1. vCPU hours
  2. The EBS volume
  3. The key pair
  4. The AMI ID
Show answer

B. A stopped instance has no compute charge, but its EBS volumes are still charged per GB-month.

Quick recap

  • A launch picks an AMI, an instance type, a subnet, security groups, a key pair and optional user data.
  • Read the AMI ID from the public SSM parameter; require IMDSv2 at launch.
  • On Windows, write keys and user data with LF endings and lock the key file with icacls.
  • Reboot keeps everything; stop keeps disks (still charged) and changes the public IP; terminate deletes.
  • When user data “didn’t run”, read /var/log/cloud-init-output.log.

Next lesson

Lesson 12: Windows Server on EC2 → Next you launch a Windows Server instance, get its Administrator password and connect with Remote Desktop.

Further reading: launch EC2 instance

To read more on the launch EC2 instance steps, see Launch an Amazon EC2 instance and Run commands when you launch an EC2 instance with user data input, both in the AWS docs. The full plan for this course is on the AWS Cloud Administration course page.

Scroll to Top

This website uses cookies

We use a few cookies to keep this site working. If you allow it, we also use Google Analytics to count visits so we can improve our lessons. You can accept all, deny the optional ones, or choose what to allow.