How to Automate AWS Inspector Findings Reports with a Single Lambda Function
A serverless solution that automates AWS Inspector vulnerability reporting across multi-account environments. A single Lambda function in the delegated admin account discovers member accounts, queries Inspector findings by severity and date range, generates per-account CSV reports in S3, and sends HTML email summaries via SES with pre-signed download links. EventBridge provides daily, weekly, or monthly scheduling with optional real-time alerts for Critical findings.
Overview
If you manage AWS Inspector across multiple accounts using a delegated admin, you've probably wished for a simple way to get a summary email of findings without logging into the console. This post shows how to do it with a single Lambda function — no frameworks, no complex infrastructure. Just deploy the function, run it, and get a formatted email with your Inspector findings.
We'll cover:
- A standalone Lambda function that queries Inspector, generates reports, and sends email
- Dynamic per-account email routing — no hardcoded recipient lists
- How to set up EventBridge to run it on a schedule
Prerequisites
- AWS Inspector enabled with a delegated admin account
- SES sender email verified (in sandbox mode, recipient emails must also be verified)
- An S3 bucket for storing reports (create one or use an existing bucket)

The Lambda Function
This single Python function does everything:
- Discovers member accounts via
ListMembers
- Resolves each account owner's email dynamically (security contact → Organizations account email fallback)
- Queries findings per account with severity and date filters
- Generates CSV reports and uploads to S3
- Sends a per-account HTML email to each owner, plus a combined report to the security team
Create a Lambda function with Python 3.12 runtime, 512 MB memory, 5-minute timeout, and paste this code:
import csvimport ioimport jsonimport loggingimport osfrom collections import Counterfrom datetime import datetime, timedelta, timezone
import boto3from botocore.config import Config
logger = logging.getLogger()logger.setLevel(logging.INFO)
RETRY_CONFIG = Config(retries={"max_attempts": 5, "mode": "adaptive"})SEVERITIES = ["CRITICAL", "HIGH", "MEDIUM", "LOW"]
def lambda_handler(event, context): # Configuration from environment variables bucket = os.environ["REPORT_BUCKET"] sender = os.environ["SENDER_EMAIL"] security_team = [e.strip() for e in os.environ.get("SECURITY_TEAM_EMAILS", "").split(",") if e.strip()] region = os.environ.get("AWS_REGION", "us-east-1")
# How far back to look — override via event payload lookback_days = int(event.get("lookback_days", 7)) report_type = event.get("report_type", "weekly")
now = datetime.now(timezone.utc) since = now - timedelta(days=lookback_days) date_str = now.strftime("%Y-%m-%d")
inspector = boto3.client("inspector2", config=RETRY_CONFIG) s3 = boto3.client("s3", config=RETRY_CONFIG) ses = boto3.client("ses", config=RETRY_CONFIG)
# Step 1: Discover member accounts and resolve owner emails account_emails = get_member_accounts_with_emails(inspector) if not account_emails: acct = boto3.client("sts").get_caller_identity()["Account"] account_emails = {acct: security_team[0] if security_team else None} logger.info("No member accounts, using current: %s", acct)
# Step 2: Query findings per account all_findings = [] for acct in account_emails: findings = get_findings(inspector, acct, since) all_findings.extend(findings) logger.info("Account %s (%s): %d findings", acct, account_emails[acct] or "no email", len(findings))
# Step 3: Generate and upload per-account CSV reports by_account = {} for f in all_findings: by_account.setdefault(f["account_id"], []).append(f)
s3_links = {} for acct, findings in by_account.items(): key = f"inspector-reports/inspector-{acct}-{date_str}.csv" upload_csv(s3, bucket, key, findings) s3_links[acct] = s3.generate_presigned_url( "get_object", Params={"Bucket": bucket, "Key": key}, ExpiresIn=604800 )
# Step 4: Send per-account emails to each owner subject = f"AWS Inspector Findings Report - {date_str}" new_findings = [f for f in all_findings if f["first_observed"] >= since.isoformat()] emails_sent = []
for acct, findings in by_account.items(): owner_email = account_emails.get(acct) if not owner_email: logger.warning("No email found for account %s, skipping", acct) continue acct_new = [f for f in findings if f["first_observed"] >= since.isoformat()] acct_links = {acct: s3_links[acct]} html = build_email(findings, acct_new, acct_links, date_str, report_type, region) ses.send_email( Source=sender, Destination={"ToAddresses": [owner_email]}, Message={"Subject": {"Data": f"{subject} - Account {acct}"}, "Body": {"Html": {"Data": html}}}, ) emails_sent.append({"account": acct, "email": owner_email})
# Step 5: Send combined report to security team if security_team and len(by_account) > 0: html = build_email(all_findings, new_findings, s3_links, date_str, report_type, region) ses.send_email( Source=sender, Destination={"ToAddresses": security_team}, Message={"Subject": {"Data": subject}, "Body": {"Html": {"Data": html}}}, )
return { "total_findings": len(all_findings), "new_findings": len(new_findings), "accounts": len(account_emails), "emails_sent": emails_sent, "reports": list(s3_links.keys()), }
# ---------------------------------------------------------------------------# Account discovery with dynamic email resolution# ---------------------------------------------------------------------------
def get_member_accounts_with_emails(inspector): """Discover member accounts and resolve owner emails dynamically.
Resolution order per account: 1. Alternate security contact (purpose-built for security notifications) 2. Organizations account email (the email used when the account was created)
This means no hardcoded email lists that go stale. """ orgs = boto3.client("organizations") account_client = boto3.client("account") accounts = {}
try: for page in inspector.get_paginator("list_members").paginate(onlyAssociated=True): for m in page.get("members", []): if m.get("status") != "ENABLED": continue aid = m["accountId"] accounts[aid] = resolve_account_email(aid, orgs, account_client) except Exception as e: logger.warning("Could not list members: %s", e)
return accounts
def resolve_account_email(account_id, orgs, account_client): """Resolve the best email for an account — security contact first, then org email.""" # Try alternate security contact first try: resp = account_client.get_alternate_contact( AccountId=account_id, AlternateContactType="SECURITY" ) email = resp["AlternateContact"]["EmailAddress"] logger.info("Account %s: using security contact %s", account_id, email) return email except Exception: pass
# Fall back to Organizations account email try: resp = orgs.describe_account(AccountId=account_id) email = resp["Account"]["Email"] logger.info("Account %s: using org account email %s", account_id, email) return email except Exception: pass
logger.warning("Account %s: no email found", account_id) return None
def get_findings(inspector, account_id, since): """Query findings for one account since a given date.""" criteria = { "awsAccountId": [{"comparison": "EQUALS", "value": account_id}], "findingStatus": [{"comparison": "EQUALS", "value": s} for s in ("ACTIVE", "SUPPRESSED")], "updatedAt": [{"startInclusive": since, "endInclusive": datetime.now(timezone.utc)}], } findings = [] try: for page in inspector.get_paginator("list_findings").paginate( filterCriteria=criteria, maxResults=100 ): findings.extend(page.get("findings", [])) except Exception as e: logger.error("Error querying %s: %s", account_id, e) return []
return [normalize(f) for f in findings]
def normalize(f): """Flatten an Inspector finding into a simple dict.""" vuln = f.get("packageVulnerabilityDetails", {}) resource = f.get("resources", [{}])[0] rec = f.get("remediation", {}).get("recommendation", {}) vid = vuln.get("vulnerabilityId", "")
return { "finding_id": f.get("findingArn", "").rsplit("/", 1)[-1], "severity": f.get("severity", "UNKNOWN"), "status": f.get("status", ""), "resource_type": resource.get("type", ""), "resource_id": resource.get("id", ""), "account_id": f.get("awsAccountId", ""), "region": resource.get("region", ""), "cve_id": vid if isinstance(vid, str) else ",".join(vid), "cvss_score": get_cvss(vuln), "inspector_score": f.get("inspectorScore", 0), "first_observed": f.get("firstObservedAt", "").isoformat() if hasattr(f.get("firstObservedAt", ""), "isoformat") else str(f.get("firstObservedAt", "")), "last_observed": f.get("lastObservedAt", "").isoformat() if hasattr(f.get("lastObservedAt", ""), "isoformat") else str(f.get("lastObservedAt", "")), "remediation": rec.get("text", ""), }
def get_cvss(vuln): """Get CVSS v3 score if available, otherwise first available.""" for s in vuln.get("cvss", []): if s.get("version", "").startswith("3"): return s.get("baseScore", 0) scores = vuln.get("cvss", []) return scores[0].get("baseScore", 0) if scores else 0
# ---------------------------------------------------------------------------# Report helpers# ---------------------------------------------------------------------------
def upload_csv(s3, bucket, key, findings): """Generate CSV and upload to S3.""" buf = io.StringIO() fields = [ "finding_id", "severity", "status", "resource_type", "resource_id", "account_id", "region", "cve_id", "cvss_score", "inspector_score", "first_observed", "last_observed", "remediation", ] writer = csv.DictWriter(buf, fieldnames=fields, extrasaction="ignore") writer.writeheader() writer.writerows(findings) s3.put_object(Bucket=bucket, Key=key, Body=buf.getvalue().encode(), ContentType="text/csv")
def build_email(all_findings, new_findings, s3_links, date_str, report_type, region): """Build HTML email body.""" sev_counts = Counter(f["severity"] for f in all_findings) new_counts = Counter(f["severity"] for f in new_findings) colors = {"CRITICAL": "#d32f2f", "HIGH": "#f57c00", "MEDIUM": "#fbc02d", "LOW": "#388e3c"}
# Top 5 resources by score top = [] seen = set() for f in sorted(all_findings, key=lambda x: x.get("inspector_score", 0), reverse=True): if f["resource_id"] and f["resource_id"] not in seen: seen.add(f["resource_id"]) top.append(f) if len(top) >= 5: break
# Build severity rows sev_rows = "" for sev in SEVERITIES: c = colors.get(sev, "#666") sev_rows += ( f'<tr><td style="padding:10px 16px;border-bottom:1px solid #eee">' f'<span style="background:{c};color:#fff;padding:3px 10px;border-radius:3px;' f'font-size:13px;font-weight:600">{sev}</span></td>' f'<td style="padding:10px;border-bottom:1px solid #eee;text-align:center;' f'font-size:20px;font-weight:700">{sev_counts.get(sev, 0)}</td>' f'<td style="padding:10px;border-bottom:1px solid #eee;text-align:center;' f'font-size:20px;font-weight:700;color:{c}">{new_counts.get(sev, 0)}</td></tr>' )
# Build top resources rows top_rows = "" for f in top: c = colors.get(f["severity"], "#666") rid = f["resource_id"][-55:] if len(f["resource_id"]) > 55 else f["resource_id"] top_rows += ( f'<tr><td style="padding:8px;border-bottom:1px solid #eee;font-family:monospace;' f'font-size:12px">{rid}</td>' f'<td style="padding:8px;border-bottom:1px solid #eee;text-align:center">' f'<span style="background:{c};color:#fff;padding:2px 8px;border-radius:3px;' f'font-size:12px">{f["severity"]}</span></td>' f'<td style="padding:8px;border-bottom:1px solid #eee;text-align:center;' f'font-weight:700">{f["inspector_score"]}</td>' f'<td style="padding:8px;border-bottom:1px solid #eee;font-family:monospace;' f'font-size:12px">{f["cve_id"]}</td></tr>' )
# Build download links dl_rows = "" for acct, url in s3_links.items(): dl_rows += ( f'<tr><td style="padding:8px;border-bottom:1px solid #eee;font-weight:600">' f'Account {acct}</td>' f'<td style="padding:8px;border-bottom:1px solid #eee">' f'<a href="{url}" style="color:#0073bb">📄 Download CSV</a></td></tr>' )
total = len(all_findings) new_total = len(new_findings) critical = sev_counts.get("CRITICAL", 0) high = sev_counts.get("HIGH", 0)
return f"""<!DOCTYPE html><html><head><meta charset="utf-8"></head><body style="margin:0;padding:0;background:#f4f6f9;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif"><table width="100%" style="background:#f4f6f9;padding:24px 0"><tr><td align="center"><table width="640" style="background:#fff;border-radius:8px;overflow:hidden;box-shadow:0 2px 8px rgba(0,0,0,0.08)">
<tr><td style="background:linear-gradient(135deg,#232f3e,#37475a);padding:28px 32px"> <h1 style="margin:0;color:#ff9900;font-size:22px">🛡️ AWS Inspector Findings Report</h1> <p style="margin:6px 0 0;color:#d5dbdb;font-size:14px">{report_type.title()} Report — {date_str}</p></td></tr>
<tr><td style="padding:24px 32px 8px"> <table width="100%"><tr> <td width="25%" style="padding:0 6px 0 0"><div style="background:#f4f6f9;border-radius:8px; padding:16px;text-align:center"><div style="font-size:28px;font-weight:800;color:#232f3e"> {total}</div><div style="font-size:11px;color:#666;text-transform:uppercase; letter-spacing:1px;margin-top:4px">Total</div></div></td> <td width="25%" style="padding:0 6px"><div style="background:#fef2f2;border-radius:8px; padding:16px;text-align:center"><div style="font-size:28px;font-weight:800;color:#d32f2f"> {critical}</div><div style="font-size:11px;color:#d32f2f;text-transform:uppercase; letter-spacing:1px;margin-top:4px">Critical</div></div></td> <td width="25%" style="padding:0 6px"><div style="background:#fff8e1;border-radius:8px; padding:16px;text-align:center"><div style="font-size:28px;font-weight:800;color:#f57c00"> {high}</div><div style="font-size:11px;color:#f57c00;text-transform:uppercase; letter-spacing:1px;margin-top:4px">High</div></div></td> <td width="25%" style="padding:0 0 0 6px"><div style="background:#e8f5e9;border-radius:8px; padding:16px;text-align:center"><div style="font-size:28px;font-weight:800;color:#388e3c"> {new_total}</div><div style="font-size:11px;color:#388e3c;text-transform:uppercase; letter-spacing:1px;margin-top:4px">New</div></div></td> </tr></table></td></tr>
<tr><td style="padding:20px 32px 8px"> <h2 style="margin:0 0 12px;font-size:16px;color:#232f3e">Findings by Severity</h2> <table width="100%" style="border:1px solid #eee;border-radius:6px;overflow:hidden"> <tr style="background:#f8f9fa"> <th style="padding:10px 16px;text-align:left;font-size:12px;color:#666">SEVERITY</th> <th style="padding:10px;text-align:center;font-size:12px;color:#666">TOTAL</th> <th style="padding:10px;text-align:center;font-size:12px;color:#666">NEW</th> </tr>{sev_rows} </table></td></tr>
<tr><td style="padding:20px 32px 8px"> <h2 style="margin:0 0 12px;font-size:16px;color:#232f3e">🔥 Top 5 Vulnerable Resources</h2> <table width="100%" style="border:1px solid #eee;border-radius:6px;overflow:hidden"> <tr style="background:#f8f9fa"> <th style="padding:8px;text-align:left;font-size:11px;color:#666">RESOURCE</th> <th style="padding:8px;text-align:center;font-size:11px;color:#666">SEVERITY</th> <th style="padding:8px;text-align:center;font-size:11px;color:#666">SCORE</th> <th style="padding:8px;text-align:left;font-size:11px;color:#666">CVE</th> </tr>{top_rows} </table></td></tr>
<tr><td style="padding:20px 32px 8px"> <h2 style="margin:0 0 12px;font-size:16px;color:#232f3e">📥 Download Reports</h2> <p style="margin:0 0 8px;font-size:12px;color:#666">Links expire in 7 days.</p> <table width="100%" style="border:1px solid #eee;border-radius:6px;overflow:hidden"> <tr style="background:#f8f9fa"> <th style="padding:8px;text-align:left;font-size:11px;color:#666">ACCOUNT</th> <th style="padding:8px;text-align:left;font-size:11px;color:#666">REPORT</th> </tr>{dl_rows} </table></td></tr>
<tr><td style="padding:24px 32px;border-top:1px solid #eee"> <p style="margin:0;font-size:12px;color:#999;text-align:center"> Generated by AWS Inspector Automated Reporting • {region}</p></td></tr>
</table></td></tr></table></body></html>"""IAM Role
Attach this policy to the Lambda execution role:
{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "inspector2:ListFindings", "inspector2:ListMembers" ], "Resource": "*" }, { "Effect": "Allow", "Action": [ "organizations:DescribeAccount", "account:GetAlternateContact" ], "Resource": "*" }, { "Effect": "Allow", "Action": "s3:PutObject", "Resource": "arn:aws:s3:::YOUR-BUCKET-NAME/inspector-reports/*" }, { "Effect": "Allow", "Action": "s3:GetObject", "Resource": "arn:aws:s3:::YOUR-BUCKET-NAME/inspector-reports/*" }, { "Effect": "Allow", "Action": "ses:SendEmail", "Resource": "*" }, { "Effect": "Allow", "Action": "sts:GetCallerIdentity", "Resource": "*" } ]}Environment Variables
Configure these on the Lambda function:
Variable | Example | Description |
|---|---|---|
REPORT_BUCKET | my-inspector-reports | S3 bucket for CSV reports |
SENDER_EMAIL | security@example.com | SES verified sender |
SECURITY_TEAM_EMAILS | secops@example.com,ciso@example.com | Security team gets the combined report across all accounts |
Note: Individual workload account owners are resolved automatically — the function looks up each account's alternate security contact first, then falls back to the Organizations account email. No hardcoded recipient lists that go stale when teams change.
Test It
Invoke the function from the AWS CLI:
aws lambda invoke \ --function-name InspectorReportFunction \ --payload '{"report_type": "weekly", "lookback_days": 7}' \ --cli-binary-format raw-in-base64-out \ response.json
cat response.jsonExample response:
{ "total_findings": 295, "new_findings": 42, "accounts": 3, "emails_sent": [ {"account": "111111111111", "email": "team-a@example.com"}, {"account": "222222222222", "email": "team-b@example.com"}, {"account": "333333333333", "email": "platform@example.com"} ], "reports": ["111111111111", "222222222222", "333333333333"]}Each account owner receives only their findings. The security team receives a combined report across all accounts.
You'll receive an HTML email with:
- Summary cards showing total, critical, high, and new finding counts
- Severity breakdown table with color-coded badges
- Top 5 most vulnerable resources ranked by Inspector score
- Pre-signed download links for each account's CSV report (valid 7 days, no console access needed)
Add a Schedule with EventBridge
To run the report automatically, create an EventBridge rule:
Weekly (every Monday at 9 AM UTC):
aws events put-rule \ --name inspector-weekly-report \ --schedule-expression "cron(0 9 ? * MON *)" \ --state ENABLED
aws events put-targets \ --rule inspector-weekly-report \ --targets '[{ "Id": "InspectorReport", "Arn": "arn:aws:lambda:us-east-1:ACCOUNT_ID:function:InspectorReportFunction", "Input": "{\"report_type\": \"weekly\", \"lookback_days\": 7}" }]'
aws lambda add-permission \ --function-name InspectorReportFunction \ --statement-id EventBridgeWeekly \ --action lambda:InvokeFunction \ --principal events.amazonaws.com \ --source-arn arn:aws:events:us-east-1:ACCOUNT_ID:rule/inspector-weekly-reportOther schedule examples:
Schedule | Cron Expression | Payload |
|---|---|---|
Daily at 9 AM UTC | cron(0 9 * * ? *) | {"report_type": "daily", "lookback_days": 1} |
Weekly on Monday | cron(0 9 ? * MON *) | {"report_type": "weekly", "lookback_days": 7} |
Monthly on the 1st | cron(0 9 1 * ? *) | {"report_type": "monthly", "lookback_days": 30} |
Optional: Real-Time Alerts for Critical Findings
Add an EventBridge rule that triggers on Inspector finding events:
aws events put-rule \ --name inspector-critical-alerts \ --event-pattern '{ "source": ["aws.inspector2"], "detail-type": ["Inspector2 Finding"], "detail": {"severity": ["CRITICAL", "HIGH"]} }' \ --state ENABLEDPoint this at a second Lambda (or an SNS topic) that sends an immediate email when a Critical or High finding is detected — so your team doesn't wait until the next scheduled report.
Cost
Component | Cost |
|---|---|
Lambda | ~30 seconds per run, well within free tier |
S3 | KB-sized CSV files, negligible |
SES | $0.10 per 1,000 emails |
EventBridge | Free for scheduled rules |
Total: less than $1/month for a weekly schedule across 10 accounts.
How Email Routing Works
A common concern with automated reporting is maintaining hardcoded email lists that go stale when teams change. This solution avoids that entirely by resolving recipient emails dynamically at runtime.
For each member account, the function checks two sources in order:
- Alternate security contact (
account:GetAlternateContact) — This is the purpose-built field in AWS for security notifications. If your organization populates this (recommended), it's the most accurate source.
- Organizations account email (
organizations:DescribeAccount) — Falls back to the email address used when the account was created. This always exists but may be a root account email or distribution list.
Account 111111111111 → Security contact: team-a-security@example.com ✓ (used) → Org email: team-a-root@example.com (skipped)
Account 222222222222 → Security contact: (not configured) → Org email: platform-team@example.com ✓ (used)
Account 333333333333 → Security contact: (not configured) → Org email: (lookup failed) → ⚠️ Skipped, logged as warningTip: Encourage workload account owners to set their alternate security contact. It can be done via the AWS console under Account Settings → Alternate Contacts, or programmatically:
aws account put-alternate-contact \ --account-id 111111111111 \ --alternate-contact-type SECURITY \ --name "Team A Security" \ --email-address team-a-security@example.com \ --phone-number "+1-555-0100" \ --title "Security Lead"Summary
With a single Lambda function and a few CLI commands, you get:
- Automated Inspector reports across all member accounts from a delegated admin
- Dynamic per-account email routing — no hardcoded lists, resolved from security contacts and Organizations
- Per-account CSV reports in S3 with pre-signed download links
- HTML email notifications with severity summary and top vulnerable resources
- Configurable schedule via EventBridge — daily, weekly, or monthly
- Optional real-time alerts for Critical and High findings
No frameworks, no complex infrastructure, no stale email lists. Just a Lambda function, an S3 bucket, and SES.
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article