π In This Post
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.
- Self-Service Request Any team member submits a ServiceNow RITM ticket. No AWS console access required. No engineer involvement needed to kick it off.
- Automatic Pipeline Execution The ticket triggers an AWS Step Functions workflow. Crawler β ETL β data ready. Fully orchestrated, no manual steps.
- 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.
- SQL Queries on Fleet Data Analyst opens Athena, runs SQL against clean Parquet tables β patch compliance, inventory, applications, fleet summary. No Python, no scripts.
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
| Service | Purpose here | What it is |
|---|---|---|
| SSM Resource Data Sync | Gets fleet inventory out of Systems Manager and into S3 | A 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 S3 | Two buckets: raw as delivered, curated as Parquet | Object 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 Catalog | Works out the shape of the raw data | A 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 ETL | Turns the raw JSON into partitioned Parquet | Managed Spark. You supply a script and AWS runs it on workers you size, billed per DPU-hour. |
| Amazon Athena | The actual question-answering layer | Runs 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 Functions | Orchestrates crawler, ETL and notification in order | Runs 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 Lambda | Receives the webhook and closes the ticket | Runs 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
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
| Requirement | Why | How to check |
|---|---|---|
| Managed instances reporting to Systems Manager | With no fleet there is no inventory, and every stage downstream succeeds on an empty bucket | aws ssm describe-instance-information returns instances |
| Patience for the first sync | Resource Data Sync has an initial delay of up to 30 minutes. An empty bucket during that window is expected, not a fault | Objects appear under the ssm/ prefix |
| The sync role's permissions | The role needs ssm:PutComplianceItems on the target instances, or data never arrives and nothing reports an error | Check the role's policy before waiting out the delay |
| The Glue script uploaded before Terraform runs | Terraform creates the job with a script location but does not upload the script, so the job fails at run time | The 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.
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
}
Step 2: SSM Resource Data Sync
Resource Data Sync exports fleet data to S3 continuously, with no extra agent.
ssm/AWS:ComplianceSummary/
accountid=<account-id>/
region=us-east-1/
resourcetype=ManagedInstanceInventory/
i-0abc123def456.json β one file per instance
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.
Step 4: Glue ETL Job (PySpark + boto3)
The ETL reads the raw NDJSON and writes four partitioned Parquet tables to the curated bucket.
The colon in those prefix names is why the ETL uses boto3, not Spark β see Troubleshooting.
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)
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.
"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.
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.
Step 7: Querying with Athena
Athena answers against the curated tables.
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;
SELECT
platform_name,
platform_version,
COUNT(*) AS instance_count
FROM fleet.inventory
GROUP BY platform_name, platform_version
ORDER BY instance_count DESC;
Validation and Evidence
Each row traces to a figure here. The lab was destroyed in June 2026; these are the results recorded then.
| Test | Expected | Actual | Status |
|---|---|---|---|
| The platform deploys | Terraform applies cleanly from CI | 10 resources created | Pass |
| Fleet data reaches S3 | SSM inventory under the raw prefix | AWS:ComplianceSummary, AWS:InstanceInformation and other types present | Pass |
| The catalog describes it | Tables discovered without being declared | Tables present in the Data Catalog, inferred by the crawler | Pass |
| The ETL runs | A successful Glue run | SUCCEEDED, on Glue 4.0 with 2 Γ G.1X workers | Pass |
| Output is partitioned Parquet | Columnar files under a partitioned prefix | Parquet partitions for patch compliance, inventory and fleet summary | Pass |
| The ticket closes itself | The requester gets an answer without an engineer | Closed automatically, with the Athena query URL in the close notes | Pass |
| The question is answerable | Patch compliance across the fleet, in SQL | Compliance status returned broken down across the fleet | Pass |
| Query cost | Low, because partitions let Athena skip data | Not recorded at the time. The partitioning is in place; the bytes-scanned figure was never captured | Not 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.
- 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.
| Service | Usage per run | Unit price | Cost per run |
|---|---|---|---|
| Glue Crawler | 2 DPU Γ 10 min | $0.44/DPU-hour | $0.15 |
| Glue ETL Job | 2 Γ 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 Gateway | 1 request | $3.50/1M | <$0.001 |
| S3 Storage | ~100 MB (raw + curated) | $0.023/GB/month | <$0.001 |
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.025Xworker type instead ofG.1Xfor 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.
cd terraform/environments/dev terraform destroy -var-file=terraform.tfvars # Expected output: # Destroy complete! Resources: 44 destroyed.
| Resource | Destroyed by Terraform? | Manual step needed? |
|---|---|---|
| S3 buckets (raw, curated, athena-results) | Yes β if empty | Empty buckets first: aws s3 rm s3://bucket --recursive |
| Glue Database + Tables | Yes | None |
| Glue Crawler + ETL Job | Yes | None |
| Step Functions State Machine | Yes | None |
| Lambda Functions (3) | Yes | None |
| API Gateway | Yes | None |
| IAM Roles + Policies | Yes | None |
| SSM Parameter Store (secrets) | Yes | None |
| SSM Resource Data Sync | No β not in Terraform | Delete manually in SSM Console β Fleet Manager β Resource Data Sync |
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.
- Read S3 with boto3 when keys contain URI-special characters. Colons are common in AWS-generated prefixes and Spark cannot open them.
- Poll, do not sleep. A Wait β Check β Choice loop survives a slow first crawler run; a hard-coded wait does not.
- Validate every webhook. HMAC-SHA256 with
compare_digestcost twenty lines and makes the endpoint safe to expose. - 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.
- Resource Data Sync has an undocumented-feeling delay. Up to thirty minutes, and a missing permission looks exactly the same.
- Close the ticket with the answer in it. The requester gets an Athena link rather than a notification that something finished.
Comments