Homeβ€Ί Blogβ€Ί Week 4 - Building a Fleet Intelligence Platform wi…
AWS Weekly Lab AWS Terraform

Building a Fleet Intelligence Platform with AWS Glue, Step Functions & ServiceNow

From scattered SSM JSON files to SQL-queryable fleet health data β€” automated end to end, ticketed from ServiceNow

AWS Platform Engineering Lab Β· Week 04

Lab Overview

How many of your EC2 instances are missing a patch? Right now, across every account?

The problem. Systems Manager already knows. It knows per instance, in a console, one account at a time β€” which is no use to an auditor asking about hundreds of instances across several accounts.

The objective. Get that inventory out of SSM and into S3, describe it, convert it to partitioned Parquet, and make the whole fleet answerable in SQL β€” triggered by a ticket, closed by the pipeline.

The outcome. It works end to end, and six separate things had to be wrong first, including a colon in a folder name that Spark refuses to parse.

  1. Self-Service Request Any team member submits a ServiceNow RITM ticket. No AWS console access required. No engineer involvement needed to kick it off.
  2. Automatic Pipeline Execution The ticket triggers an AWS Step Functions workflow. Crawler β†’ ETL β†’ data ready. Fully orchestrated, no manual steps.
  3. Ticket Auto-Closes When the pipeline finishes, the Lambda closes the ServiceNow ticket with the Athena query URL in the notes. Requester gets notified automatically.
  4. SQL Queries on Fleet Data Analyst opens Athena, runs SQL against clean Parquet tables β€” patch compliance, inventory, applications, fleet summary. No Python, no scripts.
Who Benefits

Security teams get patch compliance reports on demand. Ops teams get fleet inventory without digging through consoles. Compliance teams get audit-ready data that refreshes automatically. Engineers get out of the loop β€” no one needs to ping them to run a script.

Cloud Services and Concepts

ServicePurpose hereWhat it is
SSM Resource Data SyncGets fleet inventory out of Systems Manager and into S3A Systems Manager feature that writes inventory and compliance data to an S3 bucket on a schedule, so it can be queried like any other data.
Amazon S3Two buckets: raw as delivered, curated as ParquetObject storage: you put files into buckets and pay for what you store and for each request, with no disk to size in advance.
AWS Glue crawler and Data CatalogWorks out the shape of the raw dataA crawler reads files and infers their columns and types; the Data Catalog is where those table definitions live so query engines can read them.
AWS Glue ETLTurns the raw JSON into partitioned ParquetManaged Spark. You supply a script and AWS runs it on workers you size, billed per DPU-hour.
Amazon AthenaThe actual question-answering layerRuns SQL straight against files in S3 with no database to run. You are billed for the bytes each query scans, so file layout is a cost decision.
AWS Step FunctionsOrchestrates crawler, ETL and notification in orderRuns a workflow as an explicit state machine, so each step, its retry behaviour and its failure path are declared rather than buried in code.
AWS LambdaReceives the webhook and closes the ticketRuns a piece of code on demand with no server to manage. You are billed per request and per millisecond it runs.

Two ideas carry the build. Partitioning decides what a query costs, because Athena bills for bytes scanned. And a catalog is only a description: the data stays in S3.

Architecture and Workflow

aws AWS Cloud ServiceNow catalog request 1 Region: us-east-1 API Gateway signed POST 2 webhook receiver validates 3 Step Functions 4 states 4 Glue crawler + ETL raw to Parquet Amazon S3 raw and curated Amazon Athena queries it The workflow polls each Glue stage rather than assuming it finished, and PATCHes the ticket to Closed Complete only when the ETL really ends. 5

Why Step Functions Instead of a Single Lambda?

Glue stages run for minutes β€” sometimes ten to fifteen on a large fleet β€” past Lambda's 15-minute ceiling, which is why Step Functions does the waiting.

Why Two S3 Buckets?

The raw bucket keeps everything SSM exports, unchanged, so a corrected ETL can be re-run over history rather than re-collected.

Prerequisites

