New Delhi, India
ProjectsApril 1, 2025

Automating Cloud Inventory Across 400+ AWS Accounts

AWS STS
Amazon Aurora
HashiCorp Vault
Kubernetes
FinOps
Automating Cloud Inventory Across 400+ AWS Accounts
In a decentralized enterprise cloud estate spanning more than 400 AWS member accounts, answering the fundamental question - "What is actually running across our cloud footprint right now?" - was a multi-day ordeal. Before this initiative, inventory gathering relied on ad-hoc Python scripts executed from developer laptops, siloed AWS billing CSV exports, and manually maintained spreadsheets. These manual approaches suffered from critical operational flaws:
  • Zero Centralized Visibility: Platform leadership, Directors of SRE, and FinOps teams had no single source of truth (SSOT) to audit running services across business units.
  • Runaway Zombie Infrastructure: Thousands of unattached EBS volumes, abandoned RDS database snapshots, detached Elastic Network Interfaces (ENIs), and idle clusters accumulated silently across development and staging accounts, burning tens of thousands of dollars in monthly cloud spend.
  • Brittle Cross-Account Scripts: Ad-hoc scripts attempting to iterate through 400+ AWS accounts sequentially were plagued by AWS API rate limiting (ThrottlingException), intermittent network timeouts, and partial run failures that corrupted reporting.
  • Credential Sprawl & Security Risks: Ad-hoc tooling frequently relied on long-lived IAM access keys with broad cross-account permissions stored insecurely across local environments.
To solve this, I designed and deployed an automated, secure, and scheduled ingestion engine. The system queries a centralized AWS Config Aggregator, normalizes multi-account configuration items, and loads them into an Amazon Aurora analytical store using ephemeral credentials provisioned by HashiCorp Vault CSI and KIAM. The resulting platform feeds an enterprise-grade Grafana command center and internal programmatic APIs before regular business hours every morning, eliminating over 90% of recurring reporting effort while tracking more than 200,000 active cloud resources.
Rather than building a naive distributed crawler that makes thousands of individual API calls against 400+ separate accounts, the system leverages native AWS aggregation paired with a decoupled Kubernetes processing pipeline.
Multi-Account AWS Inventory Ingestion Architecture
  1. Centralized AWS Config Aggregator:
    • Each member account runs an AWS Config recorder collecting configuration snapshots of supported AWS resources.
    • An organization-level AWS Config Aggregator continuously consolidates resource records from all 400+ accounts into a single audit account.
    • This architectural choice eliminated thousands of individual cross-account API calls, avoiding AWS API rate-limiting and removing the need for complex network meshes.
  2. Daily Kubernetes Ingestion Engine (batch/v1 CronJob):
    • A lightweight Python ingestion container scheduled to execute daily at 04:00 UTC on an existing enterprise EKS cluster.
    • The job runs prior to business hours, guaranteeing that engineering leadership and FinOps teams arrive to freshly computed metrics every morning.
    • Implements high-throughput pagination and robust exponential backoff when querying the AWS Config SQL-like Advanced Query interface.
  3. Decoupled Data Layer (Amazon Aurora):
    • Ingested configuration data is parsed, enriched with standardized metadata, and loaded into Amazon Aurora (PostgreSQL-compatible).
    • Storing normalized relational rows alongside JSONB configuration blobs decouples analytical reporting from cloud provider APIs. Grafana dashboards and internal services query Aurora directly with sub-second latencies, completely protecting AWS Config API quotas.
  4. Internal APIs & Downstream Consumers:
    • In addition to human visualization via Grafana, a lightweight internal service exposes REST and GraphQL endpoints for downstream automation, including security compliance audits, CI/CD deployment checks, and FinOps anomaly detectors.
A core requirement for this platform was strict adherence to zero-trust credential hygiene. No hardcoded passwords, long-lived AWS secret keys, or static tokens were permitted at any layer of the architecture.
Zero-Trust Pod Identity and Dynamic Database Credential Flow
  1. Pod Scheduling: The Kubernetes CronJob pod starts at 04:00 UTC with an IAM role annotation (iam.amazonaws.com/role).
  2. KIAM Pod Identity: The node-level KIAM DaemonSet intercepts the metadata request and calls AWS STS to assume ConfigAggregatorReadOnly.
  3. Short-Lived AWS STS Lease: AWS STS returns temporary IAM credentials to the CronJob pod bounded by a 1-hour expiration window.
  4. Vault CSI Volume Mount: The CSI driver contacts HashiCorp Vault to dynamically generate a unique, short-lived PostgreSQL database role and password for Amazon Aurora.
  5. In-Memory Credential Injection: Vault CSI injects the temporary credentials into an in-memory tmpfs volume (/vault/secrets/db-creds.json) with zero disk writes.
  6. Aggregated Inventory Extraction: The CronJob streams inventory across all 400+ accounts via AWS Config SelectAggregateResourceConfig.
  7. Relational Upsert: The pod normalizes the payload and executes bulk upserts into Amazon Aurora.
  8. Automated Teardown: Upon batch completion, the pod terminates and both the AWS STS session and HashiCorp Vault database leases expire automatically.
