Security

How to Safely Decommission an Unused EC2 Instance on AWS

Old servers that nobody remembers are a security risk. They miss patches, keep ports open, and still cost money. This guide shows a simple,…

How to Safely Decommission an Unused EC2 Instance on AWS
Share:

How to Safely Decommission an Unused EC2 Instance on AWS

4 min read
14 views

Old servers that nobody remembers are a security risk. They miss patches, keep ports open, and still cost money. This guide shows a simple, safe way to decommission an unused EC2 instance: prove nobody uses it, give people time to object, keep a backup, and clean up everything it left behind.

Prerequisites

The examples run on WSL2 Ubuntu in Windows, but work the same on any Ubuntu system. All IDs below are placeholders.

Advertisement

Step-by-Step Guide

Step 1: Check Every Network Interface

The EC2 console only shows the public IP of the primary network interface. An instance can have more than one (called an ENI, a virtual network card), and a second one can quietly have its own public IP. List them all:

aws ec2 describe-network-interfaces \
  --filters Name=attachment.instance-id,Values=i-0123456789abcdef0 \
  --query 'NetworkInterfaces[].{Id:NetworkInterfaceId,PublicIp:Association.PublicIp,DeleteOnTerm:Attachment.DeleteOnTermination}' \
  --output table

Take note of any ENI with DeleteOnTerm set to False. It stays behind after you terminate the instance, so you’ll delete it yourself later.

Step 2: Check If Anyone Uses It

Look in three places. Each one catches something the others miss.

Advertisement

CloudTrail (AWS’s audit log) shows Session Manager logins from the last 90 days:

aws cloudtrail lookup-events \
  --lookup-attributes AttributeKey=EventName,AttributeValue=StartSession \
  --start-time "$(date -u -d '90 days ago' +%Y-%m-%dT%H:%M:%SZ)" \
  --output json \
| jq -r '.Events[].CloudTrailEvent | fromjson
    | select(.requestParameters.target == "i-0123456789abcdef0")
    | "\(.eventTime) \(.userIdentity.arn)"'

VPC flow logs show direct SSH connections. If port 22 is open to the internet, expect lots of bot traffic. Bots send a few KB per attempt, while a real session moves much more, so filter by size in CloudWatch Logs Insights:

fields srcAddr, bytes
| filter interfaceId = "eni-0aaaaaaaaaaaaaaaa" and dstPort = 22 and action = "ACCEPT" and bytes > 50000
| stats count() as sessions by srcAddr

No results means no real sessions in the flow log retention window.

The host itself remembers logins longer than flow logs. Use SSM Run Command to check without SSH:

aws ssm send-command \
  --instance-ids i-0123456789abcdef0 \
  --document-name AWS-RunShellScript \
  --parameters '{"commands":["last -F -n 20","journalctl -u sshd --no-pager | grep -c \"Accepted \"","systemctl list-units --type=service --state=running --no-legend","crontab -l"]}' \
  --query Command.CommandId --output text

Read the result with aws ssm get-command-invocation --command-id COMMAND_ID --instance-id i-0123456789abcdef0. You’re looking for recent logins, apps, or cron jobs. If you spot stored credentials on the host, report them to your security team. Deleting the server doesn’t make a leaked key invalid.

Step 3: Make Sure Nothing Else Depends on It

aws ec2 describe-instances --filters Name=key-name,Values=my-old-key \
  --query 'Reservations[].Instances[].InstanceId' --output text

aws ec2 describe-network-interfaces --filters Name=group-id,Values=sg-0aaaaaaaaaaaaaaaa \
  --query 'NetworkInterfaces[].NetworkInterfaceId' --output text

These show whether the key pair or security group is shared with other resources. Also check that Terraform or CloudFormation doesn’t manage the instance, or the next deploy may bring it back.

Step 4: Run a Scream Test

A scream test means switching something off and waiting to see if anyone complains. If they do, you turn it back on. First close public SSH, then stop and tag the instance:

aws ec2 revoke-security-group-ingress \
  --group-id sg-0aaaaaaaaaaaaaaaa \
  --security-group-rule-ids sgr-0aaaaaaaaaaaaaaaa

aws ec2 create-tags --resources i-0123456789abcdef0 \
  --tags Key=decom:stopped-at,Value="$(date -u +%Y-%m-%d)"

aws ec2 stop-instances --instance-ids i-0123456789abcdef0

Tell your team, then wait about a week. No complaints means you’re good to go.

Step 5: Take a Backup That Deletes Itself

A normal snapshot stays forever until someone deletes it. AWS Backup can set an expiry date when you create it:

aws backup start-backup-job \
  --backup-vault-name Default \
  --resource-arn arn:aws:ec2:us-east-1:123456789012:volume/vol-0aaaaaaaaaaaaaaaa \
  --iam-role-arn arn:aws:iam::123456789012:role/service-role/AWSBackupDefaultServiceRole \
  --lifecycle DeleteAfterDays=30

DeleteAfterDays=30 tells AWS Backup to remove the snapshot after 30 days, with no script or cron job needed.

Step 6: Terminate and Clean Up

Terminating doesn’t delete everything. Elastic IPs, extra ENIs, security groups and key pairs stay behind, and an unused Elastic IP still costs money. Remove them in this order:

aws ec2 terminate-instances --instance-ids i-0123456789abcdef0
aws ec2 wait instance-terminated --instance-ids i-0123456789abcdef0

aws ec2 disassociate-address --association-id eipassoc-0aaaaaaaaaaaaaaaa
aws ec2 release-address --allocation-id eipalloc-0aaaaaaaaaaaaaaaa
aws ec2 delete-network-interface --network-interface-id eni-0aaaaaaaaaaaaaaaa
aws ec2 delete-security-group --group-id sg-0aaaaaaaaaaaaaaaa
aws ec2 delete-key-pair --key-name my-old-key

Running describe on each one afterwards should return a NotFound error.

Conclusion

You checked for real usage, gave your team a week to object, kept a backup that cleans itself up, and removed the instance with everything attached to it. One less forgotten server on the internet. If you’re setting up replacement access, plan your private subnets with How to Design IP Addressing for Amazon VPC and Subnets.

Recommended for Linux builders

Contabo VPS hosting for Linux projects

Run Linux servers, automation tools, and self-hosted apps on a Contabo VPS with generous resources and predictable pricing.

Our customers sayExcellent4.6 out of 5 based on 11,008 reviews Trustpilot

Some links are affiliate links. This may earn LinuxBeast a commission at no extra cost to you.

Privacy settings

Choose which privacy controls to open.

Opening these controls does not change your saved choices.