RequirementWhyHow to check
Managed instances reporting to Systems ManagerWith no fleet there is no inventory, and every stage downstream succeeds on an empty bucketaws ssm describe-instance-information returns instances
Patience for the first syncResource Data Sync has an initial delay of up to 30 minutes. An empty bucket during that window is expected, not a faultObjects appear under the ssm/ prefix
The sync role's permissionsThe role needs ssm:PutComplianceItems on the target instances, or data never arrives and nothing reports an errorCheck the role's policy before waiting out the delay
The Glue script uploaded before Terraform runsTerraform creates the job with a script location but does not upload the script, so the job fails at run timeThe deploy workflow copies it to S3 before terraform apply

Implementation

Step 1: Terraform Modules

Six Terraform modules: s3, iam, glue, lambda, api-gateway and step-functions.

HCL β€” Module Composition
module "glue" {
  source              = "../../modules/glue"
  project_name        = var.project_name
  environment         = var.environment
  raw_bucket_name     = module.s3.raw_bucket_name
  curated_bucket_name = module.s3.curated_bucket_name
  glue_role_arn       = module.iam.glue_role_arn
}
Terraform apply output
GitHub Actions running terraform apply β€” 10 resources created

Step 2: SSM Resource Data Sync

Resource Data Sync exports fleet data to S3 continuously, with no extra agent.

S3 Path Structure
ssm/AWS:ComplianceSummary/
  accountid=<account-id>/
    region=us-east-1/
      resourcetype=ManagedInstanceInventory/
        i-0abc123def456.json   ← one file per instance
Raw S3 bucket SSM folders
Raw S3 bucket showing AWS:ComplianceSummary, AWS:InstanceInformation, and other SSM data types

Step 3: Glue Crawler

The crawler scans the raw bucket and registers what it finds in the Data Catalog, so the tables exist without anyone declaring their columns.

Glue catalog tables
Glue Data Catalog tables discovered from the SSM raw data

Step 4: Glue ETL Job (PySpark + boto3)

The ETL reads the raw NDJSON and writes four partitioned Parquet tables to the curated bucket.

Why boto3 instead of spark.read.json()?

The colon in those prefix names is why the ETL uses boto3, not Spark β€” see Troubleshooting.

Python β€” boto3 S3 Reader (key pattern)
def read_ssm_prefix(bucket, prefix):
    records = []
    paginator = s3_client.get_paginator("list_objects_v2")
    for page in paginator.paginate(Bucket=bucket, Prefix=prefix):
        for obj in page.get("Contents", []):
            body = s3_client.get_object(
                Bucket=bucket, Key=obj["Key"])["Body"].read()
            records += [json.loads(l) for l in body.splitlines() if l]
    return spark.createDataFrame(records)
Glue ETL run succeeded
ETL job run SUCCEEDED β€” showing execution time and DPU hours consumed
Curated S3 Parquet data
Curated S3 bucket β€” fleet/ prefix with Parquet partitions: patch_compliance, inventory, fleet_summary

Step 5: Step Functions Orchestration

A state machine ties the stages together, polling the crawler and the ETL job with a Wait β†’ Check β†’ Choice loop rather than a fixed sleep.

Step Functions β€” Polling Loop Pattern (ASL)
"WaitForCrawler": { "Type": "Wait", "Seconds": 30,
                     "Next": "CheckCrawlerStatus" },
"CheckCrawlerStatus": { "Type": "Task", ... },
"CrawlerDone?": { "Type": "Choice",
                  "Choices": [ { ... "Next": "StartETL" } ],
                  "Default": "WaitForCrawler" }

Step 6: ServiceNow Webhook & Ticket Closure

A ServiceNow webhook starts it; webhook_receiver validates the signature before anything else runs.

Python β€” HMAC-SHA256 Validation
def verify_hmac(body: str, signature: str, secret: str) -> bool:
    expected = hmac.new(
        secret.encode(), body.encode(), hashlib.sha256
    ).hexdigest()
    return hmac.compare_digest(f"sha256={expected}", signature)

# In handler:
secret = ssm_client.get_parameter(
    Name=HMAC_SECRET_PARAM, WithDecryption=True
)["Parameter"]["Value"]

if not verify_hmac(body, signature, secret):
    return {"statusCode": 401, "body": json.dumps({"error": "Unauthorized"})}

On completion the status_updater closes the ticket with a direct Athena link in the close notes.

