AWS from zero · Part 4: Automation and serverless · Lesson 26 of 38 · about 50 minutes

Project: an unused-resource checker on Lambda

Part 4's project: Juniper & Rye gets a weekly report of what it pays for and doesn't use. A read-only Lambda function finds idle disks, IPs, orphaned snapshots, NAT gateways and logs that never expire, prices each from the Price List API, and runs every Monday from EventBridge Scheduler. An idle IP was $3.65 of the $3.78 found, the keep tag worked, and the one-time schedule ran 50 seconds late and then deleted itself.

By the end you'll know

  • The five kinds of waste that quietly bill an AWS account, and what each costs
  • How to find each with read-only calls, and price it from the Price List API rather than from memory
  • Why a checker should report and never delete, and how a keep tag lets people opt things out
  • How EventBridge Scheduler runs a function once or every week, in your own time zone
  • How the parts of Part 4 fit together: boto3, Lambda, roles, SNS and a schedule

Before you start

  • You need: the juniper-rye profile, signed in, and Lesson 20's virtual environment. This project uses Lesson 21's function and role, and Lesson 23's SNS topic.
  • The script: checker-lab.py from the practice folder's lesson-26. Everything it creates is named jr-lesson26-* and tagged lesson=26, and its delete step removes it, planted waste included.
  • How the script talks to AWS: only through boto3, as in Lessons 20 to 25.
  • To see every call the script makes that changes something, put SHOW=1 in front of any step. The "By hand" section has the same calls with the AWS CLI.
  • Where you run things: your own machine, labeled (Your machine).
  • Every output below is from a real run on November 15, 2026.

Planted waste bills until you delete it

The lab leaves an idle public IP address and three small disks in your account on purpose, about half a cent an hour together. Run delete in the same sitting. If you stop partway, the weekly schedule will still run the checker on Monday, and the waste will still be billing; check lists anything left.

The short version

  • Waste is anything billed by the hour or the gigabyte that nothing uses: idle IPs, disks attached to nothing, snapshots of deleted disks, NAT gateways, logs kept forever.
  • A checker finds them with describe calls, which only read, and prices them from the Price List API.
  • It reports; people decide. Its role can't delete anything, and a keep=true tag takes a resource off the list.
  • EventBridge Scheduler runs it: at() for once, cron() for every Monday at 8am in your time zone.

What this lesson costs

PartCost, in us-east-2
The idle Elastic IP$0.005 an hour
Three 1 GiB gp3 disks$0.08 per GB a month each, by the second
The snapshot of an empty diskNext to nothing: you pay for data stored
The checker, its schedules, its topicInside the free allowances
This lesson, deleted within the hourAbout half a cent, from credits

The bill nobody reads

Most surprise AWS bills aren't one big mistake. They're small things left behind: a disk kept after its server was deleted, an IP address reserved for a test, a backup of something long gone, a log group that has kept every line since the day it was made. Each is cents or a few dollars a month, nobody owns it, and it bills forever.

Waste in an AWS account is the bakery's walk-in fridge. Nobody throws out the tub of cream from last month's special because nobody remembers whose it is, and the fridge is always full. A weekly check of what's in it, with a "keep" label for anything that should stay, keeps the space for what's needed.
WasteHow it happensHow the checker finds it
A disk attached to nothingA server is deleted but its EBS disk is kept (Lesson 16)A volume in state available
An idle public IPAn Elastic IP reserved and never attached, or left after a server goesAn address with no association
A snapshot of a deleted diskBackups outlive the disk they were taken fromIts disk no longer exists, and no image uses it
A NAT gatewayMade for private subnets (Lesson 8), billed hourly even with no trafficAny in state available
Logs kept foreverLog groups never expire unless told toNo retention set

What each kind costs here

(Your machine)

BASH
cd ~/Apps/aws-practice/lesson-26
source ../lesson-20/.venv/bin/activate
python checker-lab.py fence
OUTPUT
== Can this account do the lab in us-east-2?
  EC2 (disks, IPs, snapshots)    allowed
  Lambda                         allowed
  EventBridge Scheduler          allowed
  SNS                            allowed
  Lambda concurrency limit: 10 (the checker needs 1)
