A Data-Driven Gateway for Routing ServiceNow Incidents Across Multiple AWS DevOps Agent Spaces
Large enterprises often run one centralized ServiceNow instance while giving each business unit its own AWS DevOps Agent Space. ServiceNow can route to multiple spaces natively, but that means one Business Rule per BU. This article shows an optional gateway (API Gateway, Lambda, DynamoDB) that keeps routing in one table, sends unmatched tickets to a quarantine queue, and logs every routing decision, for teams managing 8–15+ BUs.
Enterprises with many AWS accounts across multiple business units (BUs) often centralize incident management in a single ServiceNow instance, while running a separate AWS DevOps Agent Space per BU for isolation. ServiceNow can already route incidents to different Agent Spaces natively, using one Business Rule per space with filter conditions. This article presents an optional centralized gateway (API Gateway, Lambda, DynamoDB) that consolidates that routing into a single data-driven table — worth the extra infrastructure once you are maintaining routing logic for 8–15 BUs, need central audit logging, or want to add a BU without a ServiceNow change request. It includes a working router, honest security controls, and lessons from what broke along the way. (By Vivek Madem, with Paul Maney)
A note on scope and names. This article uses generic BU names (Finance, Platform Engineering, Data Analytics) and a synthetic demo environment. No real customer names, account IDs, or credentials are referenced. The pattern was validated as a proof of concept with two Agent Spaces in a single AWS account; the routing-table design extends to more spaces and multiple accounts, though multi-account deployments add IAM trust and networking considerations not covered here. AWS features change quickly — verify current behavior against the AWS documentation before you build.
The problem
AWS DevOps Agent's native ServiceNow integration can route incidents to multiple Agent Spaces today: you create one Business Rule per space, each with filter conditions that decide which incidents go where (ticket routing and orchestration examples). For a handful of BUs, that is the simplest thing that works, and you should start there.
The friction shows up at scale. With 8–15 business units, native routing means 8–15 Business Rules living in ServiceNow, each maintained by the ServiceNow team through their change process. Adding a BU is a ServiceNow change request. There is no single place to see every routing decision, and a ticket whose fields match no rule's filter is silently not routed anywhere.
A centralized gateway trades a little AWS infrastructure for operational control at scale:
- One rule instead of N — routing logic lives in one DynamoDB table instead of 8–15 Business Rules. Adding a BU is a row insert, not a ServiceNow change request.
- A guaranteed destination — the native per-rule approach drops tickets that match no filter. The gateway routes unmatched tickets to a quarantine queue for manual triage, so nothing is silently lost.
- Central audit logging — every routing decision is recorded in one place, with the ticket-to-investigation correlation.
This article is about that gateway variant. If you have three BUs and no central-governance requirement, native Business Rule routing is likely the better choice — and that is a legitimate outcome of reading this.
What you'll learn
- How native ServiceNow multi-space routing works, and the specific scale/governance thresholds where a centralized gateway earns its keep
- How to build a stateless routing gateway that resolves organizational ownership from a ServiceNow field and forwards to the correct Agent Space webhook
- How to authenticate both hops properly — API key on the ingress, HMAC on the webhook to the Agent Space
- How business-unit isolation is actually enforced in ServiceNow (ACLs, not OAuth alone)
- How findings get back to the ticket now that Directed Actions changes the write-back story
- What broke during implementation and how we worked around it
The architecture — three layers, one flow
The pattern has three distinct jobs, each handled by a different layer.
Layer 1 — Generic Webhook + Router Lambda (trigger and route): A ServiceNow Business Rule fires on incident creation, hitting an API Gateway endpoint. A Lambda reads the ticket's organizational-ownership field, looks up a DynamoDB routing table, and POSTs to the target Agent Space's generic webhook. This is the only layer that decides where the investigation runs.
Layer 2 — ServiceNow enrichment, per BU (pull context): During the investigation, the agent pulls full ticket context on demand — related incidents, CMDB topology, change records, knowledge articles — through a per-BU-scoped ServiceNow MCP connection.
Layer 3 — BU Agent Spaces (investigate with context): Each space has BU-specific IAM scope, skills (runbooks), memories (recurring patterns), and tool integrations (Datadog, Dynatrace, etc.). The investigation runs with organizational context, not a generic prompt.
Write-back — getting findings onto the ticket — is treated separately, because Directed Actions changed how it must work (see below).
Why not just one Agent Space for everything?
Context pollution, IAM blast radius, and compliance. A single space with hundreds of enrolled accounts needs an IAM role with broad cross-account access. Its memories accumulate patterns from unrelated workloads — a database team's recurring root cause pollutes context when investigating a Lambda timeout. Skills written for one team's Terraform workflow are irrelevant for another team's CDK pipeline. And in regulated industries, one BU's investigation context must not be visible to another. Isolated Agent Spaces enforce that boundary by design — which is what creates the routing problem in the first place.
The routing decision — what it looks like
A sanitized routing log. A ServiceNow incident fires for a database cluster owned by the Finance BU:
{ "tool": "route_incident", "impacted_global_business_line": "Finance", "decision": "forward_to_bu_a", "targetAgentSpace": "devops-agent-bu-finance", "routingFields": { "number": "INC0010042", "assignment_group": "Database Platform Support", "cmdb_ci": "Aurora Cluster - Production", "category": "Software", "subcategory": "Database" }, "forwarded": true, "downstreamStatus": 200 }
Routing is based on impacted_global_business_line — a dedicated ServiceNow field that explicitly declares which BU owns the incident. Not a keyword match on the description (fragile), not the category (ambiguous). A single authoritative field that ServiceNow administrators already maintain. (Our first POC routed on description keywords; see the lessons below for why that fails.)
Building the router
The routing table
A DynamoDB table maps organizational ownership to Agent Spaces. Adding a BU is one row — no code change:
| routing_key (PK) | agent_space_id | webhook_url | description |
|---|---|---|---|
| Finance | a92a7618-… | https://event-ai.us-east-1.api.aws/webhook/generic/… | Finance BU |
| Platform Engineering | b83f9721-… | https://event-ai.us-east-1.api.aws/webhook/generic/… | Platform BU |
| Data Analytics | c74e8632-… | https://event-ai.us-east-1.api.aws/webhook/generic/… | Data BU |
| DEFAULT | (quarantine) | (SQS queue, not an Agent Space) | Manual triage for unmatched tickets |
Note the DEFAULT row. It does not forward to a catch-all Agent Space — sending a ticket of unknown ownership into an arbitrary space would violate the isolation the whole design exists to protect. Instead it routes to a quarantine queue that alerts the routing team for manual assignment. This guarantees a destination (nothing is silently dropped) without fail-open routing.
The webhook payload
DevOps Agent's generic webhook requires a specific schema. The router transforms the ServiceNow payload into it:
{ "eventType": "incident", "incidentId": "INC0010042", "action": "created", "priority": "HIGH", "title": "Aurora cluster CPU exhaustion - Production", "description": "Full description with ITSM context...", "timestamp": "2026-07-16T18:16:12Z", "service": "Finance", "data": { "sysId": "…", "assignment_group": "…", "cmdb_ci": "…" } }
Put the human-readable summary the agent should triage on in description. The data field carries structured event context and identifiers for downstream/audit use — populate it, but don't rely on it as the agent's only view of the incident; description is what reliably drives triage.
Authentication — both hops
Authentication happens at two distinct hops, and they use different mechanisms:
| Hop | Mechanism | Why |
|---|---|---|
| ServiceNow → API Gateway (ingress) | API Gateway API key + WAF + rate limiting | Simple to configure on the ServiceNow Outbound REST side; API Gateway validates before Lambda runs |
| Router → Agent Space webhook | HMAC signature | This is the mechanism the DevOps Agent webhook documents and verifies (webhook authentication methods) |
WAF and rate limiting are protections, not authentication — they don't establish caller identity, so each hop still needs its own auth. Keep all secrets (the API key, the HMAC signing key per space) in AWS Secrets Manager and read them at invocation time.
The ServiceNow Business Rule
Fire on After Insert, not Before Insert. ServiceNow assigns the incident number (INC00----) only after the record is committed; a Before-Insert rule sends a blank number and breaks ticket-to-investigation correlation. Move the network call off the user transaction where possible (a managed Outbound REST Message / async delivery) so a slow or failing endpoint never blocks the person creating the ticket.
(function executeRule(current, previous) { try { var request = new sn_ws.RESTMessageV2(); request.setEndpoint( 'https://<api-gateway-id>.execute-api.us-east-1.amazonaws.com/prod/route-incident' ); request.setHttpMethod('POST'); request.setRequestHeader('Content-Type', 'application/json'); request.setRequestHeader('x-api-key', gs.getProperty('devops.router.apikey')); var payload = { ticket_id: current.number.toString(), sys_id: current.getUniqueValue(), short_description: current.short_description.toString(), description: current.description.toString(), priority: current.priority.toString(), assignment_group: current.assignment_group.getDisplayValue(), cmdb_ci: current.cmdb_ci.getDisplayValue(), business_service: current.business_service.getDisplayValue(), impacted_global_business_line: current.u_impacted_global_business_line.getDisplayValue() }; request.setRequestBody(JSON.stringify(payload)); var response = request.executeAsync(); } catch (ex) { gs.error('DevOps Agent Router Error: ' + ex.getMessage()); } })(current, previous);
The Router Lambda
Stateless: resolve the BU, look up the target, sign, forward, persist the correlation. Core logic, trimmed:
import json import boto3 import urllib3 import hashlib import hmac from datetime import datetime, timezone dynamodb = boto3.resource('dynamodb', region_name='us-east-1') routing_table = dynamodb.Table('devops-agent-routing') correlation_table = dynamodb.Table('devops-agent-investigation-correlation') sqs = boto3.client('sqs', region_name='us-east-1') http = urllib3.PoolManager() def lambda_handler(event, context): # API Gateway proxy delivers the body as a JSON string; direct # invocation delivers the event itself. Handle both. try: body = json.loads(event['body']) except (KeyError, TypeError): body = event ticket_id = body.get('ticket_id', 'UNKNOWN') gbl = body.get('impacted_global_business_line', '').strip() # Resolve target; unmatched ownership goes to quarantine, not a catch-all space target = get_target(gbl) if gbl else None if not target: quarantine(body) return {'statusCode': 202, 'body': json.dumps({'routed': False, 'quarantined': True})} priority_map = {'1': 'CRITICAL', '2': 'HIGH', '3': 'MEDIUM', '4': 'LOW', '5': 'MINIMAL'} payload = json.dumps({ 'eventType': 'incident', 'incidentId': ticket_id, 'action': 'created', 'priority': priority_map.get(body.get('priority', '3'), 'MEDIUM'), 'title': body.get('short_description', f'ServiceNow {ticket_id}'), 'description': build_description(body), 'timestamp': datetime.now(timezone.utc).isoformat(), 'service': gbl, 'data': {k: body.get(k, '') for k in ('sys_id', 'assignment_group', 'cmdb_ci', 'business_service')} }) # HMAC-sign the webhook call to the Agent Space signing_key = get_secret(f"webhook-hmac/{target['agent_space_id']}") signature = hmac.new(signing_key.encode(), payload.encode(), hashlib.sha256).hexdigest() response = http.request('POST', target['webhook_url'], body=payload, headers={'Content-Type': 'application/json', 'X-Signature': signature}) correlation_table.put_item(Item={ 'ticket_id': ticket_id, 'sys_id': body.get('sys_id', ''), 'agent_space_id': target['agent_space_id'], 'routing_key': gbl, 'status': 'routed', 'downstream_status': str(response.status), 'created_at': datetime.now(timezone.utc).isoformat() }) return {'statusCode': 200, 'body': json.dumps({'routed': True, 'target': gbl})}
A note on the try/except around the body: API Gateway with Lambda Proxy Integration puts the payload inside event['body'] as a JSON string; without proxy integration it arrives as the event object. Our first end-to-end test from ServiceNow threw KeyError: 'body' even though Lambda console tests passed — this handles both.
Business-unit isolation — ACLs, not OAuth alone
When the agent enriches an investigation by reading ServiceNow, scoping that access per BU is a compliance requirement, not just a nicety. OAuth authenticates the principal and can restrict scopes, but it does not by itself limit which records a caller can read. Row-level isolation is enforced on the ServiceNow side:
- A dedicated ServiceNow integration user per BU (not a shared admin account)
- Record and field ACLs, plus domain separation or query business rules, that filter tickets by assignment group / business unit
- An MCP tool allowlist limiting which operations each space can call
- Negative tests that prove one BU's integration user cannot read or update another BU's records
Document these explicitly. "We use OAuth" is not evidence of isolation; a passing negative test is.
Write-back — getting findings onto the ticket
Getting findings back onto the ServiceNow ticket is the part most affected by recent platform changes, so treat it as its own decision rather than assuming the agent will write to the ticket mid-investigation.
Directed Actions govern mutating third-party tools: a tool that writes to ServiceNow is categorized as a mutating action and requires operator approval in chat. A mutating call made during an autonomous investigation does not silently succeed — it fails or waits for approval (categorizing tools for third-party integrations). So "the agent autonomously writes its findings back through MCP" is not a safe assumption. The options:
| Option | How it works | Autonomous? |
|---|---|---|
| Built-in ServiceNow comment write-back | The native integration posts investigation updates as comments | Yes, within the native integration's behavior |
| MCP write tool (in chat) | Agent proposes the write; operator approves via Directed Actions | No — requires approval |
| Parallel completion automation | An EventBridge rule fires on investigation completion → Lambda reads findings from the Agent Space Data API → updates the ticket's root-cause field and appends a link | Yes |
For a fully autonomous write-back, the parallel EventBridge + Data API path is the pattern to build. It also gives you a clean place to shape the output — the raw investigation narrative is long, so summarize to root cause plus recommended actions before posting. (AWS has signaled work on investigation-summary conciseness; check current capabilities before building your own report renderer, since the service may now do this for you.)
What didn't work, and what we learned
The boto3 SDK has no start_investigation. The DevOps Agent client exposes create_agent_space, list_webhooks, create_chat, send_message — but no direct "start an investigation" call. We found this by listing the client's methods. Investigations are triggered via the generic webhook (HTTP POST with the documented schema).
Business Rule timing matters. Before-Insert means the incident number isn't assigned yet — the payload's number comes through blank and correlation breaks. Use After-Insert, and use getUniqueValue() / sys_id as the machine correlation key (the display number is for humans).
API Gateway integration type changes the payload shape. Proxy integration wraps the body as a JSON string in event['body']; without it the event is the payload. Handle both or your ServiceNow-triggered calls fail while console tests pass.
Keyword routing breaks at scale. Our first POC scanned the description for "EC2", "RDS", "Lambda". An incident titled "Lambda timeout calling RDS" matches two BUs. Route on a dedicated ownership field instead.
Memories are not a data warehouse. A team wanted to load two years of incident history into memories so the agent "knows everything." Memories have limits and are surfaced through progressive disclosure — the agent pulls them into context as needed, so a bloated store competes with actual investigation reasoning. Keep memories for high-signal synthesized patterns ("this alarm usually means X"); use the ServiceNow MCP for historical queries ("related incidents for this CI in the last 90 days"), which returns only what's relevant to the question at hand.
Free ServiceNow developer instances hibernate. A developer.servicenow.com instance goes dormant after a few hours; the Business Rule silently fails on the first call while it wakes. Check ServiceNow's System Logs when a delivery seems to vanish.
Scaling the pattern
Adding a business unit is configuration, not code:
| Step | Time | Code change? |
|---|---|---|
| Create Agent Space with BU-scoped IAM | 10 min | No |
| Configure the generic webhook (HMAC) on the space | 5 min | No |
| Set up the per-BU ServiceNow integration user + ACLs | 20 min | No |
| Add BU skills and instructions | 30 min | No |
| Insert one row in the DynamoDB routing table | 1 min | No |
| Store the HMAC key in Secrets Manager | 2 min | No |
For 20+ spaces, Git-managed skills (sync runbooks from a central repo) and the Assets API (push skills, instructions, and memories programmatically) keep configuration consistent.
Security controls
| Layer | Control |
|---|---|
| ServiceNow → Router | API Gateway API key; WAF; rate limiting; payload validation |
| Router → Agent Space webhook | HMAC signature verified by the webhook; keys in Secrets Manager |
| Agent Space → ServiceNow (enrichment) | Per-BU integration user; record/field ACLs; domain separation; MCP tool allowlist; negative tests |
| Agent Space IAM | Scoped to the BU's accounts; no cross-BU access |
| Delivery | After-Insert; async/outbox; correlation store for reconciliation |
When to use this — and when not to
Use native ServiceNow Business Rule routing if you have a few BUs and no central-governance requirement. Adopt the gateway when routing logic for many BUs would otherwise sprawl across Business Rules, when you need one audited place for every routing decision, when unmatched tickets must be caught rather than dropped, or when adding a BU shouldn't require a ServiceNow change request. The gateway is an operational-scale choice, not a capability the platform lacks.
Acknowledgements
This pattern grew out of customer working sessions led by Paul Maney. Thanks also to Kartik Ganesh and Dan Malloy for technical review.
Related resources
- Connecting ServiceNow — ticket routing and orchestration examples
- Invoking DevOps Agent through a webhook — authentication methods
- Working with Directed Actions — categorizing tools for third-party integrations
- Closing the Jira Incident Loop with AWS DevOps Agent
- Six Patterns for Connecting OpenSearch Logs to AWS DevOps Agent
- Tags
- AWS DevOps Agent
- Language
- English
Relevant content
- Accepted Answer
asked 3 years ago
AWS OFFICIALUpdated 3 months ago