ServiceNow ticket closed
Ticket automatically closed by status_updater β€” close notes contain the Athena query URL

Step 7: Querying with Athena

Athena answers against the curated tables.

SQL β€” Patch Compliance Summary
SELECT
    compliance_status,
    COUNT(*)         AS instance_count,
    ROUND(COUNT(*) * 100.0 / SUM(COUNT(*)) OVER (), 1) AS pct
FROM fleet.patch_compliance
GROUP BY compliance_status
ORDER BY instance_count DESC;
SQL β€” OS Distribution
SELECT
    platform_name,
    platform_version,
    COUNT(*) AS instance_count
FROM fleet.inventory
GROUP BY platform_name, platform_version
ORDER BY instance_count DESC;
Athena patch compliance query
Patch compliance query results β€” compliance_status breakdown across fleet

Validation and Evidence

Each row traces to a figure here. The lab was destroyed in June 2026; these are the results recorded then.

TestExpectedActualStatus
The platform deploysTerraform applies cleanly from CI10 resources createdPass
Fleet data reaches S3SSM inventory under the raw prefixAWS:ComplianceSummary, AWS:InstanceInformation and other types presentPass
The catalog describes itTables discovered without being declaredTables present in the Data Catalog, inferred by the crawlerPass
The ETL runsA successful Glue runSUCCEEDED, on Glue 4.0 with 2 Γ— G.1X workersPass
Output is partitioned ParquetColumnar files under a partitioned prefixParquet partitions for patch compliance, inventory and fleet summaryPass
The ticket closes itselfThe requester gets an answer without an engineerClosed automatically, with the Athena query URL in the close notesPass
The question is answerablePatch compliance across the fleet, in SQLCompliance status returned broken down across the fleetPass
Query costLow, because partitions let Athena skip dataNot recorded at the time. The partitioning is in place; the bytes-scanned figure was never capturedNot measured

Security and Cost

Security β€” Controls at Every Layer

  • Secrets. ServiceNow password and HMAC secret in SSM Parameter Store as SecureString, read at runtime β€” never in environment variables or source.
  • Webhook authentication. HMAC-SHA256 with compare_digest, before anything else.
  • Least privilege. A role per Lambda and Glue job, scoped to named resources, no wildcard ARNs.
  • Buckets. AES-256 at rest, public access blocked, and a lifecycle rule expiring raw data after 90 days.
What’s Missing for Production
  • VPC endpoints for S3, Glue, SSM β€” currently traffic routes over public AWS endpoints
  • WAF on the API Gateway to rate-limit and block malicious IPs
  • S3 Object Lock on the curated bucket for immutable audit trail
  • CloudTrail data events enabled on S3 buckets for full audit logging
  • Glue job bookmark enabled to avoid reprocessing already-seen data

Cost β€” What This Actually Costs

This pipeline is designed to run on-demand (triggered by ServiceNow, not continuously). Here’s the cost breakdown per pipeline run in dev, based on a fleet of ~50 EC2 instances.

ServiceUsage per runUnit priceCost per run
Glue Crawler2 DPU Γ— 10 min$0.44/DPU-hour$0.15
Glue ETL Job2 Γ— G.1X Γ— 5 min$0.44/DPU-hour$0.07
Step Functions~20 state transitions$0.025/1000<$0.001
Lambda (3 functions)~5 invocations total$0.20/1M requests<$0.001
Athena~1 MB scanned$5/TB<$0.001
API Gateway1 request$3.50/1M<$0.001
S3 Storage~100 MB (raw + curated)$0.023/GB/month<$0.001
Total per pipeline run: ~$0.22
Running twice daily for a month: ~$13.20/month. The Glue crawler and ETL job dominate cost β€” consolidating crawler runs and using job bookmarks to skip unchanged data would cut this by 40–60%.

Cost Optimisation Tips

  • Enable Glue job bookmarks to skip files already processed β€” reduces ETL run time significantly after the first run
  • Use G.025X worker type instead of G.1X for small fleets (<500 instances) β€” 4Γ— cheaper
  • Schedule SSM Resource Data Sync to run every 6 hours instead of continuously to reduce S3 write costs
  • Set S3 Intelligent-Tiering on the curated bucket after 30 days

Troubleshooting and Lessons