The ingestion CronJob pod runs with a dedicated KIAM role annotation: The assumed role is strictly scoped via AWS IAM policy conditions, allowing only read-only query operations on the designated Config Aggregator:
[!NOTE] Engineering Context on KIAM: While KIAM was the enterprise standard in this EKS cluster, modern Kubernetes platforms have largely transitioned to EKS Pod Identity or IAM Roles for Service Accounts (IRSA) to eliminate the iptables proxy daemonset overhead. The core security principle remains identical: short-lived, STS-assumed role credentials with zero static keys. For an architectural deep-dive into multi-account IAM role assumption and confused-deputy mitigation, see the companion guide: Multi-Account AWS Automation: IAM Role Assumption at Scale.
Static database credentials represent a primary attack vector in batch jobs. To eliminate this:
  • The Kubernetes pod leverages the HashiCorp Vault CSI Provider (secrets-store.csi.k8s.io).
  • When the CronJob pod is scheduled, Vault's database secrets engine dynamically creates a dedicated PostgreSQL user in Aurora with a 1-hour Time-To-Live (TTL).
  • The credentials are injected via an in-memory tmpfs volume (/vault/secrets/db-creds.json) and never written to disk.
  • When the job finishes and the pod terminates, the lease naturally expires in Vault, and the temporary database credentials are revoked automatically.
The ingestion engine uses SQL-like syntax against the AWS Config Aggregator using SelectAggregateResourceConfig. This allows extracting precise configurations across all 400+ accounts in parallel chunks. To guarantee that retrying a failed CronJob run never produces duplicate entries or corrupts historical trendlines, database persistence relies on partitioned upsert semantics: Tracking 200,000+ resources daily generates approximately 6 million records per month. To maintain sub-second Grafana query latencies:
  • Table Partitioning: Partitions are created dynamically per month.
  • Automated Retention Lifecycle: A secondary lightweight maintenance job purges full configuration JSON payloads older than 90 days while preserving daily roll-up counts (account_id, resource_type, count) in a permanent summary table for multi-year trend analysis.
When the ingestion engine completed its initial fleet-wide reconciliation across the 400+ AWS accounts, it exposed the true magnitude of the enterprise cloud surface area.
Enterprise Cloud Inventory Grafana Dashboard
  • Compute & Serverless (AWS::EC2::Instance): 3,168 active instances spread across on-demand and spot fleets across 14 AWS regions.
  • Containers (AWS::EKS::Cluster): 50 EKS clusters spanning production, staging, and sandboxed developer environments.
  • Functions (AWS::Lambda::Function): 40,600+ Lambda functions powering microservices, data processing pipelines, and event-driven automation.
  • Object Storage (AWS::S3::Bucket): 9,059 S3 buckets evaluated continuously for encryption and public-access block compliance.
  • Block Storage (AWS::EC2::Volume): 13,444 active EBS volumes (with 17,930 historical records tracked across state transitions).
  • Relational Data (AWS::RDS::DBCluster): 1,002 database clusters including multi-AZ Aurora clusters and standard RDS instances.
  • Database Backups (AWS::RDS::DBClusterSnapshot): 19,000+ snapshots retained across accounts for disaster recovery and staging rollbacks.
  • Identity & Access (AWS::IAM::Role): 97,600+ IAM roles auditing service roles, cross-account trust configurations, and CI/CD policies.
  • Monitoring & Alerting (AWS::CloudWatch::Alarm): 73,700+ alarms enforcing operational and security thresholds across the fleet.
  • Network Interfaces (AWS::EC2::NetworkInterface): 32,900+ managed ENIs attached to Lambdas, Application Load Balancers, NAT Gateways, and pods.
While the dashboard gave engineering leadership instant situational awareness, its most immediate return on investment came from FinOps cloud waste reclamation. In a 400-account environment without automated enforcement, orphaned resources accumulate unnoticed:
  • Unattached EBS Volumes (13,444 Total): 1,200+ unattached volumes in available state following uncoordinated EC2 terminations (~$18,000 to $24,000 in monthly waste).
  • Orphaned DB Snapshots (19,000+ Total): 6,500+ orphaned manual snapshots older than 90 days lingering in staging accounts (~$12,000 to $15,000 in monthly waste).
  • Idle Elastic IPs & Dangling ENIs (32,900+ Total): 800+ unattached Elastic IPs and orphaned ENIs driving IPv4 hourly charges and CIDR exhaustion.
  1. Unattached EBS Volumes:
    • The query filtered volumes where attachment.status was null or available. Over 1,200 unattached EBS volumes (many provisioned as expensive gp3 or io1 with pre-allocated IOPS) were sitting idle following improper EC2 terminations.
    • Surfacing this list enabled automated cleanup tickets, saving an estimated $20,000+ per month in unneeded storage.
  2. Orphaned DB Snapshots:
    • Over 6,500 manual RDS snapshots had been created prior to major software releases in staging environments and never deleted, accumulating petabytes of cold backup storage.
  3. Stale IAM Roles & Cloud Surface Area:
    • Auditing over 97,600 IAM roles exposed hundreds of dormant roles left behind by decommissioned services, enabling security teams to systematically shrink the organization-wide attack surface.
