athena-cloudwatch-connector.md
| source_path | references/data-discovery/cloudwatch-extraction/references/athena-cloudwatch-connector.md |
|---|---|
| source_sha256 | 5c9e5e6f197a24dbc1e06ef863b3e9b7e76a1ae3055a374f459f800256b80d06 |
| source_url | https://github.com/aws/agent-toolkit-for-aws/blob/903433d67cc4eeab334355620373f33a0c162dd4/skills/core-skills/aws-ai-ml/references/data-discovery/cloudwatch-extraction/references/athena-cloudwatch-connector.md |
| supporting_skill_id | 40202 |
| upstream_revision | 903433d67cc4eeab334355620373f33a0c162dd4 |
Query CloudWatch via the Athena CloudWatch connector
Stage 2 of overview.md. Query the resolved log group into JSONL on S3, then
leave registration to ../../dataset-import/. This reference forms the query,
runs it against Athena, and consolidates the output to a single .jsonl.
The connector model (drives the SQL)
The Athena CloudWatch connector is an Athena Federation Lambda, registered as
an Athena data catalog (referenced by its catalog name — e.g. the
FEDERATED catalog the console path creates — or by the "lambda:<fn>" form the
SAR path uses). It
maps each LogGroup → a database, each LogStream → a table, plus an
all_log_streams view per group. Every table has a FIXED 3-column schema:
log_stream VARCHAR, time INT64 (epoch ms), message VARCHAR. The trace JSON
is a STRING inside message — there are no per-attribute columns, so a standard
query parses JSON out of message.
Set up / reuse the connector
1. Detect and reuse first.
- Existing connector:
aws athena list-data-catalogs --region <r>— look for
either shape, since the two deploy paths register differently: a
FEDERATED-type entry withConnectionType: "CLOUDWATCH"(the console/Glue
path) or aLAMBDA-type entry whose function is the CloudWatch connector
(the SAR path). Reuse whichever is found (idempotent — do not deploy a second). - Existing spill bucket:
aws s3 ls | grep -i 'athena\|spill'(e.g. an
aws-athena-query-results-*bucket) — offer to reuse it rather than create a
new one, and reuse the same bucket for the Athena workgroup output location.
2. If no connector exists, state the manifest and get an explicit go before
deploying — do NOT create account infra silently:
Resources this creates (one-time per account/region):
- 1 Lambda function — the Athena CloudWatch connector
- 1 IAM role for that Lambda (CloudWatch Logs read + S3 spill write +
athena:GetQueryExecution); on an IAM denial elsewhere, name the exact
action/resource and the policy statement to add — never call a grant API - 1 CloudFormation stack wrapping both (deployed from the connector app)
- 1 Athena data catalog registration pointing at the Lambda —
FEDERATEDtype
withConnectionType: "CLOUDWATCH"on the console/Glue path,LAMBDAtype on
the SAR path - 1 S3 spill bucket — only if no reusable bucket exists
- 1 Athena workgroup output-location update — only if the chosen workgroup has none
Expect a couple of minutes for the CloudFormation stack to reach
CREATE_COMPLETE; tell the user to expect that wait before starting so the
deploy is not a silent gap.
3. Deploy — present the user two options and recommend the console:
- Athena console (recommended) — Athena console → Data sources and
catalogs → Create data source → choose Amazon CloudWatch Logs →
Next. On Enter data source details (one page, no detour to the
Lambda console): name the data source → under AWS Glue connection
details, set the Spill location in Amazon S3 (your spill bucket) and
leave encryption at its default → under Lambda execution IAM role,
choose Create and use a new execution role (or Use an existing
execution role if reusing one) → Next → Review and create →
acknowledge Athena will create resources on my behalf → Create data
source. This still creates a Lambda function and its execution role under
the hood — the wizard just wraps it in an AWS Glue connection and does it
all inline on one page, instead of the SAR flow's separate trip to deploy
the Lambda app first. AWS's own guidance
recommends this path for prebuilt connectors including CloudWatch Logs (this
guidance may change — check the linked page); create/rollback stays atomic
and teardown is a singledelete-stack. - Serverless Application Repository (SAR) —
aws serverlessrepo create-cloud-formation-change-setonathena-cloudwatch.yaml,
then execute the change set. Keep this as the fallback for a custom
connector build or an older connector version per the same AWS guidance.
Form the query — two shapes
Preferred — passthrough (CloudWatch Logs Insights syntax)
SELECT * FROM TABLE(system.query(
STARTTIME => '<epoch_ms, clamped>', ENDTIME => '<epoch_ms>',
QUERYSTRING => 'fields @timestamp, @message | filter <selector> | ...',
LOGGROUPNAMES => '<resolved log group>', LIMIT => '<n>'))
The QUERYSTRING is a Logs Insights query. The default <selector> is
source-specific — each record shape has its own discriminator and the wrong
selector matches ZERO rows rather than erroring. See
trace-schema-and-json-paths.md (Rule 4 / Rule 4b) for the per-shape
selectors. Two AgentCore facts beyond the table: the runtime's span streams appear in the
connector automatically once Transaction Search is on (no connector redeploy), and
the conversation content lives in span events[], not attributes (Rule 4b). Let
the caller OVERRIDE the selector (agent traces use a different discriminator), with an
all-rows opt-out. Put the window and any content/finish_reason/status filters in
the same QUERYSTRING — using backtick-quoted dotted field names for a STRING
leaf (e.g. `gen_ai.evaluation.name`), the Insights analogue of the Trino
bracket paths in the schema reference. A numeric or boolean leaf (e.g.
http.status_code, gen_ai.evaluation.passed) does NOT resolve this way —
Logs Insights' automatic field discovery only exposes string leaves for direct
filter/ispresent; extract those with parse first (see the worked selectors
in trace-schema-and-json-paths.md).
Prefer this shape: the log group is a STRING argument, so the connector's
"no uppercase database names" constraint does not apply (it bites only the
standard-SQL path below, where the group is a SQL database identifier).
CloudWatch Logs Insights caps a single query at 10,000 returned rows, so a
query over a high-volume group returns exactly 10,000 and silently truncates
regardless of LIMIT — the count is a cap hit, not the true total. To extract
more, split the window into sub-ranges each small enough to stay under 10,000
rows (newest-first, verifying each sub-range is not itself capped), then
consolidate the shards with the same output contract below.
Fallback — standard federated SQL
SELECT message FROM "<cw-catalog>"."<log_group>"."all_log_streams"
WHERE time BETWEEN <start_ms> AND <end_ms>
AND json_extract_scalar(message, '$.attributes["aws.genai.span_kind"]') = 'LLM'
Use only if passthrough is unavailable. Fields come out of message via Athena
engine-v3 (Trino) JSON functions (json_extract / json_extract_scalar /
json_parse). Dotted gen_ai keys MUST use bracket notation
($["gen_ai.usage.input_tokens"]), not dot notation — a dot splits the key into
non-existent nesting and silently returns NULL. The content lives in a nested
events[] array whose parts[].content is sometimes an object, so use
json_extract (not json_extract_scalar) there. See
trace-schema-and-json-paths.md for the full JSON-path contract. A
mixed-case log group (the Endpoints endpoint group) degrades or fails here
because it becomes the database name — another reason to prefer passthrough.
Scale and cost
The connector reads CloudWatch live per query: it parallelizes scans across the
group's log streams and pushes time-range filters down into CloudWatch Logs, so a
narrow window and a high-selectivity filter are what keep a query cheap and keep
it from throttling. On a high-volume group a broad scan can hit CloudWatch
throttling; the connector has built-in AIMD backoff (tunable via its
throttle_initial_delay_ms / throttle_max_delay_ms / throttle_decrease_factor
/ throttle_increase_ms Lambda env vars), but the first levers are to (a) tighten
STARTTIME/ENDTIME so the time-filter pushdown shrinks the scan, then (b) push
a selective filter into QUERYSTRING; only then tune the env vars, or fall back
to native logs:StartQuery windowed into sub-batches with the same output
contract.
Cost lands as CloudWatch Logs bytes-scanned (DataScanned-Bytes, the StartQuery
operation — the passthrough system.query runs the Logs Insights query inside
CloudWatch), plus the connector's Lambda invocation and S3 spill. Bytes scanned is
the dominant driver, which is why windowing and source-side filtering matter.
Output + run the query
-
Both query shapes MUST be
UNLOAD-wrapped — a bareSELECTemits CSV.
A plainSELECT(either shape) writes its result to the workgroup output
location as CSV (<query-id>.csv, header + quoted fields), which is NOT JSONL
and mismatchesdataset-import's format check. This applies to the preferred
passthrough shape too: a bareSELECT * FROM TABLE(system.query(...))is still a
SELECT, so it also emits CSV. Wrap BOTH shapes inUNLOAD, uncompressed.Passthrough (preferred) — wrap the 5-line
system.query(...)shape from
"Form the query" above:UNLOAD (<the passthrough SELECT * FROM TABLE(system.query(...)) above>) TO 's3://<bucket>/<prefix>/' WITH (format='JSON', compression='NONE')Standard-SQL fallback:
UNLOAD (SELECT message FROM <...>) TO 's3://<bucket>/<prefix>/' WITH (format='JSON', compression='NONE')Both shapes nest the record under the projected column name — the key just
differs. On the standard-SQL fallback (SELECT message), each line is
{"message":"<escaped record JSON>"}. On the passthrough, the query projects
fields @timestamp, @message, so eachUNLOADline is
{"@timestamp":<...>,"@message":"<escaped record JSON>"}— the record is under
@message(with an extra@timestampcolumn). Either waydataset-transformation
unwraps the record column (messageor@message); project only the record
column in the passthrough (fields @message) if you want the simpler
single-key line. Do NOT tryjson_parse(message)to
flatten it:UNLOAD ... format='JSON'rejects a Prestojson-typed column with
NOT_SUPPORTED: Unsupported Hive type: json, andCAST(json_parse(message) AS VARCHAR)fails withINVALID_CAST_ARGUMENT. The passthrough Logs Insights path
(preferred) also needs theUNLOADwrap to land as JSONL on S3.
UNLOADrequires the target prefix to be EMPTY — it will not overwrite and
fails withlocation ... is not emptyif the prefix already holds objects. Use
a unique prefix per run (e.g.<base-prefix>/$(date +%Y%m%dT%H%M%S)/) so a retry
does not fail here.
The drift-proof default is to select the whole record (SELECT messageon the
standard-SQL path, orfields @messageon the passthrough —dataset-transformation
unwraps the record column either way) and leave field extraction todataset-transformation.
Before a full run,
do the 1-row path probe intrace-schema-and-json-paths.md(Rule 5)
so you don't ship an all-NULL dataset from a wrong JSON path. -
Show the user the exact query and get an explicit go before executing —
it reads their trace content and runs a paid Athena scan. Let them narrow the
window/filters first. -
Run the query against Athena with the connector catalog name, an
Athena workgroup with an output S3 location, and the region. Start the
query, poll until it reachesSUCCEEDED, and surface the data-scanned/cost on
failure or completion. -
UNLOADwrites to a PREFIX, not a single named object — it emits one or
more random-named, extension-less objects unders3://<bucket>/<prefix>/.
dataset-importtakes a single S3 URI ending in.jsonl. So after the query,
list the prefix, confirm it is non-empty, then consolidate the shard(s) into one
.jsonlobject and pass that key as theSOURCE. Decide the method from what
the listing shows, and keep customer trace content off local disk where you can.
A single shard needs only a server-side copy/rename to the final.jsonl
key — no download at all. Multiple shards must be joined, and S3 has no
general server-side object concatenation: the only server-side mechanism is a
multipart upload withUploadPartCopy, which requires every part except the
last to be at least 5 MB, so it fails (EntityTooSmall) on the small shards a
narrow trace window typically produces. So the standard multi-shard path is a
streamed concat — read each shard and append in order, writing to a scratch path
and removing it after upload.compression='NONE'above means every shard is
already plain newline-delimited JSONL, so the join is a straight byte concat
with no re-serialization; do NOT copy each shard onto the same key (that
overwrites, keeping only the last). Use the server-side multipart join only when
the shards are known to clear the 5 MB-per-part floor. -
Empty result: if the prefix is empty (0 rows matched), warn (widen the
window, re-check the groupcreationTime, loosen the filter) and STOP — do not
register an empty dataset.
Then register
Hand the single consolidated .jsonl S3 URI to ../../dataset-import/overview.md
(Stage 3) as the SOURCE, with Custom as the format. Follow that workflow — it
fills the dataset name / project, guards the name collision, and needs
sdk-getting-started to have run. The DataSet ARN it returns is the handoff
handle to dataset-transformation.
Children
No children yet.
Like how this is organised?
Build your own Memory tree on knowen.md: notes, decisions and tasks in one connected markdown graph, shared with your team and your AI agents.