Problem. The Glue job crashed immediately with java.net.URISyntaxException: Relative path in absolute URI.
Root cause. SSM writes its data under prefixes like AWS:ComplianceSummary, and Java's URI parser reads the colon as a protocol separator. spark.read.json() could not open a path it considered malformed.
Resolution. Listed and downloaded the objects with a boto3 paginator instead, which treats a key as a string, then built the DataFrame from the records.
Lesson. A service that names its own prefixes can still produce names another service refuses to parse.

Problem. Every signed webhook returned 401, with the right secret.
Root cause. ServiceNow sent the signature as x-servicenow-hmac; the function read X-ServiceNow-HMAC. API Gateway lowercases header names, so the lookup found nothing and compared against an empty string.
Resolution. Read the lowercase name.
Lesson. A missing header and a wrong signature fail identically. Log which of the two it was.

Problem. The state machine appeared stuck polling the crawler.
Root cause. It was not. The poll waits 30 seconds and a first crawler run takes four to five minutes doing schema inference from cold.
Resolution. No code change; added logging so the poll count is visible.
Lesson. "Indistinguishable from hung" is a reporting defect even when the logic is right.

Problem. The Glue job failed with Script not found.
Root cause. Terraform creates the job with a script location; it does not put the script there.
Resolution. Upload it in the deploy workflow before terraform apply.
Lesson. A resource that only references an artefact is created happily whether or not the artefact exists.

Problem. The raw bucket stayed empty for more than twenty minutes after Resource Data Sync was configured.
Root cause. Two things at once: the initial sync delay is up to thirty minutes, and the sync role was missing ssm:PutComplianceItems on the target instances.
Resolution. Fixed the permission, then waited.
Lesson. When the symptom of "not finished yet" and the symptom of "not permitted" are both an empty bucket, check the permission before you wait.

Problem. Closing the ticket returned 404.
Root cause. The payload carried the human-readable number (RITM0012345); the API PATCH endpoint addresses records by sys_id.
Resolution. Resolve the number to a sys_id with a query first, and carry the sys_id in the payload from then on.
Lesson. The identifier a system shows a person is rarely the one its API wants.

Cleanup and Key Takeaways

Cleanup β€” Tearing It Down

Everything except the Resource Data Sync and the bucket contents is Terraform-managed and destroys in one command.

Bash β€” Terraform Destroy
cd terraform/environments/dev
terraform destroy -var-file=terraform.tfvars

# Expected output:
# Destroy complete! Resources: 44 destroyed.
ResourceDestroyed by Terraform?Manual step needed?
S3 buckets (raw, curated, athena-results)Yes β€” if emptyEmpty buckets first: aws s3 rm s3://bucket --recursive
Glue Database + TablesYesNone
Glue Crawler + ETL JobYesNone
Step Functions State MachineYesNone
Lambda Functions (3)YesNone
API GatewayYesNone
IAM Roles + PoliciesYesNone
SSM Parameter Store (secrets)YesNone
SSM Resource Data SyncNo β€” not in TerraformDelete manually in SSM Console β†’ Fleet Manager β†’ Resource Data Sync
Empty S3 buckets before running destroy
Terraform will fail to delete non-empty S3 buckets. Run aws s3 rm s3://BUCKET-NAME --recursive for all three buckets before terraform destroy.

Takeaways β€” What I’d Do Differently

Six lessons from this build that apply beyond this specific project.

  1. Read S3 with boto3 when keys contain URI-special characters. Colons are common in AWS-generated prefixes and Spark cannot open them.
  2. Poll, do not sleep. A Wait β†’ Check β†’ Choice loop survives a slow first crawler run; a hard-coded wait does not.
  3. Validate every webhook. HMAC-SHA256 with compare_digest cost twenty lines and makes the endpoint safe to expose.
  4. Keep raw and curated separate. Raw NDJSON stays as delivered, curated Parquet is what gets queried, and either can be rebuilt from the other direction.
  5. Resource Data Sync has an undocumented-feeling delay. Up to thirty minutes, and a missing permission looks exactly the same.
  6. Close the ticket with the answer in it. The requester gets an Athena link rather than a notification that something finished.

Comments

How was your experience?
Your feedback helps improve this site.
PoorExcellent