A production case study is only credible when it honestly discusses architectural trade-offs, discrepancies between marketing language and implementation reality, and technical limitations.
  • The Marketing Pitch: Marketing descriptions often label operational dashboards as "real-time" command centers providing "live resource counts."
  • The Engineering Reality: In an estate of 400+ accounts and 200,000+ resources, continuous real-time streaming is both cost-prohibitive and unnecessary for strategic infrastructure governance.
  • The Deliberate Trade-Off: Running a daily batch snapshot at 04:00 UTC prior to business hours provided an exact, stable, and immutable baseline for day-over-day delta comparisons. As the production Grafana dashboard header explicitly clarifies:
    "Data is loaded daily as a snapshot prior to regular business hours and does not reflect the count as of right now."
  • Attempting an event-driven, real-time EventBridge forwarding architecture across 400 accounts would have increased infrastructure complexity by orders of magnitude while providing negligible value for FinOps forecasting and capacity planning.
  • The system utilized KIAM to intercept AWS metadata API calls from the CronJob container. While KIAM was the robust standard at the time of initial rollout, running a daemonset that modifies node iptables carries operational fragility during node OS upgrades and EKS minor version bumps.
  • Modern iterations of this pipeline should migrate directly to EKS Pod Identity or IRSA, leveraging native AWS OIDC web identity tokens to eliminate daemonset dependencies completely.
  • In architectural schematics, the arrow connecting AWS Config to the Kubernetes CronJob visually represents configuration data flowing into the worker. In execution reality, the CronJob initiates outbound HTTPS pull requests to the AWS Config endpoint using authenticated STS credentials, pulling paginated result pages over port 443.
  • Data Collection Cadence: Shifted from monthly ad-hoc manual sprints to a daily automated snapshot (04:00 UTC) before business hours.
  • Time to Compile Fleet Report: Cut from 3-5 business days of manual scripting down to sub-second Grafana queries and internal API access.
  • Multi-Account Fleet Coverage: Expanded from partial coverage (~40-60 key accounts) to 100% complete coverage across all 400+ accounts.
  • Credential Hygiene: Eliminated static IAM access keys on engineer laptops in favor of zero static secrets (KIAM + HashiCorp Vault CSI).
  • Recurring Engineering Overhead: Reclaimed ~40-60 engineer-hours/month, representing a greater than 90% reduction via zero-touch automation.
  • FinOps Waste Discovery: Shifted from reactive surprises during quarterly audits to proactive daily identification of zombie assets.
  1. Leverage Cloud-Native Aggregation Before Writing Custom Crawlers: Building custom concurrent boto3 scripts to poll hundreds of accounts is an anti-pattern. Native cloud primitives like AWS Config Aggregators handle cross-account data collection, rate-limiting, and error isolation far more reliably than bespoke application code.
  2. Decouple Analytics from Provider APIs: Never hook operational visualization dashboards directly to cloud provider management APIs. Ingesting data into an analytical database like Amazon Aurora protects API rate quotas, enables multi-table joins, and delivers instantaneous sub-second user queries.
  3. Enforce Ephemeral Credentials Across Every Hop: A system is only as secure as its weakest integration. Combining Kubernetes pod identity for AWS authorization with HashiCorp Vault dynamic secret generation for database authentication guarantees that even a compromised container leaves behind zero persistent credentials.
  4. Visibility Precedes Optimization: You cannot optimize, secure, or govern what you cannot see. Establishing a single source of truth across 400+ accounts transformed FinOps and platform engineering from a reactive game of guessing into an empirical, data-driven discipline.

Related projects

High-Throughput On-Premises NAS to Azure Blob Migration Pipeline

High-Throughput On-Premises NAS to Azure Blob Migration Pipeline

Re-engineered a serial on-premises NAS to Azure Blob Storage loader script into a batch-concurrent AzCopy pipeline, cutting benchmark runtime from 33m 08s to 1m 12s (~27x faster) ahead of a 126 TB / 1.6 million file production migration.
Azure Blob
AzCopy v10
Batch Optimization
Linux Concurrency
Bash / Go
ATS Certify: Modular Resume Engineering & AI Evaluation Architecture

ATS Certify: Modular Resume Engineering & AI Evaluation Architecture

Architected an end-to-end resume engineering and ATS evaluation platform featuring a zero-backend client-side vector builder (pdf-lib / docx) and a decoupled hybrid evaluation engine (Next.js 14, Python FastAPI with PyMuPDF, and pluggable Gemini/Ollama scoring adapters), backed by a 5-stage distributed roadmap to scale to 1 million users.
Next.js 14
Python FastAPI
Gemini API
PyMuPDF
pdf-lib