== What each kind of waste costs in us-east-2 (from the Price List API)
  EBS gp3 disk, per GB a month               $0.08 per GB-Mo
  EBS gp2 disk, per GB a month               $0.1 per GB-Mo
  EBS snapshot, per GB a month               $0.05 per GB-Mo
  Idle public IPv4 address, per hour         $0.005 per Hrs, or $3.65 a month
  NAT gateway, per hour (data extra)         $0.045 per Hrs, or $32.85 a month
  CloudWatch Logs storage, per GB a month    $0.03 per GB-Mo
== The planted waste: three 1 GiB disks and one idle IP, about $0.0053 an hour
  the checker, its schedule and its report: inside the free allowances

Every price came from the Price List API, not from this page. Prices differ by Region and change over time, so a checker that hardcodes them goes stale quietly. The script looks each one up by its usage type, such as USE2-PublicIPv4:IdleAddress, the same name that appears on the bill. The USE2 is us-east-2.

A NAT gateway at $32.85 a month before any data is the biggest single item here. A forgotten one in a test VPC costs more than everything else on this list together. An idle IP is the most common: AWS charges for every public IPv4 address, in use or not, and an idle one is the easiest to forget.

Plant some waste

BASH
python checker-lab.py plant
OUTPUT
== Disks attached to nothing (1 GiB gp3 each, in us-east-2a)
  vol-00a5ccdaf5007c545  jr-lesson26-forgotten
  vol-0e53f351bd84cffdd  jr-lesson26-kept, tagged keep=true: the checker should skip it
== A snapshot of a disk that's since been deleted
  snap-01ef8a69747d693e0  snapshot of vol-0a1916164959f6107, done in 36 seconds; then the disk was deleted
== A public IP address held but attached to nothing
  eipalloc-08545f11fa0d28926  an Elastic IP, billed by the hour while it's idle
== A log group that keeps everything forever
  /jr-lesson26/forgotten  retention: never expires

One of each kind except a NAT gateway, which would cost far more than the rest, plus one disk tagged keep=true. That tag is how a person says "yes, this is idle, and it should stay", perhaps a disk kept for an audit. The checker should leave it off its list.

The checker

The unused-resource checkerEventBridge Scheduler starts the checker, a Lambda function, every Monday at 8am. The checker reads from EC2, for disks, IPs, snapshots and NAT gateways, and from CloudWatch Logs, for log groups, using describe calls only. It sends its report to an SNS topic, which can email it. It can't change or delete anything.EventBridge SchedulerMondays, 8amstartsThe checkerLambda, read-only roleEC2disks, IPs, snapshots, NAT gatewaysCloudWatch Logslog groups and their retentiondescribedescribethe reportReport topicSNS, then emailDashed lines only read. The checker can look and report; it can't change or delete.
Part 4 in one project: a schedule, a function with a narrow role, describe calls through boto3, and a topic for the result.

In the console: Lambda > Create function, then Configuration > Environment variables for the prices and the topic.

BASH
python checker-lab.py build
OUTPUT
== A topic for the report
== The checker's role: read-only. It can look, write its logs and send its report. It can't delete.
== The checker: Python 3.13 on Arm, 256 MB, 60-second timeout
  active after 10 seconds, 3 retries for the new role
== jr-lesson26-checker: python3.13, 256 MB, timeout 60 s, package 1,927 bytes
  prices it was given: idle_ip $0.005, log_storage $0.03, nat $0.045, snapshot $0.05, volume_gp2 $0.1, volume_gp3 $0.08
  report topic: jr-lesson26-report; email subscriptions: 0 confirmed, 0 pending

The build step looked the prices up on your machine and gave them to the function as an environment variable, so each run doesn't have to call the Price List API. Run build again after deleting the function and it picks up any new prices.

The heart of the checker is a handful of describe calls. Here are the first two:

PYTHON
def handler(event, context):
    found, skipped = [], []

    def add(kind, ident, detail, monthly, tags=None):
        (skipped if kept(tags) else found).append(
            {"kind": kind, "id": ident, "detail": detail, "monthly": round(monthly, 4)})

    volume_ids = set()
    for v in pages(ec2, "describe_volumes", "Volumes"):
        volume_ids.add(v["VolumeId"])
        if v["State"] == "available":
            price = PRICES.get("volume_" + v["VolumeType"], PRICES["volume_gp3"])
            add("disk", v["VolumeId"], "%d GiB %s, attached to nothing, %d days old" % (
                v["Size"], v["VolumeType"], days_since(v["CreateTime"])), v["Size"] * price, v.get("Tags"))

    for a in ec2.describe_addresses()["Addresses"]:
        if "AssociationId" not in a:
            add("ip", a.get("AllocationId", "?"), "Elastic IP attached to nothing",
                PRICES["idle_ip"] * HOURS, a.get("Tags"))
PartWhy
pages(), a paginatorAn account with hundreds of disks or snapshots returns them a page at a time (Lesson 20)
volume_idsCollected while listing disks, so a snapshot whose disk isn't in it is an orphan
kept()Anything tagged keep=true goes on the skipped count, not the list
A cap of 20 linesA big account gets the 20 costliest items and a total for the rest, not a wall of text
The log lineOne line of counts per run, so you can see runs happened without reading reports

The role can describe and nothing more. Its policy is the whole security story of this project:

JSON
{"Effect": "Allow", "Resource": "*", "Action": [
    "ec2:DescribeVolumes", "ec2:DescribeAddresses", "ec2:DescribeSnapshots",
    "ec2:DescribeImages", "ec2:DescribeNatGateways", "logs:DescribeLogGroups"]},
{"Effect": "Allow", "Action": ["logs:CreateLogStream", "logs:PutLogEvents"],
 "Resource": "arn:aws:logs:us-east-2:111122223333:log-group:/aws/lambda/jr-lesson26-checker:*"},
{"Effect": "Allow", "Action": "sns:Publish",
 "Resource": "arn:aws:sns:us-east-2:111122223333:jr-lesson26-report"}

Describe calls in EC2 don't support narrowing to particular resources, so Resource is * for them. That's acceptable because they only read. If a bug, or someone editing the code, tried to delete a disk, AWS would refuse.

Run it by hand

BASH
python checker-lab.py run
OUTPUT
== The checker's report (1.6 seconds)
  | Unused resources in us-east-2, 2026-11-15 16:20 UTC
  | 
  | $   3.65 a month  ip       eipalloc-08545f11fa0d28926
  |                     Elastic IP attached to nothing
  | $   0.08 a month  disk     vol-00a5ccdaf5007c545
  |                     1 GiB gp3, attached to nothing, 0 days old
  | $   0.05 a month  snapshot snap-01ef8a69747d693e0
  |                     snapshot of a 1 GiB disk that's gone, 0 days old; cost is at most this
  | $   0.00 a month  logs     /jr-lesson26/forgotten
  |                     logs kept forever, 0 bytes stored, 0 days old
  | 
  | Total: $3.78 a month, 4 items
  | Skipped, tagged keep=true: 1
  | This report only lists. Nothing was changed or deleted.
In the reportShows
The idle IP: $3.65 of $3.78Sorting by cost puts the one thing worth acting on first
Skipped: 1The keep=true disk was left off, as it should be
The snapshot, "at most"Snapshots bill for data stored, not disk size. An empty disk's snapshot costs almost nothing; $0.05 is the ceiling.
The log group, 0 bytesCloudWatch doesn't update a log group's stored size straight away. The 50 lines written are there; the figure catches up later.
Only the planted itemsThis account had no waste of its own: earlier lessons' delete steps did their job

Four items, and only one matters. That's typical. A report sorted by cost, with a total, lets someone spend two minutes on it on a Monday morning: release the IP, and leave the rest until it grows. A report in creation order, or one that lists every log group equally, gets ignored by the third week.

The checker deleted nothing, and that's deliberate. "Attached to nothing" doesn't mean "not needed": a disk may be detached for maintenance, an IP reserved for a server being rebuilt, a snapshot kept for a legal hold. A checker can see that something is idle; only a person knows why. The safer pattern when deleting is wanted is in "Spot the problem" below.

Put it on a schedule

In the console: Amazon EventBridge > Scheduler > Schedules > Create schedule.

BASH
python checker-lab.py schedule
OUTPUT
== The scheduler's role: it can start the checker, and nothing else
== A one-time schedule: at(2026-11-15T16:23:00) UTC, deleted by AWS once it has run
  created after 10 seconds, 3 retries for the new role
== A weekly schedule: cron(0 8 ? * MON *) in America/New_York (every Monday, 8am), within a 15-minute window
== Waiting for the one-time run (nothing on this machine starts it)
  now 16:20:21 UTC; due 16:23 UTC
  it ran at 16:23:50 UTC, 50 seconds after it was due
  it logged: {"source": "one-time schedule", "found": 4, "skipped": 1, "monthly_usd": 3.78}
== Schedules now
  jr-lesson26-once       gone: it ran once, and AWS deleted it
  jr-lesson26-weekly     cron(0 8 ? * MON *), enabled
SettingIsIn the lab
at()Run once, at this time3 minutes ahead, in UTC
cron()Minutes, hours, day of month, month, day of week, year0 8 ? * MON *: 8:00 every Monday
Time zoneThe zone the expression is read in, daylight saving includedAmerica/New_York
Flexible windowRun any time within this many minutes, to spread loadOff for the one-time run, 15 minutes for the weekly
After completionWhat happens to a one-time schedule once it's runDELETE: AWS removed it
Retry policyHow often to try again if the function can't be started2 retries, within an hour

The one-time run started 50 seconds after it was due, with nothing on your machine involved. Scheduler doesn't start schedules to the second; for a weekly report, a minute either way doesn't matter. Then it deleted the schedule itself, so one-time jobs don't pile up.

The time zone matters more than it looks. cron(0 8 ? * MON *) in UTC would run at 3am or 4am in New York, depending on the season, because UTC has no daylight saving. With the time zone set, Scheduler keeps it at 8am local all year. In cron, ? means "any" for the day of month, because you can't set both a day of month and a day of week.

Scheduler needs its own role to start the function, the same pattern as Step Functions in Lesson 24. Its trust policy accepts only scheduler.amazonaws.com, and only on behalf of this account (the aws:SourceAccount condition), and it can start this one function. The new role took 10 seconds and 3 retries before Scheduler accepted it, as Lambda's did in build.

Lesson 23 used EventBridge rules to route events. Rules can also run on a timer, but Scheduler is the newer service for that: it handles time zones, one-time runs and retries, and its free allowance is 14 million runs a month.

Take it down

In the console: delete the schedule, the function, both roles, the topic and both log groups; then release the Elastic IP, and delete the snapshot and both disks in EC2.

BASH
python checker-lab.py delete
OUTPUT
== Deleting schedule jr-lesson26-weekly
== Deleting the checker
== Deleting role jr-lesson26-checker-role
== Deleting role jr-lesson26-scheduler-role
== Deleting the report topic and its subscriptions
== Deleting log group /aws/lambda/jr-lesson26-checker
== Deleting log group /jr-lesson26/forgotten
== Releasing Elastic IP eipalloc-08545f11fa0d28926
== Deleting snapshot snap-01ef8a69747d693e0
== Deleting disk vol-0e53f351bd84cffdd (jr-lesson26-kept)
== Deleting disk vol-00a5ccdaf5007c545 (jr-lesson26-forgotten)
== Anything left from Lesson 26
  nothing: all clear

delete found the planted waste by its lesson=26 tag, not by remembering IDs, so it works even if a step was run twice. The same habit is what makes real cleanup safe: tag what you create, and delete by tag.

By hand: the same checks with the AWS CLI

(Your machine) The four checks, as one-liners:

BASH
export AWS_PROFILE=juniper-rye AWS_REGION=us-east-2

aws ec2 describe-volumes --filters Name=status,Values=available \
  --query "Volumes[].[VolumeId,Size,VolumeType,CreateTime]" --output table

aws ec2 describe-addresses --query "Addresses[?AssociationId==null].[AllocationId,PublicIp]" --output table

aws ec2 describe-nat-gateways --filter Name=state,Values=available \
  --query "NatGateways[].[NatGatewayId,CreateTime]" --output table

aws logs describe-log-groups --query "logGroups[?retentionInDays==null].[logGroupName,storedBytes]" --output table

Orphaned snapshots take two lists compared, which is why the checker is code. One price, from the Price List API:

BASH
aws pricing get-products --region us-east-1 --service-code AmazonVPC \
  --filters Type=TERM_MATCH,Field=usagetype,Value=USE2-PublicIPv4:IdleAddress \
  --query "PriceList[0]" --output text

A weekly schedule, once the function and the scheduler's role exist:

