Skip to main content

Launching and Securing AWS EC2 Instances

Launch EC2 instances with the right AMI, instance type, User Data, security groups and IAM role, then choose purchasing options and placement.

Overview and What You Will Learn

Amazon EC2 rents you virtual servers. You choose an AMI (the starting disk image), an instance type (CPU, memory and network), a security group (the firewall) and an IAM role (the instance's permissions), and AWS runs the machine. Almost every other compute service on AWS, including ECS, EKS, Auto Scaling and Elastic Beanstalk, is built on the same pieces, so getting them right here pays off everywhere.

In this lab you will:

  • Launch an instance from CloudFormation with User Data, a restrictive security group and an IAM role
  • Connect through Session Manager and check the role and the metadata service (IMDSv2)
  • Prove how security groups behave and tell a timeout from a refused connection
  • See which IP addresses change on stop and start
  • Bake a custom AMI and clean up its snapshots
  • Choose purchasing options, placement groups, network interfaces and hibernation for real workloads

Why This Matters in Production

Compute is where mistakes are expensive and visible. A wrong instance type wastes money or throttles performance. A security group open to the world gets scanned within minutes. Access keys stored on a server are among the most common causes of cloud breaches, because anyone who compromises the server owns the keys. A platform team at a company like Zerodha or Swiggy standardizes AMIs, roles and security groups so every new server is safe by default and identical to the last one.

Core Principles

An instance is the combination of five decisions. Each one has a safe default.

Decision Safe default
AMI Current Amazon Linux 2023, or your own baked image
Instance type Smallest current-generation type that fits, test Graviton
Network access Security group with only the ports you need
Permissions IAM role, never stored access keys
Access method Session Manager, no open SSH port

AMIs. An AMI is a template with the operating system, installed software and disk layout. AMIs belong to a Region and can be copied to others. There are three kinds: AWS-provided (Amazon Linux, Ubuntu, Windows Server), Marketplace (vendor software pre-installed) and custom AMIs you build. Amazon Linux 2 reached end of support on June 30, 2026, so launch Amazon Linux 2023 (AL2023, supported until June 2029) for new instances and plan to migrate old ones. When you create an AMI from a running instance, AWS snapshots every attached EBS volume and the AMI stores references to those snapshots. Deregistering the AMI does not delete the snapshots, so remove them yourself or they keep billing you.

AMI Default SSH username
Amazon Linux ec2-user
Ubuntu ubuntu
Debian admin
RHEL ec2-user
Windows Server Administrator (RDP)

Instance types. The name encodes family, generation, optional capabilities and size.

◈ DIAGRAM
m7g.2xlarge
| | |
| | +-- size: micro, small, large, xlarge, 2xlarge ...
| +---- generation (higher is newer): 7
+------- family: m = general purpose
suffix letters: g = AWS Graviton (Arm), a = AMD, i = Intel,
d = local NVMe disk, n = faster network
Category Example families Typical use
General purpose T, M Web apps, APIs, small databases
Compute optimized C Batch, transcoding, high-performance computing
Memory optimized R, X In-memory databases, large caches
Storage optimized I, D High-IOPS databases, data warehouses
Accelerated P, G GPU training and inference, graphics

Graviton (Arm) instances usually give better price and performance for software that supports Arm, so test them. The burstable T family earns CPU credits while idle and spends them on bursts, so it suits low or spiky load but throttles under sustained load. The Free Tier rules changed in 2025, so check the current terms in the Billing console before assuming an instance type is free.

Security groups. A security group is a stateful firewall attached to the instance's network interface. It has allow rules only, and traffic that is not allowed is dropped. Because it is stateful, return traffic for an allowed connection is permitted automatically. Groups are specific to a VPC. Chain them by referencing group IDs instead of IP addresses, because IPs change and group IDs do not.

flowchart LR I([Internet]) -->|80 and 443| W[web-sg] W -->|8080 from web-sg| A[app-sg] A -->|5432 from app-sg| D[(db-sg)] classDef edge fill:#F97316,color:#FFFFFF classDef tier fill:#326CE5,color:#FFFFFF classDef data fill:#10B981,color:#FFFFFF class I edge class W,A tier class D data
Tip

A connection timeout usually means something is dropping packets: a security group, network ACL or route. A "connection refused" means the packets arrived but nothing is listening on that port. The two errors tell you where to look.

Ways to connect. A key pair lets you SSH in: AWS stores the public key on the instance and you keep the private key.

Bash
chmod 400 devops-key.pem
ssh -i devops-key.pem ec2-user@13.235.45.67

EC2 Instance Connect pushes a temporary key and opens a browser shell, but port 22 must still be reachable. Session Manager needs no inbound port and no key at all, only the SSM Agent and a role with AmazonSSMManagedInstanceCore, and it records who connected, so it is the best choice for production. For private subnets, an EC2 Instance Connect Endpoint reaches instances without a public IP.

IP addresses. A private IP stays with the instance for its life. An auto-assigned public IP is released when you stop the instance and a new one is assigned on start. An Elastic IP is a static public address you own. AWS now charges for every public IPv4 address, whether attached or idle, and the default limit is five Elastic IPs per Region. In most designs a load balancer with a DNS name is a better stable endpoint than an Elastic IP.

IAM roles. An instance profile delivers temporary, automatically rotated credentials to the instance, so no access key is ever stored on the server. Read credentials through the instance metadata service, and require IMDSv2, which uses a session token and blocks the SSRF attacks that steal credentials through IMDSv1.

User Data. User Data is a script that cloud-init runs as root the first time an instance boots. It must start with #!/bin/bash, is limited to 16 KB, and by default does not run again on later stops and starts. Changing it and restarting does not re-run it, so use Systems Manager or configuration management for ongoing changes.

Common Mistake

Putting passwords or API keys in User Data. Anything running on the instance can read it from the metadata service. Fetch secrets at runtime from Secrets Manager or Parameter Store using the instance role.

Purchasing options.

Option Typical savings Best for
On-Demand None Unpredictable or short-lived workloads
Savings Plans Up to about 66 to 72 percent Steady spend, flexible across instances
Reserved Instances Up to about 72 percent Steady 24/7 use of a known type
Spot Up to about 90 percent Fault-tolerant batch, CI and stateless workers
Dedicated Hosts None Per-socket licenses and compliance isolation
Capacity Reservations None Guaranteed capacity in one AZ

Compute Savings Plans apply across instance families, Regions, Fargate and Lambda, while EC2 Instance Savings Plans give a deeper discount for one family in one Region. Spot instances can be reclaimed by AWS with a two-minute warning, so use them only for work that tolerates interruption. For a persistent Spot request, cancel the request first and then terminate the instance, otherwise the request launches a replacement.

Placement groups. They control how instances sit on hardware.

Type Behavior and use
Cluster Packed in one AZ for the lowest latency and highest throughput, for HPC and ML
Spread Each instance on separate hardware, up to 7 per AZ, for a few critical servers
Partition Groups on separate racks, up to 7 partitions per AZ, for Kafka, Cassandra and Hadoop

Elastic Network Interfaces. An ENI is a virtual network card holding a private IP, MAC address and security groups. Because those belong to the ENI, detaching a secondary ENI from a failed instance and attaching it to a standby moves the IP address with it, with no configuration change in clients. ENIs are tied to one AZ.

Hibernate. Hibernate saves RAM contents to the root EBS volume, then restores them on start so the application resumes where it left off, which helps with slow warm-up. It needs a supported instance and AMI, an EBS root volume large enough for RAM, less than 150 GiB of RAM and a maximum of 60 days. Encrypt the root volume, since RAM can contain secrets, and check the current prerequisites in the EC2 documentation.

Detailed Step-by-Step Practical Lab

Milestone 1: Define the Instance as Code

This template creates a security group that allows only HTTP, a role for Session Manager and S3 read access, and an instance that requires IMDSv2. It looks up the current AL2023 AMI from a public parameter, so no AMI ID is hardcoded.

YAML
AWSTemplateFormatVersion: "2010-09-09"
Description: EC2 lab with User Data, IAM role and a restrictive security group
Parameters:
VpcId:
Type: AWS::EC2::VPC::Id
SubnetId:
Type: AWS::EC2::Subnet::Id
InstanceType:
Type: String
Default: t3.micro
LatestAmiId:
Type: AWS::SSM::Parameter::Value<AWS::EC2::Image::Id>
Default: /aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64
Resources:
WebSecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: HTTP only, no SSH
VpcId: !Ref VpcId
SecurityGroupIngress:
- IpProtocol: tcp
FromPort: 80
ToPort: 80
CidrIp: 0.0.0.0/0
InstanceRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Principal:
Service: ec2.amazonaws.com
Action: sts:AssumeRole
ManagedPolicyArns:
- arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore
- arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess
InstanceProfile:
Type: AWS::IAM::InstanceProfile
Properties:
Roles: [!Ref InstanceRole]
WebServer:
Type: AWS::EC2::Instance
Properties:
InstanceType: !Ref InstanceType
ImageId: !Ref LatestAmiId
IamInstanceProfile: !Ref InstanceProfile
MetadataOptions:
HttpTokens: required
HttpEndpoint: enabled
NetworkInterfaces:
- DeviceIndex: "0"
SubnetId: !Ref SubnetId
AssociatePublicIpAddress: true
GroupSet:
- !Ref WebSecurityGroup
Tags:
- Key: Name
Value: devops-web-01
- Key: Environment
Value: dev
- Key: Team
Value: platform
UserData:
Fn::Base64: |
#!/bin/bash
dnf install -y nginx
echo "<h1>DevOps Network - $(hostname -f)</h1>" > /usr/share/nginx/html/index.html
systemctl enable --now nginx
Outputs:
InstanceId:
Value: !Ref WebServer
SecurityGroupId:
Value: !Ref WebSecurityGroup
PublicIp:
Value: !GetAtt WebServer.PublicIp
Milestone 2: Deploy and Test the Web Server

Use the default VPC for the lab.

Bash
export AWS_REGION=ap-south-1
export VPC_ID=$(aws ec2 describe-vpcs --filters Name=is-default,Values=true \
--query "Vpcs[0].VpcId" --output text)
export SUBNET_ID=$(aws ec2 describe-subnets --filters Name=vpc-id,Values=$VPC_ID \
--query "Subnets[0].SubnetId" --output text)
aws cloudformation deploy \
--stack-name ec2-lab \
--template-file ec2-lab.yaml \
--parameter-overrides VpcId=$VPC_ID SubnetId=$SUBNET_ID \
--capabilities CAPABILITY_IAM
export INSTANCE_ID=$(aws cloudformation describe-stacks --stack-name ec2-lab \
--query "Stacks[0].Outputs[?OutputKey=='InstanceId'].OutputValue" --output text)
export SG_ID=$(aws cloudformation describe-stacks --stack-name ec2-lab \
--query "Stacks[0].Outputs[?OutputKey=='SecurityGroupId'].OutputValue" --output text)
export PUBLIC_IP=$(aws ec2 describe-instances --instance-ids $INSTANCE_ID \
--query "Reservations[0].Instances[0].PublicIpAddress" --output text)
# User Data needs a minute or two to finish
sleep 90
curl -s http://$PUBLIC_IP
Milestone 3: Connect with Session Manager and Check the Role

No SSH port is open and there is no key pair. You need the Session Manager plugin for the AWS CLI.

Bash
aws ssm start-session --target $INSTANCE_ID

Inside the session:

Bash
# The role supplies credentials, nothing was configured
aws sts get-caller-identity
aws s3 ls
# Read metadata with IMDSv2 (session token required)
TOKEN=$(curl -s -X PUT http://169.254.169.254/latest/api/token \
-H "X-aws-ec2-metadata-token-ttl-seconds: 21600")
curl -s -H "X-aws-ec2-metadata-token: $TOKEN" \
http://169.254.169.254/latest/meta-data/instance-id
# A request without the token is refused (HTTP 401)
curl -s -o /dev/null -w "%{http_code}\n" http://169.254.169.254/latest/meta-data/instance-id
# If User Data seems not to have run, read the log
sudo tail -n 30 /var/log/cloud-init-output.log
Milestone 4: Observe Security Group Behavior

Security group changes apply immediately, with no restart.

Bash
# Remove the HTTP rule: requests now time out because packets are dropped
aws ec2 revoke-security-group-ingress \
--group-id $SG_ID --protocol tcp --port 80 --cidr 0.0.0.0/0
curl -s --max-time 5 http://$PUBLIC_IP || echo "timeout: blocked by the security group"
# Restore it: the page loads again
aws ec2 authorize-security-group-ingress \
--group-id $SG_ID --protocol tcp --port 80 --cidr 0.0.0.0/0
curl -s http://$PUBLIC_IP

Now see the other failure. Stop nginx from a Session Manager shell (sudo systemctl stop nginx) and run curl http://$PUBLIC_IP again. It fails immediately with "connection refused", because the security group allows the traffic but nothing is listening. Start nginx again afterward.

Milestone 5: See What Changes on Stop and Start

The private IP stays the same and the auto-assigned public IP changes.

Bash
query_ips() {
aws ec2 describe-instances --instance-ids $INSTANCE_ID \
--query "Reservations[0].Instances[0].[PrivateIpAddress,PublicIpAddress]" --output text
}
echo "before:"; query_ips
aws ec2 stop-instances --instance-ids $INSTANCE_ID
aws ec2 wait instance-stopped --instance-ids $INSTANCE_ID
aws ec2 start-instances --instance-ids $INSTANCE_ID
aws ec2 wait instance-running --instance-ids $INSTANCE_ID
echo "after:"; query_ips

If you need a fixed public address, allocate an Elastic IP and associate it, then release it when finished, because idle and attached public IPv4 addresses are both billed.

Bash
ALLOC_ID=$(aws ec2 allocate-address --domain vpc --query AllocationId --output text)
aws ec2 associate-address --instance-id $INSTANCE_ID --allocation-id $ALLOC_ID
# later
aws ec2 disassociate-address --association-id $(aws ec2 describe-addresses \
--allocation-ids $ALLOC_ID --query "Addresses[0].AssociationId" --output text)
aws ec2 release-address --allocation-id $ALLOC_ID
Milestone 6: Bake a Custom AMI

A pre-baked AMI has your software already installed, so new instances become ready in a fraction of the time User Data would take. This matters most for Auto Scaling, where slow boot means delayed capacity.

Bash
AMI_ID=$(aws ec2 create-image \
--instance-id $INSTANCE_ID \
--name "devops-web-v1" \
--description "nginx baked in" \
--query ImageId --output text)
aws ec2 wait image-available --image-ids $AMI_ID
aws ec2 describe-images --image-ids $AMI_ID \
--query "Images[0].BlockDeviceMappings[].Ebs.SnapshotId" --output text

create-image reboots the instance by default to get a consistent file system. Add --no-reboot only when you accept a less consistent image. Baked images need rebuilding on a schedule so they keep receiving security patches.

Milestone 7: Clean Up

Remove the AMI and its snapshots before deleting the stack.

Bash
SNAP_IDS=$(aws ec2 describe-images --image-ids $AMI_ID \
--query "Images[0].BlockDeviceMappings[].Ebs.SnapshotId" --output text)
aws ec2 deregister-image --image-id $AMI_ID
for s in $SNAP_IDS; do aws ec2 delete-snapshot --snapshot-id $s; done
aws cloudformation delete-stack --stack-name ec2-lab
aws cloudformation wait stack-delete-complete --stack-name ec2-lab

Production Best Practices & Common Pitfalls

  1. Use IAM roles, never access keys on servers. Require IMDSv2 on every instance.
  2. Close port 22. Use Session Manager, or restrict SSH to a specific address.
  3. Allow only needed ports, and reference security groups instead of IPs.
  4. Pre-bake AMIs for Auto Scaling. Rebuild them regularly and delete old ones and their snapshots.
  5. Use current-generation types and test Graviton. Right-size from real CloudWatch data, not guesses.
  6. Tag every instance. Name, environment, team and cost center, because Cost Explorer needs tags.
  7. Match purchasing to the workload. Commit for steady load, Spot for interruptible work, On-Demand for the rest.
  8. Enable detailed monitoring where it matters. Basic monitoring reports every 5 minutes, detailed monitoring every minute.
  9. Migrate off Amazon Linux 2. Use AL2023 for new instances.
Common Mistake

Opening SSH to 0.0.0.0/0. Automated scanners find new public instances within minutes. Use Session Manager, or restrict the source to your own address.

Security

Storing access keys on an instance means anyone who compromises it gets your permissions. Use an instance role and IMDSv2 so credentials are temporary and harder to steal.

Remember

Deregistering an AMI does not delete its snapshots. Delete them yourself or they keep costing money.

Quick Reference & Troubleshooting Commands

Command Description
aws ec2 describe-instances List instances
aws ec2 run-instances Launch an instance
aws ec2 stop-instances and start-instances Stop and start
aws ec2 terminate-instances Delete an instance
aws ec2 describe-security-groups Inspect firewall rules
aws ec2 create-image Build an AMI from an instance
aws ec2 describe-images --owners self List your AMIs
Symptom Likely cause and fix
Connection timeout Security group, network ACL or route is dropping traffic, check inbound rules
Connection refused Application not running or listening on another port
Unable to locate credentials No instance profile attached, attach a role
User Data did not run Syntax error or already ran, read /var/log/cloud-init-output.log
Public IP changed Auto-assigned IPs release on stop, use DNS or an Elastic IP
Not in Session Manager Missing SSM role, agent stopped or no route to SSM endpoints
Cannot hibernate Unsupported instance or AMI, unencrypted or too small root volume

Resources

AWS Direct Connect vs VPN: Run Both as Failover

AWS Direct Connect vs VPN: Run Both as Failover

Run AWS Direct Connect as primary and Site-to-Site VPN as BGP failover. Size the backup, set route preference and test it before an outage does.

10 min read•Aug 2026
Lambda vs Fargate vs EC2 Spot: The Cost Crossover

Lambda vs Fargate vs EC2 Spot: The Cost Crossover

Lambda vs Fargate vs EC2 Spot, at the crossover where Lambda stops being cheaper — 2026 pricing, invocation thresholds, and interruption math.

5 min read•Aug 2026
Secrets Manager vs Parameter Store vs Vault

Secrets Manager vs Parameter Store vs Vault

Secrets Manager vs Parameter Store vs Vault: cost math, rotation, dynamic secrets and a decision flow, plus the Vault, IBM and OpenBao licensing context.

10 min read•Aug 2026
AWS VPC Security: Hardening Every Layer

AWS VPC Security: Hardening Every Layer

Harden your AWS VPC in layers: subnets, Security Groups, NACLs, Flow Logs, endpoints, and IAM conditions, with CLI examples for production.

10 min read•Jul 2026
Event-Driven Architecture on AWS Explained

Event-Driven Architecture on AWS Explained

Build event-driven systems on AWS with SQS, SNS, EventBridge and Kinesis: fan-out, DLQs, idempotent consumers and queue-based scaling.

11 min read•Jul 2026
S3 vs RDS vs DynamoDB: Choosing AWS Storage

S3 vs RDS vs DynamoDB: Choosing AWS Storage

Choosing S3, RDS, or DynamoDB wrong costs you in performance, cost, and scalability. Here is a practical decision guide based on your actual access patterns.

5 min read•Jul 2026
AWS Cost Optimisation: 8 Actions That Cut Bills

AWS Cost Optimisation: 8 Actions That Cut Bills

Cut your AWS bill without re-architecting: eight ordered steps from anomaly alerts and tagging to rightsizing, VPC endpoints, Savings Plans and Spot.

11 min read•Jul 2026
EC2 vs Lambda vs Fargate: Choosing AWS Compute

EC2 vs Lambda vs Fargate: Choosing AWS Compute

Choose between EC2, Lambda and Fargate using traffic shape, state and runtime limits, with worked cost break-evens instead of rules of thumb.

11 min read•Jul 2026

Explore More in AWS Compute and Auto Scaling

All 6 Topics

Frequently Asked Questions

Is Launching and Securing AWS EC2 Instances free to learn on DevOps Network?

Yes - this topic, like everything on DevOps Network, is 100% free with no paywall or sign-up gate.

What does the Launching and Securing AWS EC2 Instances topic cover?

Launch EC2 instances with the right AMI, instance type, User Data, security groups and IAM role, then choose purchasing options and placement.

Found a mistake, an outdated step or a broken link?