Cloud and deployment · Intermediate · 22 min
Find and stop what is costing you money on AWS
By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · AWS CLI 2.42.4
You will know which service and usage type pushed your AWS bill up, have a read-only script that lists idle volumes, old snapshots, unused public IPv4 addresses, NAT gateways, empty load balancers and stopped instances in every enabled Region, and have removed what you no longer need.
On this page
A bill that jumps from USD 4 to USD 40 rarely has a mystery behind it. Something is still switched on: a NAT gateway from a networking experiment, a load balancer with nothing behind it, a stopped instance whose disks you are still paying for, or a public IPv4 address that has been billed by the hour since February 2024 whether it is used or not. The hard part is that these things sit in different screens, often in a Region you forgot you touched.
This tutorial works in two halves. First you ask Cost Explorer where the money went, from the command line, narrowing it down from service to usage type to Region. Then you write find-waste.sh, a short read-only script that looks for the usual causes in every Region your account has enabled and prints one line per finding. The last two steps remove what it found, with a warning before each delete.
Everything lives in ~/aws-cost-demo. The script only calls describe and get APIs, so you can run it as often as you like. The Cost Explorer calls are the one part that costs money: USD 0.01 per request on the Cost Explorer pricing page (read 26 November 2026). This tutorial makes three of them and saves each answer to a file, so you can read it again for free.
Step 1 · Install the AWS CLI and confirm the account
Install curl, unzip and jq, then version 2.42.4 of the AWS CLI from Amazon's versioned installer. uname -m prints x86_64 or aarch64, which matches Amazon's file names:
sudo apt update
sudo apt install -y curl unzip jq ca-certificates
AWS_CLI_VERSION=2.42.4
cd "$(mktemp -d)"
curl -fsSLo awscliv2.zip "https://awscli.amazonaws.com/awscli-exe-linux-$(uname -m)-${AWS_CLI_VERSION}.zip"
unzip -q -o awscliv2.zip
sudo ./aws/install
aws --versionIf the CLI is already installed, the installer says so; run sudo ./aws/install --update instead. It gets no updates from apt, so to upgrade later you run the same commands with a newer version number. The zip is tens of megabytes; on a prepaid mobile bundle, download it once over Wi-Fi and keep it.
If you use a named profile, run export AWS_PROFILE=<your-profile> first (replace the placeholder); set up the AWS CLI with SSO and named profiles shows how. Then make the working folder and check which account you are about to inspect:
mkdir -p ~/aws-cost-demo
cd ~/aws-cost-demo
aws sts get-caller-identity --query '[Account,Arn]' --output textCheck it worked
aws --version starts with aws-cli/2.42.4, and the last command prints your 12-digit account ID and the ARN of the identity you signed in as. If either is not what you expected, fix your profile now: everything after this reads, and later deletes, in that account.
Step 2 · See which services the bill went up on
Start with the question the bill asks: which service changed? Compare last month with this month so far. jq works out the dates the same way on Linux and macOS; the start is the first day of last month, and the end, which Cost Explorer does not include, is today:
cd ~/aws-cost-demo
START=$(jq -rn 'now | floor | gmtime | .[1] -= 1 | .[2] = 1 | mktime | strftime("%Y-%m-%d")')
END=$(jq -rn 'now | strftime("%Y-%m-%d")')
echo "From ${START} up to ${END}"Now ask for unblended cost per service, one figure per calendar month. Cost Explorer is served from us-east-1 whichever Region you work in. This is the first of the three paid requests:
aws ce get-cost-and-usage --region us-east-1 \
--time-period Start="$START",End="$END" \
--granularity MONTHLY \
--metrics UnblendedCost \
--group-by Type=DIMENSION,Key=SERVICE \
--output json > by-service.jsonThe raw answer has one block per month, each with its own list of services. This jq program turns it into one line per service with both months side by side, biggest current spend first, and hides anything under a cent:
jq -r '
(.ResultsByTime | map(.TimePeriod.Start)) as $months
| [.ResultsByTime[] as $m | $m.Groups[]
| {service: .Keys[0], month: $m.TimePeriod.Start, usd: (.Metrics.UnblendedCost.Amount | tonumber)}]
| group_by(.service)
| map({service: .[0].service,
before: (map(select(.month == $months[0]).usd) | add // 0),
now: (map(select(.month == $months[-1]).usd) | add // 0)})
| map(select(.now >= 0.01 or .before >= 0.01))
| sort_by(-.now)
| (["SERVICE", "LAST_MONTH", "THIS_MONTH"] | @tsv),
(.[] | [.service, (.before * 100 | round / 100), (.now * 100 | round / 100)] | @tsv)
' by-service.json | tee service-summary.tsvRead it with one thing in mind: this month is not finished. A service at USD 9 after ten days of the month is heading for about USD 27. Look for services whose current figure is already close to, or above, last month's, and for services that did not exist last month at all.
Check it worked
You see a header line and then one line per service, something like EC2 - Other 0.81 27.9. The first data line is the service to chase. Write its name down exactly as printed. If the call failed with AccessDeniedException, your identity lacks ce:GetCostAndUsage, or IAM access to billing information has not been activated for the account (the root user turns it on under Account settings). If it says Cost Explorer is not enabled, open Cost Explorer once in the console and wait about a day for the data.
Step 3 · Narrow it down to usage type and Region
A service name is still too broad. EC2 - Other in particular is a catch-all that holds EBS volumes and snapshots, NAT gateways and EC2 data transfer. Elastic IP charges no longer sit here: since February 2024 they bill as public IPv4 under Amazon Virtual Private Cloud. The usage type says exactly which meter is running. Set the service you wrote down, then build a filter file for it:
SERVICE='EC2 - Other'
jq -n --arg service "$SERVICE" '{Dimensions: {Key: "SERVICE", Values: [$service]}}' > filter.json
cat filter.jsonReplace EC2 - Other with your own service name if it was different. Then ask for that one service grouped by usage type (the second paid request):
aws ce get-cost-and-usage --region us-east-1 \
--time-period Start="$START",End="$END" \
--granularity MONTHLY \
--metrics UnblendedCost \
--filter file://filter.json \
--group-by Type=DIMENSION,Key=USAGE_TYPE \
--output json > by-usage-type.jsonThis month's usage types, largest first:
jq -r '.ResultsByTime[-1].Groups
| map({type: .Keys[0], usd: (.Metrics.UnblendedCost.Amount | tonumber)})
| map(select(.usd >= 0.01)) | sort_by(-.usd)
| .[] | [.type, (.usd * 100 | round / 100)] | @tsv' by-usage-type.json | tee usage-summary.tsvUsage type names start with a short Region code outside us-east-1 (such as EU- for Ireland, so EU-NatGateway-Hours, or EUW2- for London) and then name the meter. The ones this tutorial goes after look something like this:
NatGateway-HoursandNatGateway-Bytes: a NAT gateway exists, and traffic passes through it;EBS:VolumeUsage.gp3(or.gp2,.io2): EBS volumes, attached or not;EBS:SnapshotUsage: snapshots;PublicIPv4:InUseAddressandPublicIPv4:IdleAddress, usually under theAmazon Virtual Private Cloudservice: public IPv4 addresses, at USD 0.005 per address per hour for both in-use and idle ones on the Amazon VPC pricing page (read 26 November 2026);LoadBalancerUsage, underAmazon Elastic Load Balancing: hours a load balancer has existed.
Last, find out where the spend is. A resource in a Region you never open in the console is the classic surprise. The third paid request groups the whole bill by Region:
aws ce get-cost-and-usage --region us-east-1 \
--time-period Start="$START",End="$END" \
--granularity MONTHLY \
--metrics UnblendedCost \
--group-by Type=DIMENSION,Key=REGION \
--output json > by-region.jsonThe last block in the answer is this month. Spend with no Region at all (tax, support, some global services) shows as global or NoRegion.
Check it worked
usage-summary.tsv lists usage types with this month's cost, the biggest first, and the top line names a meter you can match to the list above. jq -r '.ResultsByTime[-1].Groups[] | [.Keys[0], .Metrics.UnblendedCost.Amount] | @tsv' by-region.json prints Region codes such as us-east-1 or eu-west-1 with an amount. Any Region you did not expect is a lead for the sweep in a later step.
Step 4 · Write a read-only script that finds the usual causes
Cost Explorer tells you the meter; it does not name the resource. For that you ask each service what it is running. The script below checks seven things that keep billing while doing little or nothing:
- unattached EBS volumes (state
available), billed for their full size; - snapshots you own older than 90 days (change it with
SNAPSHOT_DAYS); - idle Elastic IPs, allocated but not associated with anything;
- every public IPv4 address on a network interface, used or not, since each is billed by the hour;
- NAT gateways, billed for every hour they exist plus every gigabyte they process;
- stopped instances, which no longer bill for compute but still bill for their volumes;
- load balancers with no registered targets.
Write it into the working folder:
cd ~/aws-cost-demo
cat > find-waste.sh <<'SCRIPT'
#!/usr/bin/env bash
# find-waste.sh: list AWS resources that keep billing while doing little or nothing.
# Usage: ./find-waste.sh [region ...] (no arguments: every Region enabled for the account)
# Read-only: it only calls describe and get APIs. Output is tab-separated: REGION KIND ID DETAIL.
set -euo pipefail
SNAPSHOT_DAYS="${SNAPSHOT_DAYS:-90}"
ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
CUTOFF=$(jq -rn --argjson days "$SNAPSHOT_DAYS" '(now - $days * 86400) | todate')
TMP=$(mktemp -d)
trap 'rm -rf "$TMP"' EXIT
if [ "$#" -gt 0 ]; then
REGIONS="$*"
else
REGIONS=$(aws ec2 describe-regions --region us-east-1 --query 'Regions[].RegionName' --output text)
fi
printf 'REGION\tKIND\tID\tDETAIL\n'
for r in $REGIONS; do
echo "Checking ${r}" >&2
aws ec2 describe-volumes --region "$r" --output json > "$TMP/volumes.json"
jq -r --arg r "$r" '.Volumes[] | select(.State == "available")
| [$r, "unattached-volume", .VolumeId, "\(.Size) GiB \(.VolumeType), created \(.CreateTime[0:10])"] | @tsv' \
"$TMP/volumes.json"
aws ec2 describe-snapshots --region "$r" --owner-ids "$ACCOUNT_ID" --output json \
| jq -r --arg r "$r" --arg me "$ACCOUNT_ID" --arg cutoff "$CUTOFF" '.Snapshots[]
| select(.OwnerId == $me and .StartTime < $cutoff)
| [$r, "old-snapshot", .SnapshotId, "\(.VolumeSize) GiB, taken \(.StartTime[0:10])"] | @tsv'
aws ec2 describe-addresses --region "$r" --output json \
| jq -r --arg r "$r" '.Addresses[] | select(.AssociationId == null)
| [$r, "idle-elastic-ip", .AllocationId, .PublicIp] | @tsv'
aws ec2 describe-network-interfaces --region "$r" --output json \
| jq -r --arg r "$r" '.NetworkInterfaces[] | select(.Association.PublicIp != null)
| [$r, "public-ipv4", .NetworkInterfaceId,
"\(.Association.PublicIp) on \(.Attachment.InstanceId // .InterfaceType // "nothing")"] | @tsv'
aws ec2 describe-nat-gateways --region "$r" --output json \
| jq -r --arg r "$r" '.NatGateways[] | select(.State == "available" or .State == "pending")
| [$r, "nat-gateway", .NatGatewayId, "in \(.SubnetId), created \(.CreateTime[0:10])"] | @tsv'
aws ec2 describe-instances --region "$r" --filters Name=instance-state-name,Values=stopped --output json \
| jq -r --arg r "$r" --slurpfile vols "$TMP/volumes.json" '
($vols[0].Volumes | map({key: .VolumeId, value: .Size}) | from_entries) as $size
| .Reservations[].Instances[]
| [$r, "stopped-instance", .InstanceId,
([.BlockDeviceMappings[]? | .Ebs.VolumeId // empty | "\(.) \($size[.] // "?") GiB"]
| join(", ") | if . == "" then "no EBS volumes" else . end)] | @tsv'
aws elbv2 describe-load-balancers --region "$r" \
--query 'LoadBalancers[].[LoadBalancerArn,LoadBalancerName,Type]' --output text \
| while read -r arn name type; do
targets=0
for tg in $(aws elbv2 describe-target-groups --region "$r" --load-balancer-arn "$arn" \
--query 'TargetGroups[].TargetGroupArn' --output text); do
n=$(aws elbv2 describe-target-health --region "$r" --target-group-arn "$tg" \
--query 'length(TargetHealthDescriptions)' --output text)
targets=$((targets + n))
done
if [ "$targets" -eq 0 ]; then
printf '%s\tidle-load-balancer\t%s\t%s, no registered targets\n' "$r" "$name" "$type"
fi
done
done
SCRIPT
chmod +x find-waste.sh
bash -n find-waste.sh && echo "Syntax OK"A few choices worth knowing about. Every call names its Region with --region, so your profile's default Region does not matter. The volume list is fetched once per Region and reused to show the size of each stopped instance's disks. Filtering happens in jq, not in --query, because the JMESPath behind --query cannot easily compare a snapshot's timestamp with a cutoff worked out in the shell, and keeping all the logic in one jq filter makes it easier to read. Snapshots are matched on your own account ID, so public snapshots shared by others never show up. set -euo pipefail stops the script at the first failed call, which is what you want: a half-finished report that looks complete is worse than an error.
Check it worked
The last line prints Syntax OK, and head -3 find-waste.sh shows the #!/usr/bin/env bash line and the usage comment. ls -l find-waste.sh shows it is executable (-rwx at the start).
Step 5 · Run it in your main Region and read the findings
Start with the Region you use most. Replace us-east-1 with yours:
cd ~/aws-cost-demo
./find-waste.sh us-east-1 > findings-home.tsv
cat findings-home.tsvProgress messages (Checking us-east-1) go to the terminal; the findings go to the file. Each line has four tab-separated columns: the Region, what kind of finding it is, the ID you need to act on it, and a detail. Read each kind like this before you touch anything:
unattached-volume: a disk nobody is using. Check the creation date and size. A volume left behind by a terminated instance is usually safe to remove; one someone detached on purpose may hold data they still want.old-snapshot: a backup older than the cutoff. Snapshots are incremental, so deleting one old snapshot may free less storage than its size suggests, but a long chain of daily snapshots adds up.idle-elastic-ip: an address you pay for and do not use. Keep it only if a DNS record or a partner's allow list depends on that exact address.public-ipv4: an address in use, on an instance (i-...), a NAT gateway or a load balancer. Not waste by itself, but each one bills. On an account opened from 15 July 2025, Free Tier credits absorb these charges only until the credits run out or the free plan ends.nat-gateway: the most common big surprise in a learning account. It bills every hour it exists, even with no traffic.stopped-instance: no compute charge, but each listed volume bills for its full size every month, and an Elastic IP on it still bills.idle-load-balancer: a load balancer with nothing behind it, billed for every hour it exists.
If the file holds only the header line, nothing in this Region matches. That is a good result, and the next step looks everywhere else.
Check it worked
cat findings-home.tsv prints REGION KIND ID DETAIL and then one line per finding, for example us-east-1 nat-gateway nat-0a1b2c3d4e5f60789 in subnet-..., created 2026-10-30. Each ID matches something you can find in the EC2 or VPC console for that Region. Write down which findings you recognise and which you do not; ask whoever shares the account about the ones you do not.
Step 6 · Sweep every enabled Region
Leftovers in other Regions are the ones that run for months, because the console only shows one Region at a time. With no arguments, the script asks EC2 for every Region enabled for your account and checks each in turn. That is about seven calls per Region, so expect a few minutes:
cd ~/aws-cost-demo
./find-waste.sh > findings-all.tsv
tail -n +2 findings-all.tsv | cut -f1,2 | sort | uniq -cdescribe-regions without --all-regions lists only enabled Regions. Opt-in Regions, such as Africa (Cape Town), af-south-1, appear only if someone enabled them, and nothing can run in a Region that is not enabled, so the sweep misses nothing that bills. If the script stops with AuthFailure or UnauthorizedOperation in one Region, an organisation policy may block it there; run ./find-waste.sh again with the remaining Regions listed as arguments.
The script covers EC2, EBS, VPC and the current load balancer types. It does not look at RDS databases, Classic Load Balancers, EKS clusters or anything outside EC2's world. If the usage types from Cost Explorer point at one of those, open that service's console in the Region by-region.json named.
Check it worked
The summary prints one count per Region and kind, something like 1 eu-west-1 unattached-volume. Every Region that appeared in by-region.json with real spend should either show up here or belong to a service the script does not check. A Region you have never worked in that shows up here is your leftover.
Step 7 · Remove storage you no longer need
Every command in this step permanently deletes data, and AWS has no recycle bin by default. Work through findings-all.tsv one line at a time, copy the Region and ID from that line into the placeholders, and do not script these deletes until you have done them by hand once.
An unattached volume. If you might want the data later, snapshot it first. A snapshot also bills, but usually less than the volume did. Then delete the volume:
aws ec2 create-snapshot --region <region> --volume-id <volume-id> --description "Kept before deleting <volume-id>"
aws ec2 delete-volume --region <region> --volume-id <volume-id>An old snapshot. A snapshot that backs one of your AMIs cannot be deleted until the AMI is deregistered, and you may still launch servers from that AMI. Check first; an empty answer means no AMI uses it:
aws ec2 describe-images --region <region> --owners self \
--query "Images[?BlockDeviceMappings[?Ebs.SnapshotId=='<snapshot-id>']].[ImageId,Name]" --output text
aws ec2 delete-snapshot --region <region> --snapshot-id <snapshot-id>A stopped instance you will not start again. First see which volumes go with it. Volumes marked True in the last column are deleted with the instance; False ones stay behind as unattached volumes, which the next sweep will show:
aws ec2 describe-instances --region <region> --instance-ids <instance-id> \
--query 'Reservations[0].Instances[0].BlockDeviceMappings[].[DeviceName,Ebs.VolumeId,Ebs.DeleteOnTermination]' --output textIf you might need the server again, make an AMI of it before you terminate it. The AMI keeps snapshots of its volumes, which bill until you deregister the AMI and delete them. Terminating cannot be undone:
aws ec2 create-image --region <region> --instance-id <instance-id> --name "<instance-id>-before-terminate"
aws ec2 terminate-instances --region <region> --instance-ids <instance-id>Check it worked
Run the script again for the Region you cleaned, for example ./find-waste.sh <region> | grep -E 'unattached-volume|old-snapshot|stopped-instance'. The IDs you deleted are gone. A volume you kept on purpose, or one left by a terminated instance with DeleteOnTermination set to False, still shows; decide on it the same way.
Step 8 · Remove idle network resources and sweep again
These deletes do not destroy data, but they can break things that depend on them, so read each warning before the command.
An idle Elastic IP. Once released, you will almost certainly never get that exact address back. Make sure no DNS record, firewall rule or partner allow list names it:
aws ec2 release-address --region <region> --allocation-id <allocation-id>A NAT gateway. Deleting it cuts outbound internet access for every private subnet whose route table points at it: those routes become blackholes, and servers there can no longer download updates. First list those route tables, and note the Elastic IP the gateway uses, because deleting the gateway leaves that address allocated and billing:
aws ec2 describe-route-tables --region <region> \
--query "RouteTables[?Routes[?NatGatewayId=='<nat-gateway-id>']].RouteTableId" --output text
aws ec2 describe-nat-gateways --region <region> --nat-gateway-ids <nat-gateway-id> \
--query 'NatGateways[0].NatGatewayAddresses[].AllocationId' --output text
aws ec2 delete-nat-gateway --region <region> --nat-gateway-id <nat-gateway-id>Deletion takes a few minutes. Repeat this until it prints deleted, then release the address the second command printed:
aws ec2 describe-nat-gateways --region <region> --nat-gateway-ids <nat-gateway-id> --query 'NatGateways[0].State' --output text
aws ec2 release-address --region <region> --allocation-id <allocation-id-from-above>A load balancer with no targets. Its DNS name stops resolving for good, so check that no DNS record or app config still points at it. Target groups outlive the load balancer, so note them first and delete them after. If the delete fails because deletion protection is on, someone turned that on deliberately; ask before you turn it off. Replace the name with the ID from your findings:
LB_NAME=<load-balancer-name>
LB_ARN=$(aws elbv2 describe-load-balancers --region <region> --names "$LB_NAME" --query 'LoadBalancers[0].LoadBalancerArn' --output text)
TG_ARNS=$(aws elbv2 describe-target-groups --region <region> --load-balancer-arn "$LB_ARN" --query 'TargetGroups[].TargetGroupArn' --output text)
aws elbv2 delete-load-balancer --region <region> --load-balancer-arn "$LB_ARN"
for tg in $TG_ARNS; do aws elbv2 delete-target-group --region <region> --target-group-arn "$tg"; doneA public IPv4 address on a running instance. Only remove it if the instance does not need to be reached from the internet, or reaches out through IPv6 or a NAT gateway instead. Without it you can still get a shell with Session Manager. This works on the instance's primary network interface (the eni-... ID in the finding). To stop new instances in a subnet getting an address automatically, turn the setting off on the subnet as well:
aws ec2 modify-network-interface-attribute --region <region> --network-interface-id <eni-id> --no-associate-public-ip-address
aws ec2 modify-subnet-attribute --region <region> --subnet-id <subnet-id> --no-map-public-ip-on-launchNow sweep every Region again and keep the result as your baseline for next month:
cd ~/aws-cost-demo
./find-waste.sh > findings-after.tsv
tail -n +2 findings-after.tsv | cut -f2 | sort | uniq -cCheck it worked
None of the IDs you removed appear in findings-after.tsv. What remains is either something you decided to keep, such as the public IPv4 address of a server that really is public, or something to ask about. Cost Explorer updates at least once a day, so tomorrow the usage types you removed (NatGateway-Hours, PublicIPv4:IdleAddress and so on) stop growing; if your bill is in US dollars on a local card, check the next statement too, since exchange rates and card fees come on top. When you no longer want the script and the saved reports, rm -rf ~/aws-cost-demo removes them; the cleanup itself left nothing else on your machine.
Next steps
- Get an email before the next surprise, not after it: set an AWS budget and cost alerts.
- Make the next investigation shorter by tagging what you create, so Cost Explorer can group by project: tag cloud resources so you know what costs what.
- If a NAT gateway was your biggest cost, learn when a private subnet needs one at all: understand AWS VPCs, subnets, route tables and NAT.
- Run
./find-waste.shon the first of every month and compare the output with the last one; a new line is always worth a question.
Related tutorials
- Tag cloud resources so you know what costs whatYou will have a four-key tagging scheme applied to every AWS resource through Terraform default_tags, a script that lists resources missing a tag, a tag policy ready for your organisation and cost allocation tags that split the bill by project.
- Store and serve files with Cloudflare R2 from a WorkerYou will build a Worker that uploads, downloads and lists files in an R2 bucket, with a size limit, a content-type allowlist, ETag and range support and a bearer token, test it locally with Wrangler and Vitest, and reach the same bucket through R2's S3-compatible API.
- Store container images in Amazon ECR with scanning and lifecycle policiesYou will have a private Amazon ECR repository with immutable tags and scan on push, an nginx image copied into it with crane, its vulnerability findings read from the CLI, a lifecycle policy that keeps the ten newest tagged images, and pull access granted to a second AWS account.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials