惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

The Hacker News
The Hacker News
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
雷峰网
雷峰网
人人都是产品经理
人人都是产品经理
Recent Announcements
Recent Announcements
D
DataBreaches.Net
P
Proofpoint News Feed
V
Visual Studio Blog
J
Java Code Geeks
Recorded Future
Recorded Future
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
F
Full Disclosure
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
The GitHub Blog
The GitHub Blog
Engineering at Meta
Engineering at Meta
C
Cybersecurity and Infrastructure Security Agency CISA
V
Vulnerabilities – Threatpost
罗磊的独立博客
Jina AI
Jina AI
博客园 - 【当耐特】
C
CERT Recently Published Vulnerability Notes
G
GRAHAM CLULEY
Y
Y Combinator Blog
L
LangChain Blog
L
LINUX DO - 热门话题
宝玉的分享
宝玉的分享
月光博客
月光博客
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
H
Help Net Security
云风的 BLOG
云风的 BLOG
C
CXSECURITY Database RSS Feed - CXSecurity.com
博客园_首页
A
About on SuperTechFans
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Latest news
Latest news
T
Threatpost
T
Tenable Blog
有赞技术团队
有赞技术团队
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Stack Overflow Blog
Stack Overflow Blog
C
Cisco Blogs
C
Check Point Blog
T
Tor Project blog
T
Threat Research - Cisco Blogs
T
The Exploit Database - CXSecurity.com
S
Schneier on Security
美团技术团队
I
Intezer
S
Securelist
AWS News Blog
AWS News Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
How I Built a Serverless Scanner to Find (and Kill) Zombie AWS Resources
Roberto Belo · 2026-05-14 · via DEV Community

Every AWS account has zombies.

Not the fun kind. The kind that silently drain your budget while nobody's looking. An EBS volume that was attached to an instance you terminated six months ago. A NAT Gateway routing traffic for a VPC that no longer has any workloads. A Transfer Family SFTP server that was set up for a migration, used once, and forgotten.

I've audited enough accounts to know this isn't an edge case. It's the default. Infrastructure outlives the context that created it. Projects get cancelled, teams move on, POCs never get torn down. But the meter keeps running.

AWS Cost Explorer will tell you what you're spending. It won't tell you why (or whether anyone still needs it). So I built a tool that answers that question.

aws-zombie-hunter is an open-source, container-based Lambda that scans an AWS account for orphaned resources across seven categories, estimates the monthly waste, and writes a structured JSON report to S3.

This article walks through the architecture, the scanner design pattern, the testing strategy, and the things I learned along the way.

Why a Lambda (and not a CLI)

The first version of this in my head was a CLI script. Run it locally, pipe output to a file, done. But that falls apart quickly for anything beyond a hobby project.

A CLI means someone has to remember to run it. It needs credentials on a developer's machine. It doesn't scale to multiple accounts. And when you want to track zombie trends over time (are we getting better at cleaning up, or worse?), you need persistent storage and a schedule.

A Lambda solves all of that. EventBridge triggers it on a schedule (daily, weekly, whatever makes sense). Results go to S3 with a date-based key, so you get historical data for free. IAM handles permissions (read-only, no credentials on laptops). And it costs roughly $0.10/month to run (which is ironic, given that it typically finds hundreds of dollars in waste).

I went with a container-based Lambda (Python 3.12 on the official AWS base image) instead of a zip deployment. The reason is practical: moto, boto3, and the rest of the test/dev tooling push the package well past Lambda's 250 MB zip limit. A container image gives you up to 10 GB and a clean Dockerfile to reproduce the build. It also shows Docker competence in a portfolio project, which doesn't hurt.

The scanner architecture

The core design problem was: how do you scan seven different AWS resource types without the codebase turning into a 500-line if/elif chain?

The answer is a scanner registry with a common interface. Every scanner is a subclass of BaseScanner, which defines the contract:

from abc import ABC, abstractmethod

class BaseScanner(ABC):
    VERSION: str = "1.0.0"

    def __init__(self, session: boto3.Session, regions: list[str]):
        self.session = session
        self.regions = regions

    @property
    @abstractmethod
    def resource_type(self) -> ResourceType:
        ...

    @abstractmethod
    def scan(self) -> list[ZombieResource]:
        ...

Enter fullscreen mode Exit fullscreen mode

Each scanner knows how to detect zombies for one resource type. The EIPScanner looks for Elastic IPs not associated with a running instance. The EBSScanner finds unattached volumes and snapshots not linked to any AMI. The TransferFamilyScanner checks for SFTP servers with zero configured users (or zero file transfers in the last 30 days via CloudWatch metrics).

A registry module auto-discovers all BaseScanner subclasses and runs them in parallel using ThreadPoolExecutor. This keeps the handler clean:

def lambda_handler(event, context):
    config = load_config()
    session = boto3.Session()

    scanners = ScannerRegistry.discover()
    results = ScannerRegistry.run_all(
        scanners, session, config.regions
    )

    report = ScanResult(
        zombies=results.zombies,
        errors=results.errors,
        regions_scanned=config.regions,
        # ...
    )

    save_to_s3(report, config.bucket, config.prefix)

    if config.sns_topic:
        notify(report.summary(), config.sns_topic)

    return report.summary()

Enter fullscreen mode Exit fullscreen mode

Adding a new scanner means creating a new file in src/scanner/, subclassing BaseScanner, and implementing scan(). The registry picks it up automatically. No handler changes, no configuration updates.

What it scans (and how it decides what's "dead")

Seven resource types, each with specific detection criteria:

EC2 Instances — state is stopped. A stopped instance still incurs EBS storage costs for its root and attached volumes, and it's almost always a forgotten resource.

EBS Volumes — not attached to any instance. The volume exists, it has data (maybe), but nothing is using it. Also catches old snapshots not linked to any active AMI.

Elastic IPs — allocated but not associated with a running instance. AWS charges for idle EIPs ($3.60/month each since the February 2024 pricing change), so even a handful adds up.

Transfer Family Servers — SFTP/FTPS servers with zero configured users, or (via CloudWatch) zero FilesIn/FilesOut in the last 30 days. These are expensive ($219/month base cost for a public endpoint) and easy to forget after a one-time migration.

RDS Instances — state is stopped. AWS automatically restarts stopped RDS instances after 7 days (a detail many people miss), so a "stopped" RDS instance is either very recent or has been cycling through stop/auto-restart for months.

Load Balancers — ALBs and NLBs with zero healthy targets. The load balancer exists, it's routing nothing, and it's costing you ~$16/month plus hourly charges.

NAT Gateways — present in a subnet but no active routes point to them in the route table. At $32/month plus data processing charges, an orphaned NAT Gateway is one of the more expensive zombies.

Cost estimation: good enough, not perfect

Every zombie gets an estimated_monthly_cost_usd field. This isn't meant to match your bill to the cent. It's meant to make you go "wait, we're wasting how much?"

The estimation uses a static prices.json file with base prices per resource type and regional multipliers. A stopped t3.medium in us-east-1 gets a different EBS cost estimate than one in ap-southeast-1. It's approximate, but consistently approximate (and that's what matters for prioritization).

I considered pulling real-time pricing from the AWS Price List API, but it's slow, complex, and overkill for a scanner that runs once a day. The static file approach means the Lambda has no external dependencies at scan time (no API calls that could fail or add latency) and the prices are easy to update with a PR.

The S3 output format

Reports land in S3 with a date-based key pattern: {prefix}{YYYY-MM-DD}.json. Running the scan twice on the same day overwrites the previous result (last scan wins, by design).

The JSON structure is designed for downstream consumption. A future report-generator Lambda (not built yet) can read these files to produce trend charts. The format includes a top-level summary (total zombies, total waste, breakdown by severity and type) plus the full list of zombie resources with all the metadata you'd need to act on them:

{
  "scan_id": "a1b2c3d4-...",
  "account_id": "123456789012",
  "scan_timestamp": "2026-05-12T06:00:12Z",
  "regions_scanned": ["us-east-1", "eu-west-1", "eu-central-1"],
  "total_monthly_waste_usd": 1247.60,
  "total_zombies": 12,
  "summary": {
    "by_severity": { "low": 3, "medium": 5, "high": 3, "critical": 1 },
    "by_type": {
      "ec2_instance": 2,
      "ebs_volume": 4,
      "elastic_ip": 2,
      "transfer_server": 1
    }
  },
  "zombies": [
    {
      "resource_type": "transfer_server",
      "resource_id": "s-0abc1234def567890",
      "region": "eu-west-1",
      "reason": "Transfer Family server with 0 configured users",
      "estimated_monthly_cost_usd": 219.00,
      "severity": "high",
      "age_days": 427,
      "recommended_action": "Review and terminate if unused"
    }
  ],
  "errors": []
}

Enter fullscreen mode Exit fullscreen mode

The errors array is important. If one scanner fails (say, you don't have transfer:List* permissions), the Lambda doesn't crash. It logs the error, adds it to the report, and continues with the remaining scanners. Partial results are better than no results.

Testing with moto (62 tests, 90% coverage)

This project has a test suite I'm actually proud of. Every scanner has its own test file, every detection rule has a positive and negative test case, and the full handler flow is integration-tested end to end.

The secret weapon is moto, which mocks AWS services in-process. No LocalStack, no Docker containers for tests, no real AWS calls. You decorate a test with @mock_aws, create fake resources, run the scanner, and assert what it found:

@mock_aws
def test_finds_unattached_ebs_volumes():
    ec2 = boto3.client("ec2", region_name="us-east-1")
    volume = ec2.create_volume(
        AvailabilityZone="us-east-1a",
        Size=100,
        VolumeType="gp3"
    )

    scanner = EBSScanner(
        session=boto3.Session(), regions=["us-east-1"]
    )
    zombies = scanner.scan()

    assert len(zombies) == 1
    assert zombies[0].resource_id == volume["VolumeId"]
    assert zombies[0].estimated_monthly_cost_usd > 0


@mock_aws
def test_ignores_attached_volumes():
    # Create instance, volume gets attached automatically
    ec2 = boto3.client("ec2", region_name="us-east-1")
    ec2.run_instances(
        ImageId="ami-test",
        InstanceType="t3.medium",
        MinCount=1, MaxCount=1
    )

    scanner = EBSScanner(
        session=boto3.Session(), regions=["us-east-1"]
    )
    zombies = scanner.scan()

    # Root volume is attached, so no zombies
    assert len(zombies) == 0

Enter fullscreen mode Exit fullscreen mode

This pattern scales. Each scanner gets a test_finds_* and test_ignores_* pair at minimum, plus edge cases (multi-region, tagged resources, empty regions). The handler integration test mocks S3 and SNS too, verifying the full flow from event to stored report.

Quality gates: mypy --strict with zero errors, ruff for linting and formatting, pytest --cov for the 90% coverage floor. All of this runs in CI before any merge.

Deployment: SAM with a two-phase pattern

The infrastructure is defined in a SAM template.yaml that provisions:

  • The Lambda function (container image from ECR)
  • An S3 bucket for reports
  • An EventBridge rule for scheduled scanning
  • IAM roles with read-only permissions (EC2, EBS, ELB, RDS, Transfer, CloudWatch, S3 write to the report bucket)
  • An optional SNS topic for notifications

Deployment is sam build && sam deploy --guided. The ECR repository for the container image needs to exist before the first deploy, so there's a bootstrapping step documented in the README.

One thing I'd flag: the IAM policy is deliberately read-only for all scanned services. The tool finds zombies. It doesn't kill them. That's a conscious decision (you don't want an automated tool terminating resources without human review, even if they look dead).

What I learned (and what I'd change)

ThreadPoolExecutor was the right call. Scanners are I/O-bound (API calls to AWS), so threading gives you near-linear speedup across scanners. The full scan across seven resource types and three regions takes about 45 seconds. Without parallelism, it was closer to three minutes.

Static pricing beats dynamic pricing for this use case. I initially tried to pull real-time prices from the AWS Price List Bulk API. The API is slow, the response format is bizarre (nested JSON with string-encoded numbers), and the latency added 10+ seconds per scan. A prices.json file that gets updated once a quarter is simpler and good enough.

The scanner registry pattern pays for itself. When I wanted to add NAT Gateway scanning after the initial six scanners, it took exactly one new file and one test file. Zero changes to the handler, zero changes to the registry. That's the kind of extensibility that makes a project maintainable.

Error isolation is non-negotiable. Early versions crashed the entire Lambda when one scanner hit a permissions error. Now each scanner runs in its own try/except block, and failures get logged and recorded without affecting the others. In multi-account setups where IAM policies vary, this is essential.

What's next: a report-generator Lambda that reads the JSON files from S3 and produces charts (cost trends over time, breakdown by resource type, worst offenders). Same bucket, separate function, clean separation of concerns. That's a v2 project.

Try it

The repo is at github.com/biscolab/aws-zombie-hunter. Deploy it, run it once, and I'd be surprised if it doesn't find at least a couple of zombies you didn't know about.

The Lambda costs pennies to run. The zombies it finds cost a lot more.


I also wrote a shorter take on this problem on LinkedIn — the "why" rather than the "how". If you're curious about the project or have ideas for additional scanners, drop a comment or open an issue on the repo.