EC2 is where most students first "rent a server", and where most surprise bills start. These ten tips make instances easier to reach, cheaper to run and harder to break.
Access
1. Skip SSH keys with Session Manager
Systems Manager Session Manager gives you a shell in the browser or CLI with no open port 22 and no key file. The instance needs the SSM Agent (preinstalled on Amazon Linux) and an instance profile with the AmazonSSMManagedInstanceCore policy.
aws ssm start-session --target i-0123456789abcdef0
2. Lost your key? Use EC2 Instance Connect
For Amazon Linux and Ubuntu, EC2 Instance Connect pushes a temporary key for 60 seconds, so you can connect from the console without the original .pem file.
3. Close port 22 to the world
If you do use SSH, set the security group source to My IP, not 0.0.0.0/0 . Bots scan the whole internet for open SSH ports all day.
Cost
4. Pick Graviton (t4g)
Arm-based Graviton instances such as t4g usually cost less than the x86 equivalent for the same size. Most Linux software, Python and Node.js runs on them unchanged.
5. Use Spot for experiments
Spot Instances can be up to 90% cheaper than On-Demand. AWS can reclaim them with a two-minute warning, so use them for batch jobs, training runs and labs you can restart, not for things that must stay up.
6. Stop idle instances automatically
Create a CloudWatch alarm on CPUUtilization below, say, 5% for an hour, with the action Stop this instance. Your forgotten lab server turns itself off.
7. Stop versus hibernate versus terminate
Stop ends compute charges but keeps the EBS volume (still billed). Hibernate also saves RAM to disk, so apps resume where they left off. Terminate deletes the instance. Know which one you're clicking.
Setup and safety
8. Automate setup with user data
Paste a script into User data at launch and it runs as root on first boot: install packages, clone your repo, start your app. That makes your server rebuildable in minutes.
#!/bin/bash
dnf install -y git python3-pip
git clone https://github.com/you/app /opt/app
9. Save your setup as a launch template or AMI
A launch template stores instance type, security group, key and user data. An AMI saves the whole disk. Either way, the next launch is one click instead of fifteen.
10. Turn on termination protection
Enable termination protection (and stop protection) on any instance you care about, so a mis-click or a cleanup script can't delete it.
Quick checklist
- [ ] Session Manager instead of open SSH
- [ ] Security group source set to My IP, if SSH is open
- [ ] Graviton where software allows
- [ ] Auto-stop alarm on idle CPU
- [ ] User data plus a launch template
- [ ] Termination protection on anything important
Which EC2 trick saved you the most time? And are you still opening port 22 to the world?
Loading article