BASH
ACCOUNT=$(aws sts get-caller-identity --query Account --output text)
aws scheduler create-schedule --name jr-lesson26-weekly \
  --schedule-expression "cron(0 8 ? * MON *)" --schedule-expression-timezone America/New_York \
  --flexible-time-window Mode=FLEXIBLE,MaximumWindowInMinutes=15 \
  --target "Arn=arn:aws:lambda:us-east-2:$ACCOUNT:function:jr-lesson26-checker,RoleArn=arn:aws:iam::$ACCOUNT:role/jr-lesson26-scheduler-role,Input='{\"source\":\"weekly schedule\"}'"

In real systems

  • Check every Region you use, and every account. This checker looks at one Region; waste in a Region nobody looks at is the most forgotten of all. With AWS Organizations (Lesson 36), one checker assumes a read-only role in each account.
  • AWS has free tools for this too: Trusted Advisor's cost checks, Compute Optimizer, and Cost Optimization Hub. Use them, and keep a checker of your own for the rules that are yours, like the keep tag.
  • Every resource has an owner tag, so the report can say whose the waste is (Lesson 37).
  • The report goes where people already look, a team channel or a weekly email, sorted by cost, with a total.
  • Deleting, if done at all, is slow and reversible: tag first, wait, snapshot, then delete what nobody claimed.
  • Log groups get a retention when they're made, in Terraform or CloudFormation (Part 5), so they never need finding.
  • The budget alarm from Lesson 2 stays on; a checker finds known kinds of waste, an alarm catches everything else.

Spot the problem

Work out what's wrong before you read the explanation.

"The cleanup job deleted the restore disk." A team extends its checker to delete any disk attached to nothing, to save someone the Monday chore. Three weeks later, a database server is being repaired: its disk was detached for an hour to be checked, the job ran in that hour, and the disk was gone. What's wrong? "Attached to nothing" was treated as "not needed", and the job deleted on a single look, with no owner, no waiting period and no way back. The fix: report only, or delete in stages: tag the disk as a candidate, wait a week, skip anything tagged keep=true or claimed, snapshot it, and only then delete; keep the deleting role separate from the reporting one. Then check: detach a test disk and run the job; is the disk tagged as a candidate rather than deleted, and is there a snapshot before anything is removed?

Keep this

RememberWhy
Five kinds of quiet wasteIdle IPs, loose disks, orphaned snapshots, NAT gateways, logs kept forever
Price from the Price List APIPrices differ by Region and change
Sort by cost, show a totalThe idle IP was $3.65 of $3.78
Read-only role, report onlyIdle doesn't mean unneeded; a person decides
A keep tagLets people take things off the list
cron() with a time zone8am local all year, not 8am UTC
at() with DELETEOne-time jobs clean themselves up
Delete by tagFinds everything, even after a step ran twice

Where you are now

That's Part 4 done. Juniper & Rye has a weekly report of what it pays for and doesn't use: a Lambda function with a read-only role, prices from the Price List API, a keep tag, a topic for the report, and a schedule that runs it at 8am every Monday. It found an idle IP that would have cost $3.65 a month, skipped the disk marked keep, and ran by itself 50 seconds after it was due. Part 5 moves to containers and infrastructure as code, starting with Lesson 27: ECR and ECS on Fargate.

Check yourself

  1. Which planted item made up most of the report's monthly total?

  2. Why does the checker look prices up instead of hardcoding them?

  3. Why can't the checker delete a disk, even if its code is changed?

  4. The report said the log group held 0 bytes after 50 lines were written. Why?

  5. Why does the weekly schedule set a time zone?

  6. What happened to the one-time schedule after it ran?

  7. Why is the snapshot's cost shown as at most $0.05?

Key terms

  • Unused resource: anything billed by time or size that nothing uses.
  • Elastic IP: a public IPv4 address you hold until you release it, billed hourly.
  • Orphaned snapshot: a snapshot whose disk no longer exists.
  • Retention: how long a log group keeps its logs; none set means forever.
  • Price List API: AWS's service for looking up current prices by Region and usage type.
  • Usage type: the name a charge has on the bill, like USE2-PublicIPv4:IdleAddress.
  • Keep tag: a tag, here keep=true, that takes a resource off the checker's list.
  • EventBridge Scheduler: AWS's service for running a target once or on a repeating schedule.
  • Cron expression: a pattern of minutes, hours, days and months saying when to run.
  • Flexible time window: a span within which a schedule may run, to spread load.

Go deeper