Sub topic 20
Cleaning up to avoid charges
This chapter assumes you can launch an instance with the AWS CLI, that you know what EBS volumes, snapshots, and Elastic IPs are, and that you have used describe-* commands with --query and --filters. Cleanup is the last step of any EC2 exercise. Skipping it is the most common cause of surprise bills for learners.
What keeps costing money
Stopping an instance is not cleanup. Each resource type bills on its own rules, and some keep billing after the instance is gone.
| Resource | Billed when | Stops billing when |
|---|---|---|
| Instance compute | The instance is in the `running` state | The instance is stopped or terminated |
| EBS volume | The volume exists, attached or not | The volume is deleted |
| EBS snapshot | The snapshot exists | The snapshot is deleted |
| Public IPv4 address | The address is in use, including an Elastic IP that is not attached to anything | The Elastic IP is released, or the instance that holds an auto-assigned address is stopped or terminated |
| Instance store | Included in the instance price | The instance stops or terminates (the data is lost) |
A stopped instance still has its root EBS volume, and that volume still costs money. A terminated instance usually deletes its root volume, but not always, and it does not delete extra volumes by default. The DeleteOnTermination flag on each volume attachment controls this.
Plan the order
Delete things in an order that respects their dependencies. An attached volume can't be deleted, and an associated Elastic IP can't be released cleanly. Work from the instance outward.
Step 1: Terminate the instance
Terminate by instance ID. First confirm the ID belongs to the instance you intend to remove, because termination can't be undone.
aws ec2 describe-instances \
--filters Name=tag:Name,Values=tutorial-web \
--query 'Reservations[].Instances[].[InstanceId,State.Name]' \
--output table
aws ec2 terminate-instances --instance-ids i-0123456789abcdef0
aws ec2 wait instance-terminated --instance-ids i-0123456789abcdef0The wait command blocks until the state is terminated. A terminated instance stays visible in describe-instances for about an hour and then disappears. It does not bill during that time.
If termination fails, check whether termination protection is on. The DisableApiTermination attribute blocks the call.
aws ec2 modify-instance-attribute \
--instance-id i-0123456789abcdef0 \
--no-disable-api-terminationStep 2: Find leftover EBS volumes
List volumes in the available state. These are not attached to any instance, so they do nothing except bill you.
aws ec2 describe-volumes \
--filters Name=status,Values=available \
--query 'Volumes[].[VolumeId,Size,VolumeType,CreateTime]' \
--output tableCheck each one before you delete it. A volume that looks orphaned may hold data someone wants. Once you are sure, delete it.
aws ec2 delete-volume --volume-id vol-0123456789abcdef0To avoid this problem in future, launch with DeleteOnTermination set to true for any volume you don't need to keep. You can check the current setting like this:
aws ec2 describe-instances \
--instance-ids i-0123456789abcdef0 \
--query 'Reservations[].Instances[].BlockDeviceMappings[].[DeviceName,Ebs.VolumeId,Ebs.DeleteOnTermination]' \
--output tableRun this before you terminate, since the mapping is gone afterward.
Step 3: Release Elastic IPs
An Elastic IP is yours until you release it. Terminating the instance only disassociates the address. It stays allocated to your account and bills as an idle public IPv4 address.
aws ec2 describe-addresses \
--query 'Addresses[].[AllocationId,PublicIp,AssociationId]' \
--output table
aws ec2 release-address --allocation-id eipalloc-0123456789abcdef0A row with an empty AssociationId is an address attached to nothing.
Step 4: Delete snapshots you no longer need
Snapshots survive the volume they came from. List the ones you own, then delete those you don't need.
aws ec2 describe-snapshots \
--owner-ids self \
--query 'Snapshots[].[SnapshotId,VolumeSize,StartTime,Description]' \
--output table
aws ec2 delete-snapshot --snapshot-id snap-0123456789abcdef0The --owner-ids self filter matters. Without it, the command lists a very large number of public snapshots owned by other accounts.
Snapshots are incremental, so deleting one snapshot may free little storage. Data that a later snapshot still references is kept. Deleting a snapshot never breaks the other snapshots in the chain.
If you created an AMI from your instance, its snapshots can't be deleted while the AMI is registered. Deregister the AMI first, then delete its snapshots.
aws ec2 deregister-image --image-id ami-0123456789abcdef0Step 5: Delete the security group and key pair
Security groups and key pairs don't cost money, but removing them keeps your account tidy. A security group can't be deleted while a network interface still uses it. Run this after the instance reaches terminated.
aws ec2 delete-security-group --group-id sg-0123456789abcdef0
aws ec2 delete-key-pair --key-name my-keyDeleting a key pair removes only the public key stored in AWS. Your local .pem file stays on disk, so remove it yourself if you no longer need it.
If you get a DependencyViolation error on the security group, another resource still references it. Another security group's rules may name it as a source, or a network interface may still be attached. Find the user with this query:
aws ec2 describe-network-interfaces \
--filters Name=group-id,Values=sg-0123456789abcdef0 \
--query 'NetworkInterfaces[].[NetworkInterfaceId,Status,Description]' \
--output tableStep 6: Verify and watch your bill
A clean describe result is the proof that cleanup worked. Check each Region you used, since resources are per Region. This loop covers every enabled Region for running or stopped instances.
for r in $(aws ec2 describe-regions --query 'Regions[].RegionName' --output text); do
echo "== $r"
aws ec2 describe-instances --region "$r" \
--filters Name=instance-state-name,Values=pending,running,stopping,stopped \
--query 'Reservations[].Instances[].InstanceId' --output text
doneRepeat the same idea for volumes, addresses, and snapshots in any Region where you worked. Also open the Billing console's Cost Explorer a day later. Charges appear with a delay, so a resource you missed shows up there first. Setting a budget alert before you start experimenting gives you an early warning.
Common mistakes
- Cleaning up in the wrong Region. The CLI uses your default Region unless you pass
--region. An empty list may only mean you are looking in the wrong place. - Stopping instead of terminating. A stopped instance leaves its EBS volumes billing.
- Forgetting extra volumes. Volumes you added after launch usually keep
DeleteOnTerminationset to false. - Releasing the wrong Elastic IP. Check the allocation ID against the instance first, because a released address can't be reclaimed.
- Leaving snapshots and AMIs. They are easy to forget because they sit under separate console pages.
Exercise
You terminated your instance an hour ago. A day later, Cost Explorer still shows daily charges for EC2-related items. Name three kinds of leftover resources to look for, and give the CLI command that finds one of them.
Show answer
Look for unattached EBS volumes, allocated but unassociated Elastic IPs, and snapshots (or AMIs with snapshots). For volumes, run aws ec2 describe-volumes --filters Name=status,Values=available. For Elastic IPs, run aws ec2 describe-addresses and look for rows with no association. For snapshots, run aws ec2 describe-snapshots --owner-ids self.
Exercise
Why does aws ec2 delete-snapshot fail on a snapshot that backs one of your AMIs, and what do you do?
Show answer
A registered AMI still references the snapshot, so AWS refuses to delete it. Deregister the AMI with aws ec2 deregister-image --image-id <ami-id>, then delete the snapshot.