Tag Archives: Advanced (300)

Observing and evaluating production agents using OpenSearch Agent Health

Post Syndicated from Ulrich Hinze original https://aws.amazon.com/blogs/big-data/observing-and-evaluating-production-agents-using-opensearch-agent-health/

As AI agents are moving from experimental prototypes to production workloads, teams need visibility into what agents are doing and a systematic way to measure whether they’re doing it well. Traditional testing methodologies like unit and integration tests fall short for this task, as measuring an agent’s quality isn’t a straightforward true/false decision. Instead, agent observability and evaluations (evals for short) provide a two-legged solution to this problem. Agent observability captures the details of an agent’s behavior, and evals compare this behavior to the behavior that you want. With this approach, teams can monitor their agent’s quality over time and introduce agent-specific quality gates in their software development lifecycle.

In this post, we show how to combine an AI agent running on AWS with OpenSearch Agent Health for observability and evals. You will deploy an agent and its observability data pipeline to AWS, then use Agent Health as a local development tool connecting to your cloud resources.

Overview of solution

Agent observability and evaluations rely on OpenTelemetry traces to understand agent behavior. Traces describe the flow of a request through components of a system. OpenSearch Agent Health is a purpose-built tool for analyzing agent traces and running evaluations against an agent for quality control. Although Agent Health works with any open source OpenSearch installation, many AWS customers choose Amazon OpenSearch Ingestion and Amazon OpenSearch Service for ingesting and storing their OpenTelemetry data. You can connect OpenSearch Agent Health to these AWS resources to fetch live data and store its own configuration and evaluation history.

The following diagram shows the overall architecture of the solution presented in this post: Architecture diagram showing the agent, Amazon OpenSearch Ingestion, Amazon OpenSearch Service, and OpenSearch Agent Health observability and evaluation flow

Figure 1: Solution overview

The individual parts are:

  1. AWS Amplify for hosting an assistant-ui chat interface. Connects to the agent backend using the Agent-User Interaction (AG-UI) protocol.
  2. Sample ecommerce AI agent using Strands Agents SDK, deployed to Amazon Bedrock AgentCore runtime, exposing an AG-UI Server-Sent Events (SSE) endpoint. This agent has access to multiple tools, such as product search and shopping basket operations. For this sample project, the tool calls are all simulated within the agent runtime rather than including API calls to other systems. The agent emits messages, reasoning steps, and tool calls as OpenTelemetry traces.
  3. Large language models (LLMs) on Amazon Bedrock. One model (Amazon Nova 2 Lite) is used to power the agent, the other model (Anthropic Claude Opus 4.6) is used to evaluate the agent behavior.
  4. Amazon OpenSearch Ingestion for collecting and transforming the raw agent traces and loading them into an Amazon OpenSearch Service domain. Agent traces have the same structure as regular OpenTelemetry traces, with the addition of generative AI semantics (for example, tool calls and token usage). This means a regular OpenTelemetry pipeline configuration can be used to process agent traces.
  5. OpenSearch Agent Health for analyzing traces and running evaluation test cases and benchmarks against the agent. Agent Health uses the same AG-UI endpoint as the front-end application. It authenticates to the application, to Amazon Bedrock for model functionality, and to Amazon OpenSearch Service using AWS SigV4 authentication.

Walkthrough

In this walkthrough, we showcase how you can use Agent Health and Strands to measure and improve your agent’s quality over time.

We follow these steps:

  • Deploy solution to AWS and test the application.
  • Start Agent Health locally and connect it to cloud resources.
  • Explore agent traces and run evaluations.

We have created a GitHub repository for you to follow along.

Prerequisites

For this walkthrough, you should have the following prerequisites:

  • An AWS account
  • Git
  • Node.js
  • AWS Cloud Development Kit (AWS CDK)

Deploy solution to AWS and test the application

In this section, you check out the repository and deploy the infrastructure to AWS. Be aware that these steps create AWS resources that incur cost. We cover cleanup steps at the end of this post.

First, clone the repository to a local directory:

git clone https://github.com/aws-samples/sample-agent-health-with-amazon-opensearch-service && cd sample-agent-health-with-amazon-opensearch-service

Switch to the infra folder and install dependencies:

cd infra && npm install

Before you can start the deployment, determine the AWS Identity and Access Management (IAM) user or role that you will use to start Agent Health later on. In many cases, this will be the same role that you use to deploy the infrastructure. Set this ARN in your environment by issuing the following command:

export AGENT_HEALTH_READER_ARN=arn:aws:iam::<YOUR_ACCOUNT_ID>:role/<YOUR_ROLE_NAME>

Bootstrap your AWS account for use with AWS CDK:

cdk bootstrap -c agentHealthReaderArn=$AGENT_HEALTH_READER_ARN

Run the infrastructure deployment. Review and acknowledge IAM statement changes when prompted. This takes around 25 minutes to complete:

cdk deploy -R -c agentHealthReaderArn=$AGENT_HEALTH_READER_ARN

The -R parameter defines that if something fails during this deployment, the successfully provisioned resources are retained. Be aware that this command creates AWS resources, incurring cost. Review the cleanup section at the end of this post for removing all created resources.

When the deploy command finishes successfully, you should see an output like the following:

...
AgentObservabilityStack

✨ Deployment time: 1402.42 s

Outputs:
AgentObservabilityStack.AgentEndpoint = https://bedrock-agentcore.us-east-1.amazonaws.com/runtimes/arn%3Aaws%3Abedrock-agentcore%3Aus-east-1%3A123456789012%3Aruntime%2Fretail_agent-abcdefghij/invocations?qualifier=AgentObservabilityStAgentRuntimeEndpointABCDEFGH
AgentObservabilityStack.ChatUrl = https://main.abcdefghijklmn.amplifyapp.com
...

Next, create a user for your application. Retrieve the CDK output value for AgentObservabilityStack.UserPoolId. Create a user for the application using the user pool ID, an email address, and a strong password (minimum eight characters including uppercase, lowercase, letter, and digit):

export COGNITO_EMAIL=<YOUR_EMAIL>
export COGNITO_PASSWORD=<YOUR_PASSWORD>
export USER_POOL=<YOUR_USER_POOL_ID>
aws cognito-idp admin-create-user --user-pool-id $USER_POOL --username $COGNITO_EMAIL --message-action SUPPRESS --user-attributes Name=email_verified,Value=true
aws cognito-idp admin-set-user-password --user-pool-id $USER_POOL --username $COGNITO_EMAIL --password "$COGNITO_PASSWORD" --permanent

You can now access the retail agent application. From the CDK output values, retrieve the value for AgentObservabilityStack.ChatUrl. Copy and paste this URL into your browser. Log in with your email and password. You should now see the agent interface:

Sample retail agent chat interface showing the ecommerce assistant ready for queries

Figure 2: Sample retail agent user interface

Experiment with the application. Here is an example sequence of queries you can put in:

  • Do you have books on Python?
  • Is this in stock?
  • Put it into my basket.
  • What else can you do for me?

Start Agent Health

Now that you have the infrastructure running, you can start OpenSearch Agent Health locally and connect it to your cloud resources.

The CDK infrastructure deployment created a file cdk-output.json, which contains all relevant configuration values for Agent Health. We’ve already created a file agent-health/agent-health.config.ts that pulls these values dynamically in your environment, so you can start Agent Health without any further configuration.

Open a terminal and start Agent Health by running the following command:

cd ../agent-health && npm install
npx @opensearch-project/agent-health

Open http://localhost:4001 in your browser to access Agent Health UI. Choose Agent Traces in the sidebar menu to access your agent’s traces. You should see traces from your previous interactions:

Agent Health Traces view listing agent traces captured from previous interactions

Figure 3: Agent traces. As Agent Health is in active development, this interface might have changed since the time of writing

Expand the trace and explore the information it contains, such as token count and agent trajectory (sequence of messages, reasoning steps, and tool calls).

If you’re unable to access the application or see any traces, verify the following:

  • Check Agent Health logs in your terminal for any errors. Also check whether Agent Health is running on an alternative port, like 4002 instead of 4001.
  • If there are permission errors when accessing traces from OpenSearch, verify that the AWS credentials in your terminal match the principal (user or role) that you specified under the agentHealthReaderArn CDK parameter during cdk deploy. This principal must have ESHttpGet:* IAM permissions. Agent Health uses your current AWS credentials to access the OpenSearch API for querying traces. The OpenSearch API is guarded by both IAM and OpenSearch fine-grained access control.

Create and run a test

Choose Test Cases and New Test Case. Fill out the required fields with the following information:

  • Name: Should add to cart.
  • Initial Prompt: Add some wireless headphones to my cart. Take any that you have in stock.
  • Expected Outcomes: PROD-001 added to cart.

Back in the test cases overview, select the created test case and choose Run Test. In the Configure Run dialog, choose Retail Assistant (production) for Agent, Tool Usage Efficiency for Evaluator, Claude Opus 4.8 for Judge Model, and choose Start Run.

Agent Health now runs the configured initial prompt against the agent. The agent completes the task and sends execution traces to OpenSearch. Agent Health uses an evaluation model to check both agent responses and traces on successful execution, according to the defined expected outcomes. After the test is completed, go through the different tabs to check the test results.

Agent Health evaluation report showing test results across multiple tabs

Figure 4: Agent Health evaluation report

If you’re unable to run the test, check the following:

  • Agent Health automatically creates an Amazon Cognito token for your user upon start, but this token can expire. Restarting Agent Health creates a new token. Verify that both the COGNITO_EMAIL and COGNITO_PASSWORD variables are still set in your terminal environment.

Beyond test cases

After running a single test case, choose Benchmarks in the sidebar menu. With Benchmarks, you can run multiple test cases in parallel and summarize their results. You can compare benchmark runs by choosing Evaluation Runs in the sidebar, where you can analyze trends in pass rate, cost, and duration over time. Lastly, choose Evaluators to define your own evaluation logic beyond the predefined ones.

You can also run Agent Health tests with its command-line interface, which is handy for automation and continuous integration (CI). The equivalent command of running the preceding test is:

npx @opensearch-project/agent-health run -t <TEST_CASE_ID> -a "Retail Assistant" -e system-tool-usage --judge-model claude-opus-4.8 -e system-tool-usage

where TEST_CASE_ID can be retrieved from the browser URL when you visit the Agent Health UI (test case IDs start with tc-).

Agent Health stores all test cases, other configuration, and reports locally on disk in the agent-health/agent-health-data directory.

Cleaning up

To avoid incurring future charges, delete the resources:

cd ../infra && cdk destroy -c agentHealthReaderArn=$AGENT_HEALTH_READER_ARN

Conclusion

In this post, you learned to set up and use OpenSearch Agent Health for production agent observability and evaluations. To discover more features, see the Agent Health documentation pages. You can discuss and request additional features, and get help with setup, through the issues in the GitHub project. For more information, see the observability documentation for Amazon OpenSearch Service, where you can learn about the features available to build observability for both agents and traditional systems using OpenSearch. To investigate issues in production AI agents, see the recent post Unified observability in Amazon OpenSearch Service.


About the authors

Ulli Hinze

Ulli is a Solutions Architect based in Berlin, Germany. He focuses on SaaS, agentic AI, and OpenSearch, and helps customers build and modernize their solutions on AWS. His previous roles included software development, platform engineering, and architecture.

Megha Goyal

Megha is a Senior Software Engineer at AWS OpenSearch. For the past year she has focused on AI agent observability and evaluations, building Agent Health — an open-source developer tool for agents. Previously, she worked on data integrations with Amazon CloudWatch and Amazon Security Lake for the observability and security space. When she’s not building software, she enjoys designing and 3D-printing models at home.

Rekha Thottan

Rekha Thottan

Rekha is a Senior Product Manager Technical on the Amazon OpenSearch Service team.

Accelerate Apache Spark debugging on Amazon EMR with AWS DevOps Agent

Post Syndicated from Kalyan Janaki original https://aws.amazon.com/blogs/big-data/accelerate-apache-spark-debugging-on-amazon-emr-with-aws-devops-agent/

When an Apache Spark job fails on Amazon EMR, the root cause can hide in executor logs, memory profiles, or application code. As data pipelines grow in complexity, correlating logs, metrics, and traces across multiple services requires significant operational effort. AWS DevOps Agent handles this investigation autonomously while keeping operators in the loop to review findings and approve fixes. From a single chat prompt, it produces a root cause and mitigation plan, often without any human involvement beyond the initial question.

The native AWS API tools in AWS DevOps Agent don’t extend into Spark-internal artifacts. Sometimes those tools can’t reach the evidence that pins down the root cause: a Spark History Server event log, executor Python worker memory, or a line of code that allocated too much. In these cases, AWS DevOps Agent can describe symptoms (“the executor exited with code 1”) but can’t identify the actual antipattern that caused them.

This post shows how to extend AWS DevOps Agent to investigate failures in Apache Spark workloads on Amazon EMR. You register the Apache Spark Troubleshooting Agent for Amazon EMR, a managed Model Context Protocol (MCP) server hosted by AWS, as a custom capability provider in your AWS DevOps Agent space. You route the traffic over AWS PrivateLink so MCP calls never traverse the public internet. Then you watch a single agent chat session investigate a deliberately failing Spark job, from Amazon CloudWatch alarm to line-numbered root cause, in about two minutes.

Prerequisites

Before you begin, make sure you have the following:

How AWS DevOps Agent discovers custom tools through MCP

Model Context Protocol (MCP) is an open standard that defines how AI agents discover and invoke external tools. AWS DevOps Agent supports connecting to custom MCP servers, which means you can expose new capabilities to it without modifying the agent itself. When you connect an MCP server to AWS DevOps Agent, the agent automatically discovers the available tools, understands their schemas, and calls them as part of its investigation workflow. You build and connect the MCP server, and the agent handles the rest.

MCP tools sit alongside the agent’s built-in AWS API tools. During a single investigation, the agent can interleave calls to cloudwatch.describe-alarms, emr-serverless.get-job-run, and a custom MCP tool such as analyze_spark_workload. The agent picks the right one for each subtask. You augment the agent’s reach without replacing what it already does.

For this integration, you don’t build an MCP server. The Apache Spark Troubleshooting Agent for Amazon EMR is itself a managed MCP server, hosted by AWS at a regional endpoint. Your job is to register that endpoint with AWS DevOps Agent and authorize the agent to call it. This requires a network path from the agent to the endpoint, plus an IAM role for AWS Signature Version 4 request signing.

Why Spark internals visibility matters

The actual root cause for a Spark failure usually lives somewhere none of those APIs (such as Amazon CloudWatch Logs Insights, AWS CloudTrail, or Amazon EMR step-status calls) can reach:

The Apache Spark Troubleshooting Agent for Amazon EMR reads the following sources.

The Spark History Server event log is a per-job archive in Amazon Simple Storage Service (Amazon S3) with stage timings, task-level metrics, executor utilization, shuffle read/write volumes, and garbage-collection pauses. Amazon EMR exposes this data through the Spark UI on Amazon EMR Serverless, Amazon EMR on Amazon Elastic Compute Cloud (Amazon EC2), and Amazon EMR on Amazon Elastic Kubernetes Service (Amazon EKS), but interpreting signals like data skew, executor memory pressure, or stages that take significantly longer than expected requires familiarity with Spark internals.

  • The Spark query plan — the logical and physical plan the driver compiled. Without it, you can’t identify antipatterns such as unnecessary data repartitioning or missing broadcast hints that trigger expensive shuffles.
  • The application source code in Amazon S3 — the .py or .jar code artifact the job ran. Without it, you can’t quote the offending line of a mapPartitions user-defined function or an inefficient collect().
  • The Python worker process telemetry — the PySpark worker is a separate Python subprocess outside the Java Virtual Machine’s (JVM) managed memory. When it crashes from spark.executor.pyspark.memory exhaustion, the JVM driver sees a generic “executor exited unexpectedly” message. The actual cause is invisible to standard JVM-level logs.

When the agent invokes analyze_spark_workload during an investigation, it returns a structured analysis with the antipattern identified at the line level, the offending stage isolated, and a concrete fix: both code changes and configuration changes.

Integrating AWS DevOps Agent with Apache Spark Troubleshooting MCP

This section explains how AWS DevOps Agent connects to the Apache Spark Troubleshooting Agent through a private MCP endpoint and orchestrates the investigation workflow.

How it works

Architecture diagram showing AWS DevOps Agent connecting to the Apache Spark Troubleshooting Agent over AWS PrivateLink

Figure 1: Integration architecture between AWS DevOps Agent and the Apache Spark Troubleshooting Agent for Amazon EMR over AWS PrivateLink

  1. You submit an investigation prompt in AWS DevOps Agent.
  2. AWS DevOps Agent sends a SigV4-signed MCP call into your Amazon VPC through the AWS DevOps Agent private connection.
  3. The private connection forwards the request to the Interface VPC Endpoint.
  4. The endpoint routes the request over AWS PrivateLink to the Apache Spark Troubleshooting Agent for Amazon EMR, which AWS manages.
  5. The MCP service reads from your data sources (Amazon EMR, Amazon S3, Amazon CloudWatch Logs) using the same IAM role AWS DevOps Agent assumed for the call.
  6. When a CloudWatch alarm transitions to ALARM state (for example, a failed-jobs alarm for your Amazon EMR Serverless application), AWS DevOps Agent automatically triggers an investigation without manual intervention.
  7. AWS DevOps Agent decides which tools to call based on the prompt. For a Spark failure, that includes the Apache Spark Troubleshooting MCP server you registered as a capability provider.
  8. Each MCP request is signed with AWS Signature Version 4 using the IAM role assigned to the capability provider. The request travels from AWS DevOps Agent into your Amazon VPC through the private connection. This private connection is a managed VPC Lattice resource gateway you created during setup.
  9. From the resource gateway, the request flows to the Interface VPC Endpoint for the Amazon SageMaker Unified Studio MCP service, then on to the Apache Spark Troubleshooting Agent. The traffic stays entirely on the AWS network.
  10. The MCP server reads the inputs it needs from your AWS account using the IAM role that you assigned to the capability provider during MCP server registration. This role grants access to the Spark History Server event log and application source code in Amazon S3, the driver and executor stdout streams in Amazon CloudWatch Logs, and the job-run metadata from Amazon EMR Serverless.
  11. The MCP server returns its diagnostic findings to AWS DevOps Agent. The agent then analyzes the results, identifies the root cause, and presents recommended fixes both code-level and configuration-level in your chat.

Setting up the demo

As part of this demo, this post includes a sample AWS CloudFormation template, tested in the us-east-1 Region, that provisions the following resources for the walkthrough:

  • A dedicated Amazon Virtual Private Cloud (Amazon VPC) with two private subnets in Availability Zones supported by the Apache Spark Troubleshooting Agent for Amazon EMR.
  • An Interface VPC Endpoint for the Apache Spark Troubleshooting Agent for Amazon EMR.
  • An IAM role that AWS DevOps Agent assumes to invoke the Apache Spark Troubleshooting MCP server with AWS Signature Version 4.
  • A deliberately failing PySpark workload running on Amazon EMR Serverless, including the Amazon EMR Serverless application, the Spark execution role, and the demo logs stored in Amazon S3 bucket.
  • An Amazon CloudWatch alarm that fires when the demo job fails. This alarm is used as the trigger for the agent investigation later in this section.

Step 1: Clone the repository

Clone the git repository for the CloudFormation template, PySpark script, and Parquet data.

git clone https://github.com/aws-samples/sample-aws-data-processing-and-analytics.git

Step 2: Deploy the AWS CloudFormation stack

Deploy the template using the following AWS CLI command.

cd sample-aws-data-processing-and-analytics/blogs/devops-agent-spark-mcp-integration

aws cloudformation create-stack \
  --stack-name spark-troubleshooting-demo \
  --template-body file://cloudformation/spark-troubleshooting-devops-agent-blog.yaml \
  --capabilities CAPABILITY_NAMED_IAM \
  --region us-east-1

The stack reaches CREATE_COMPLETE in approximately 4–6 minutes. When it does, capture the following stack outputs, which you paste into the AWS DevOps Agent console in the next two steps:

  • DemoVpcId — the VPC ID for the AWS DevOps Agent private connection.
  • DemoSubnetIds — the two subnet IDs for the AWS DevOps Agent private connection.
  • SMUSVpcEndpointSecurityGroupId — the security group ID.
  • TroubleshootingRoleArn — the IAM role Amazon Resource Name (ARN).
  • MCPEndpointURL — the MCP endpoint URL to register.
  • FailedJobsAlarmName — the CloudWatch alarm name to reference in your investigation prompt.
  • DemoBucket — the S3 bucket name where you copy the demo script and Parquet data.

To retrieve all outputs at once, use the following AWS CLI command.

aws cloudformation describe-stacks \
  --region us-east-1 \
  --stack-name spark-troubleshooting-demo \
  --query "Stacks[0].Outputs" --output table
# Get your bucket name from the stack outputs
DEMO_BUCKET=$(aws cloudformation describe-stacks --stack-name spark-troubleshooting-demo --region us-east-1 --query 'Stacks[0].Outputs[?OutputKey==`DemoBucket`].OutputValue' --output text)

# Copy the script
cd sample-aws-data-processing-and-analytics/blogs/devops-agent-spark-mcp-integration
aws s3 cp scripts/customer_events_aggregator.py s3://$DEMO_BUCKET/customer_events_aggregator.py

# Copy the Parquet data
aws s3 cp data/ s3://$DEMO_BUCKET/data/ --recursive

Step 3: Create an agent space

The agent space defines which AWS account and Region the agent monitors, which IAM role it assumes, and which capability providers, including MCP servers, it can call.

Follow the steps in Creating an Agent Space in the AWS DevOps Agent User Guide. When completing those steps, use the following values:

Parameter Value
Name data-pipeline-troubleshooting
Region us-east-1
Agent Space role Choose Auto-create a new DevOps Agent role — the console generates a DevOpsAgentRole-AgentSpace* role with AIOpsAssistantPolicy attached
Optional integrations Not required

After the agent space reaches Active status, proceed to create the private connection.

Step 4: Create the AWS DevOps Agent private connection

AWS DevOps Agent uses the private connection to reach into your Amazon VPC. Follow the steps in Connecting to privately hosted tools in the AWS DevOps Agent User Guide. You can use either the console or the AWS CLI command documented under Create a private connection.

When completing those steps, use the following values from your CloudFormation stack outputs:

Parameter Value
Name A descriptive name (for example, spark-private)
VPC DemoVpcId from your stack outputs
Subnets Both subnet IDs from DemoSubnetIds
Security group SMUSVpcEndpointSecurityGroupId
TCP port ranges (Advanced configuration) 443
Host address (Service target details) sagemaker-unified-studio-mcp.us-east-1.api.aws
DNS resolution In VPC (private DNS)
Certificate public key None

After the connection reaches Active status, proceed to Step 5.

Step 5: Register the Apache Spark Troubleshooting MCP server as a capability provider

With the private connection in place, register the MCP server as a capability provider. Follow the steps in Registering an MCP server at the account level in the AWS DevOps Agent User Guide.

When completing those steps, use the following values:

Parameter Value
Name spark-troubleshooting
Endpoint URL MCPEndpointURL from your stack outputs
Connect to endpoint using a private connection Selected

Step 6: Add the MCP server to the agent space

With the MCP server registered, you need a workspace where investigations run. The agent space defines which AWS account and Region the agent monitors, which IAM role it assumes, and which capability providers, including MCP servers, it can call.

  1. In the MCP Server section, choose Add.
MCP Server section of the agent space detail page with an Add button

Figure 2: MCP Server section of the agent space detail page

  1. In the Add a capability dialog, locate spark-troubleshooting in the list of registered MCP servers and choose Add.
Add a capability dialog listing the spark-troubleshooting MCP server

Figure 3: Add a capability with the spark-troubleshooting MCP server listed

  1. On the Select MCP server tools page, both tools that the Apache Spark Troubleshooting Agent for Amazon EMR publishes are listed: analyze_spark_workload and analyze_spark_history_server_endpoint. Select both checkboxes, then choose Save.
Select MCP server tools page with both Spark troubleshooting tools checked

Figure 4: The Select MCP server tools page with both Spark troubleshooting tools selected

The agent space connects to the MCP server, lists its tools, and displays 2 Available / 2 Connected. Both tools are now part of your agent’s catalog.

MCP Server section showing spark-troubleshooting connected with two available and two connected tools

Figure 5: MCP Server section showing spark-troubleshooting connected with both tools available

Seeing it in action

To see the integration end to end, you submit a PySpark job, watch the CloudWatch alarm move to ALARM, and then ask AWS DevOps Agent to investigate using the alarm name.

The failing workload

The CloudFormation template provisioned an Amazon EMR Serverless application called analytics-events-platform and configured a sample PySpark job, customer_events_aggregator.py. The script simulates a common Python-side memory bug: a mapPartitions user-defined function accumulates 11 copies of every input row in an in-memory Python list before yielding results, while the job runs with spark.executor.pyspark.memory=256m. The Python worker process exceeds the 256 MB cap, the kernel kills it, Spark retries four times, and the stage is marked failed.

Submit the failing job

Run the DemoSubmitJobCommand from your stack outputs in your terminal. It looks like this:

aws emr-serverless start-job-run \
  --region us-east-1 \
  --application-id <DemoApplicationId> \
  --execution-role-arn <DemoExecutionRoleArn> \
  --name daily-customer-events-rollup \
  --job-driver '{"sparkSubmit":{"entryPoint":"s3://<DemoBucket>/customer_events_aggregator.py","entryPointArguments":["<DemoBucket>"],"sparkSubmitParameters":"--conf spark.executor.cores=2 --conf spark.executor.memory=1g --conf spark.executor.pyspark.memory=256m --conf spark.executor.instances=2"}}' \
  --configuration-overrides '{"monitoringConfiguration":{"s3MonitoringConfiguration":{"logUri":"s3://<DemoBucket>/logs/"}}}'

The command returns a jobRunId. Note it down. You will see it later in the agent’s investigation.

The job goes through PENDING to SCHEDULED to RUNNING to FAILED and reaches FAILED state in roughly four minutes.

Watch the CloudWatch alarm fire

The CloudFormation template also created a CloudWatch alarm named <DemoApplicationId>-FailedJobs (the exact name is in the FailedJobsAlarmName stack output). The alarm watches the FailedJobs metric in the AWS/EMRServerless namespace, scoped to your demo application, and flips to ALARM within a minute or two of the job failing.

Open the Amazon CloudWatch console, choose Alarms in the left navigation pane, and confirm the alarm is in In alarm state.

Amazon CloudWatch console alarm detail page showing the FailedJobs alarm in alarm state

Figure 6: The Amazon CloudWatch alarm detail page showing the FailedJobs alarm in the In alarm state

Ask AWS DevOps Agent to investigate

  1. Open your AWS DevOps Agent space.
  2. In the left navigation pane, choose Operator Access, then choose Incidents.
  3. Choose Start an investigation.
  4. Paste the following prompt, replacing <FailedJobsAlarmName> with the value from your stack outputs:

CloudWatch alarm in us-east-1 just went into ALARM state. Investigate why and recommend a fix

AWS DevOps Agent Start an investigation panel with the alarm prompt entered

Figure 7: AWS DevOps Agent Start an investigation panel with the Amazon CloudWatch alarm investigation prompt

The agent’s investigation chains together native AWS API tools and the Apache Spark Troubleshooting MCP tool you registered:

  1. use_aws cloudwatch describe-alarms — fetches the alarm definition and reads its metric dimensions, identifying that the alarm is scoped to Amazon EMR Serverless application <DemoApplicationId>.
  2. use_aws emr-serverless list-job-runs — finds the most recent FAILED job run on that application.
  3. use_aws emr-serverless get-job-run — pulls the FAILED run’s metadata and last-known error.
  4. spark-troubleshooting analyze_spark_workload — invokes the Apache Spark Troubleshooting Agent for Amazon EMR through the MCP capability provider, passing the application ID and job run ID. This is where the deep analysis happens.

Review the root cause and fix

When the investigation completes, AWS DevOps Agent presents the results across two tabs: Investigation timeline and Root cause.

The Investigation timeline shows every step the agent took: skills loaded, native AWS API calls made, and the moment it called the analyze_spark_workload MCP tool to analyze the failed Spark job. Each entry is expandable so you can audit the inputs and outputs.

Investigation timeline listing the agent tool calls and the MCP invocation

Figure 8: Investigation timeline tab showing the sequence of agent tool calls and the spark-troubleshooting MCP invocation

The Root cause tab is where the answer lands. It is organized into three sections that mirror what an experienced engineer would write in an incident report:

Root cause tab showing impact, root causes, and key findings for the memory failure

Figure 9: The Root cause tab showing the impact summary, identified root causes, and key findings for the Spark memory exhaustion failure

  • Impact — what failed, when, and for how long. For our demo, this calls out that the daily-customer-events-rollup job on the analytics-events-platform application failed with a MemoryError and that the alarm transitioned to ALARM state at the time of the failure.
  • Root causes — the actual antipattern. The agent identifies that customer_events_aggregator.py combines three compounding issues: an expand_event function (line 23) that amplifies each input row 11×, a repartition(1) that funnels all data into a single partition on a single executor, and a collect() (line 31) that pulls the amplified dataset back to the driver. All three run with only 1 GB of executor memory.
  • Key findings — supporting facts behind the diagnosis, including the executor memory configuration, the application’s maximum capacity, and how the agent confirmed each fact from the analyzed artifacts.

Both the antipattern identification and the supporting evidence come from artifacts the agent could only reach through the MCP tool: the application source code in Amazon S3, the Spark History Server event log, and the query plan. Without the Apache Spark Troubleshooting Agent for Amazon EMR plugged in, AWS DevOps Agent would have stopped at “the executor exited with a memory error.”

Clean up

To avoid ongoing charges, delete the resources you created. Some resources are managed by the AWS DevOps Agent console and must be removed there first. Otherwise, the CloudFormation stack deletion fails.

  1. In the AWS DevOps Agent console, open your data-pipeline-troubleshooting agent space, choose the MCP Server section, select spark-troubleshooting, and choose Remove.
  2. From the Agent spaces list, select data-pipeline-troubleshooting and choose Delete.
  3. In Capability Providers, select spark-troubleshooting and choose Deregister.
  4. In Capability Providers → Private connections, select smus-spark-private and choose Delete.
  5. Delete the AWS CloudFormation stack. This removes the Amazon VPC, the Interface VPC Endpoint, the security group, the IAM role, the Amazon EMR Serverless application, the Spark execution role, the Amazon CloudWatch alarm, and the demo logs bucket.
aws cloudformation delete-stack \
  --region us-east-1 \
  --stack-name spark-troubleshooting-demo

Conclusion

In this post, you connected the Apache Spark Troubleshooting Agent for Amazon EMR to AWS DevOps Agent as a custom MCP capability provider. You kept the traffic on the AWS network with AWS PrivateLink, and ran a failing PySpark job to see the integration end to end. A CloudWatch alarm fired, you asked the agent to investigate, and a single chat session returned the root cause along with code and configuration fixes.

You can extend this pattern beyond the demo scenario. Consider connecting the MCP server to agent spaces that monitor your production Amazon EMR environment. Any Spark job that writes a History Server event log becomes diagnosable through the same workflow.

To continue learning, explore the following resources:

If you’ve already integrated the Apache Spark Troubleshooting Agent into your operational workflow, or if you’re exploring other MCP-based extensions for AWS DevOps Agent, we want to hear about your experience. Share your thoughts and questions in the comments.


About the authors

Kalyan Janaki

Kalyan Janaki

Kalyan is Senior Big Data & Analytics Specialist with Amazon Web Services. He helps customers architect and build highly scalable, performant, and secure cloud-based solutions on AWS.

Aneesh Varghese

Aneesh Varghese

Aneesh is a Senior Technical Account Manager at AWS with more than 20 years of Information Technology industry experience. Aneesh supports enterprise customers in cost optimization strategies, Cloud operations, MLOps, providing advocacy and strategic technical guidance to help plan and build solutions using AWS best practices. Outside of work, Aneesh likes to spend time with family, play Basketball and Badminton

Scheduling email campaigns at scale with Amazon EventBridge Scheduler

Post Syndicated from Oluwaseun Ademuwagun original https://aws.amazon.com/blogs/compute/scheduling-email-campaigns-at-scale-with-amazon-eventbridge-scheduler/

Scheduling email campaigns becomes more complex when you need to send email to millions of recipients at the unique time best suited for each customer. Consider these examples:

  • A flash sale might need to hit inboxes at 9 AM local time across every time zone.
  • A follow-up email (often known as a drip sequence) might need to send a second message exactly 3 days after the first message per subscriber.
  • A re-engagement campaign might target users who haven’t logged in for 30 days.

The scheduling requirements involve multiple considerations. You’re sending hundreds of millions of messages, each at its own optimal moment personalized to the recipient’s time zone and behavior.

In this post, we walk through how to use Amazon EventBridge Scheduler to personalize email notifications to each recipient. We create one schedule per recipient to deliver each email at its individually optimal moment, with zero idle compute cost. We also show how Amazon EventBridge Scheduler handles higher volumes. Amazon EventBridge Scheduler supports billions of schedules. By default, you have a quota of 10 million schedules.

Solution overview

When every recipient has their own ideal delivery time, you need a scheduling layer that can hold billions of individual send intents and fire each one at the right moment. Most teams reach for one of three familiar patterns, each with tradeoffs that become painful at scale.

  1. Batch cron jobs: A job runs every hour, queries for all messages due in the next window, and sends them out. Recipients get email in imprecise hourly batches. At scale, the batch job itself becomes a bottleneck, processing millions of rows per run, competing for database connections, and creating a sudden spike in load on the email provider.
  2. Delay queues: You can use Amazon Simple Queue Service (Amazon SQS) as a delay queue. A delay queue postpones the delivery of new messages to a customer for a set time. A limitation of this approach is that Amazon SQS caps delays at 15 minutes.
  3. Third-party campaign tools: Offload to a SaaS email platform. This works until you need tight integration with your application data, custom send-time optimization, or control over delivery infrastructure. You’re also paying per-recipient fees that compound at scale.

All three approaches either sacrifice precision (batching), hit architectural limits (delay queues), or surrender control (third-party tools).

The building block approach

Amazon EventBridge Scheduler treats each email send as a discrete scheduled action. Instead of “process all messages due this hour,” you express the intent directly: “send this email to this person at this time.” Amazon EventBridge Scheduler holds that intent with zero compute cost until the moment arrives, then triggers the scheduled action. See the Amazon EventBridge Scheduler User Guide for the full API reference and current service quotas.

For email campaigns, Amazon EventBridge Scheduler becomes the send-time dispatcher, the component that schedules every email in a campaign for its individually optimal moment, whether that’s timezone-adjusted, behavior-triggered, or sequence-driven.

Architecture diagram

The architecture follows an event-driven, per-recipient scheduling pattern for an email campaign. To start the campaign, you first define the target audience and the content they receive. Next, you need a way to create the per-recipient schedule. To do that for a campaign that can contain millions of recipients, you need a scalable mechanism to create the schedules. You can achieve this with an AWS Step Functions state machine, a serverless workflow service that coordinates multiple AWS services into structured, visual workflows called state machines. In this solution, we orchestrate the creation of the schedules by using a Distributed Map state within the state machine, which lets us fan out and accelerate schedule creation. It does this by splitting a large dataset into chunks and processing them across thousands of parallel child executions. It reads the recipient list from Amazon Simple Storage Service (Amazon S3), applies time zone logic per recipient, and creates an individual Amazon EventBridge Scheduler resource for each recipient in parallel. After the workflow creates all schedules, the execution completes.

The actual email delivery happens later, entirely decoupled from the campaign creation step. At the scheduled time, Amazon EventBridge Scheduler invokes Amazon Simple Email Service (Amazon SES) directly, passing the template name and personalization data as template variables. For campaigns requiring complex personalization logic (conditional content, real-time suppression checks, or data enrichment), you can optionally route through an AWS Lambda function before SES. If you need to adjust timing or content for specific recipients, you can update their individual schedules directly without reprocessing the entire campaign.

Figure 1: Per-recipient email scheduling architecture with Amazon EventBridge Scheduler

Walkthrough

The solution uses four core components that work together: a campaign manager to define send-time rules, Step Functions Distributed Map to fan out and accelerate schedule creation, Amazon EventBridge Scheduler to hold each per-recipient intent and deliver through Amazon SES directly, and automatic cleanup through schedule self-deletion.

How it works

  1. Create the campaign: A marketer defines the campaign: audience segment, email template, and send-time rules (for example, “9 AM in each recipient’s local time zone” or “24 hours before a Black Friday sale”).
  2. Campaign manager fans out: An AWS Step Functions workflow uses Distributed Map to iterate over the recipient list and create one Amazon EventBridge Scheduler schedule per recipient per campaign step directly through SDK integration. Each schedule encodes the exact send time for that individual.
  3. Amazon EventBridge Scheduler fires at the right moment: At each recipient’s scheduled time, Amazon EventBridge Scheduler invokes Amazon SES directly through a universal target, passing the template name and personalization data (recipient name and attributes) as template variables.
  4. SES personalizes and sends: Amazon SES renders the email template with the provided data and delivers the message.
  5. Schedule self-deletes: ActionAfterCompletion='DELETE' prevents the accumulation of spent schedules.

Prerequisites

To follow along with this walkthrough, you need the following:

  • AWS account and permissions: An active AWS account with permissions to create Amazon EventBridge Scheduler schedules, AWS Step Functions state machines, and Amazon SES identities, along with an AWS Identity and Access Management (IAM) role for Amazon EventBridge Scheduler to invoke Amazon SES.
  • Development environment: Python 3.13 or later, AWS SDK for Python (Boto3) version 1.26 or later, and AWS Command Line Interface v2 (AWS CLI v2).
  • Amazon SES configuration: Move your Amazon SES account out of sandbox mode to allow sending to arbitrary recipients.

Scaling the fan-out with Step Functions

For campaigns with millions of recipients, use AWS Step Functions Distributed Map to parallelize schedule creation. When you want to activate a campaign, you trigger a Step Functions workflow. This workflow fans out and creates schedules across the recipient list by using a Distributed Map with direct SDK integration. The direct SDK integration between Step Functions and Amazon EventBridge Scheduler lets each child execution call CreateSchedule directly. The following state machine definition reads recipients from an Amazon S3 CSV file and creates schedules in parallel:

{
  "Comment": "Fan out campaign schedule creation via direct SDK integration",
  "StartAt": "EnsureScheduleGroup",
  "States": {
    "EnsureScheduleGroup": {
      "Type": "Task",
      "Resource": "arn:aws:states:::aws-sdk:scheduler:createScheduleGroup",
      "Parameters": {
        "Name.$": "States.Format('campaign-{}', $.campaign_id)"
      },
      "ResultPath": null,
      "Catch": [
        {
          "ErrorEquals": [
            "Scheduler.ConflictException"
          ],
          "ResultPath": null,
          "Next": "FanOutRecipients"
        }
      ],
      "Next": "FanOutRecipients"
    },
    "FanOutRecipients": {
      "Type": "Map",
      "ItemProcessor": {
        "ProcessorConfig": {
          "Mode": "DISTRIBUTED",
          "ExecutionType": "STANDARD"
        },
        "StartAt": "BuildScheduleInput",
        "States": {
          "BuildScheduleInput": {
            "Type": "Pass",
            "Parameters": {
              "schedule_name.$": "States.Format('campaign-{}-{}', $.campaign_id, $.recipient.id)",
              "group_name.$": "States.Format('campaign-{}', $.campaign_id)",
              "schedule_expression.$": "States.Format('at({}T{}:00:00)', $.send_date_date, $.send_hour)",
              "timezone.$": "$.recipient.timezone",
              "target_input": {
                "FromEmailAddress": "[email protected]",
                "Destination": {
                  "ToAddresses.$": "States.Array($.recipient.email)"
                },
                "Content": {
                  "Template": {
                    "TemplateName.$": "$.template_id",
                    "TemplateData.$": "States.JsonToString($.recipient.attributes)"
                  }
                }
              }
            },
            "Next": "CreateSchedule"
          },
          "CreateSchedule": {
            "Type": "Task",
            "Resource": "arn:aws:states:::aws-sdk:scheduler:createSchedule",
            "Retry": [
              {
                "ErrorEquals": [
                  "Scheduler.SdkClientException"
                ],
                "IntervalSeconds": 2,
                "MaxAttempts": 3,
                "BackoffRate": 2
              }
            ],
            "Parameters": {
              "Name.$": "$.schedule_name",
              "GroupName.$": "$.group_name",
              "ScheduleExpression.$": "$.schedule_expression",
              "ScheduleExpressionTimezone.$": "$.timezone",
              "FlexibleTimeWindow": {
                "Mode": "FLEXIBLE",
                "MaximumWindowInMinutes": 5
              },
              "Target": {
                "Arn": "arn:aws:scheduler:::aws-sdk:sesv2:sendEmail",
                "RoleArn": "arn:aws:iam::976764934189:role/CampaignFanOutRole-dev",
                "Input.$": "States.JsonToString($.target_input)",
                "RetryPolicy": {
                  "MaximumEventAgeInSeconds": 7200,
                  "MaximumRetryAttempts": 5
                }
              },
              "ActionAfterCompletion": "DELETE"
            },
            "ResultPath": null,
            "End": true
          }
        }
      },
      "ItemReader": {
        "Resource": "arn:aws:states:::s3:getObject",
        "ReaderConfig": {
          "InputType": "CSV",
          "CSVHeaderLocation": "FIRST_ROW"
        },
        "Parameters": {
          "Bucket.$": "$$.Execution.Input.recipient_bucket",
          "Key.$": "$$.Execution.Input.recipient_key"
        }
      },
      "ItemSelector": {
        "campaign_id.$": "$$.Execution.Input.campaign_id",
        "template_id.$": "$$.Execution.Input.template_id",
        "send_date_date.$": "$$.Execution.Input.send_date_date",
        "send_hour.$": "$$.Execution.Input.send_hour",
        "recipient": {
          "id.$": "$$.Map.Item.Value.id",
          "email.$": "$$.Map.Item.Value.email",
          "timezone.$": "$$.Map.Item.Value.timezone",
          "attributes": {
            "first_name.$": "$$.Map.Item.Value.first_name",
            "signup_date.$": "$$.Map.Item.Value.signup_date"
          }
        }
      },
      "MaxConcurrency": 1000,
      "ResultPath": null,
      "End": true
    }
  }
}

Concurrency alignment with Amazon EventBridge Scheduler API limits

Step Functions Distributed Map supports up to 10,000 concurrent child workflows. Each child calls the CreateSchedule API directly, which has a default rate limit of 5,000 TPS. This limit is sufficient for most campaigns. If your campaign volumes require higher throughput, check your current quotas in the Service Quotas console and request an increase.

To avoid throttling, set MaxConcurrency below the CreateSchedule TPS quota. A value of 2,500 provides a comfortable buffer to account for bursts and retries without requiring a quota change. For larger campaigns, request an increase through AWS Service Quotas (adjustable to tens of thousands) and raise MaxConcurrency to match.

Canceling a campaign

A schedule group is an Amazon EventBridge Scheduler resource used to organize schedules. For this use case, we have a schedule group per campaign. If you need to pull a campaign (error in content, legal issue, or strategy change), you can cancel all scheduled sends for that campaign by deleting the entire schedule group. The following code shows how to cancel all pending sends for a campaign:

def cancel_campaign(campaign_id):
    """Cancel all pending sends for a campaign by deleting its schedule group."""
    scheduler.delete_schedule_group(
        Name=f'campaign-{campaign_id}'
    )

Operational considerations

Moving to production introduces a few scaling and reliability concerns to plan for.

Handling invocation spikes at delivery time

When a mass campaign schedules millions of messages for the same time, this creates cascading pressure across two limits:

  • Amazon EventBridge Scheduler invocations throttle limit: The default is 1,000 TPS per AWS Region, and it is adjustable to tens of thousands of TPS through AWS Service Quotas. Amazon EventBridge Scheduler queues invocations internally and retries with exponential backoff when the downstream target throttles.
  • Amazon SES sending quotas: Your SES account has a per-second sending rate. If the effective invocation rate exceeds this, messages fail with throttling errors. Align Amazon SES sending quotas with your campaign volume. Check your current SES quota in the Service Quotas console and request an increase before launching large campaigns. See Amazon SES best practices for deliverability at scale.

To handle an invocation spike, we recommend using the FlexibleTimeWindow feature of Amazon EventBridge Scheduler. Setting MaximumWindowInMinutes lets Amazon EventBridge Scheduler spread invocations across a time window rather than firing them all at the exact second. Size the window based on your campaign: divide the total schedules by your effective TPS to determine the minimum spread needed. For example, 500,000 schedules at 5,000 TPS need at least a 2-minute window.

Cost model

You pay for Amazon EventBridge Scheduler on a per-invocation basis.

Cleanup

To avoid ongoing charges, delete the resources created during this walkthrough:

  1. Delete any runtime-created schedule groups.
    aws scheduler delete-schedule-group --name campaign-<campaign-id>

  2. Delete the Step Functions state machine.
    aws stepfunctions delete-state-machine \
        --state-machine-arn arn:aws:states:us-east-1:<account-id>:stateMachine:CampaignFanOut

Note: If you have active schedules still waiting to fire, deleting the schedule group will cancel all pending sends.

IAM role for Amazon EventBridge Scheduler and Step Functions

The Step Functions state machine needs an execution role with permissions to create schedules, send email, and pass the role to the Amazon EventBridge Scheduler service. Amazon EventBridge Scheduler needs permissions to call SES. The following policy shows the combined permissions for both scenarios:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "AllowPassRoleToScheduler",
      "Effect": "Allow",
      "Action": "iam:PassRole",
      "Resource": "arn:aws:iam::<ACCOUNT_ID>:role/CampaignFanOutRole",
      "Condition": {
        "StringEquals": {
          "iam:PassedToService": "scheduler.amazonaws.com"
        }
      }
    },
    {
      "Sid": "AllowSESSend",
      "Effect": "Allow",
      "Action": [
        "ses:SendEmail",
        "ses:SendTemplatedEmail"
      ],
      "Resource": "arn:aws:ses:<REGION>:<ACCOUNT_ID>:identity/[email protected]"
    },
    {
      "Sid": "DistributedMapExecution",
      "Effect": "Allow",
      "Action": [
        "states:StartExecution",
        "states:DescribeExecution",
        "states:StopExecution"
      ],
      "Resource": [
        "arn:aws:states:<REGION>:<ACCOUNT_ID>:stateMachine:CampaignFanOut",
        "arn:aws:states:<REGION>:<ACCOUNT_ID>:execution:CampaignFanOut:*"
      ]
    },
    {
      "Sid": "ReadRecipientsBucket",
      "Effect": "Allow",
      "Action": [
        "s3:GetObject",
        "s3:ListBucket"
      ],
      "Resource": [
        "arn:aws:s3:::campaign-recipients-<ACCOUNT_ID>",
        "arn:aws:s3:::campaign-recipients-<ACCOUNT_ID>/*"
      ]
    },
    {
      "Sid": "CreateSchedules",
      "Effect": "Allow",
      "Action": "scheduler:CreateSchedule",
      "Resource": "arn:aws:scheduler:<REGION>:<ACCOUNT_ID>:schedule/campaign-*"
    },
    {
      "Sid": "CreateScheduleGroups",
      "Effect": "Allow",
      "Action": "scheduler:CreateScheduleGroup",
      "Resource": "arn:aws:scheduler:<REGION>:<ACCOUNT_ID>:schedule-group/campaign-*"
    },
    {
      "Sid": "PassRoleToScheduler",
      "Effect": "Allow",
      "Action": "iam:PassRole",
      "Resource": "arn:aws:iam::<ACCOUNT_ID>:role/SchedulerCampaignRole",
      "Condition": {
        "StringEquals": {
          "iam:PassedToService": "scheduler.amazonaws.com"
        }
      }
    }
  ]
}

This policy scopes the scheduler:CreateSchedule and scheduler:CreateScheduleGroup actions to resources prefixed with campaign-*, following least-privilege principles.

A condition restricts the iam:PassRole permission so that it can only pass the role to the Amazon EventBridge Scheduler service.

Conclusion

In this post, we walked through how to use Amazon EventBridge Scheduler to personalize email campaign delivery for each recipient. An email campaign system has two core problems: deciding what to send and deciding when to send it. Most teams over-engineer the “when” with polling infrastructure, batch jobs, and queue chains. Amazon EventBridge Scheduler collapses that into a single CreateSchedule API call per recipient.

To get started, explore Amazon EventBridge Scheduler on the AWS Management Console. Browse Serverless Land patterns for more than 20 Amazon EventBridge Scheduler patterns and other use cases beyond email campaigns.

Suggested tags: Amazon EventBridge, architecture, events, modernization, serverless.

Integrate Amazon Redshift and IAM Identity Center with enhanced VPC routing

Post Syndicated from Maneesh Sharma original https://aws.amazon.com/blogs/big-data/integrate-amazon-redshift-and-iam-identity-center-with-enhanced-vpc-routing/

You can now use AWS IAM Identity Center authentication with enhanced VPC routing on Amazon Redshift clusters and Amazon Redshift Serverless workgroups. Your users get single sign-on with their existing corporate credentials, and the authentication traffic originates from within your virtual private cloud (VPC) through a VPC endpoint, staying on the AWS private network.

We covered the IAM Identity Center integration end to end in a previous post, Integrate Identity Provider (IdP) with Amazon Redshift Query Editor V2 and SQL Client using AWS IAM Identity Center for seamless Single Sign-On. That post shows how users sign in through Query Editor V2 and third-party SQL clients, and how their identity is propagated to the AWS analytics services.

Many organizations also require that this traffic doesn’t traverse the public internet. Enhanced VPC routing sends everything between your cluster and other AWS services through your VPC, where you can govern it with security groups, network ACLs, and endpoint policies, and observe it in VPC Flow Logs. For teams with data residency, regulatory, or network isolation requirements, it’s often mandatory.

In this post, we show how the new IAM Identity Center VPC endpoints provide a private network path for authentication traffic when enhanced VPC routing is enabled. We walk through the endpoint setup and validate the flow from Query Editor V2 and a SQL client. To use this feature, your Amazon Redshift cluster must be running patch 204 or later, and you must create the VPC endpoints described in the following steps.

Solution overview

When a user signs in with IAM Identity Center from Query Editor V2 or a SQL client, Amazon Redshift doesn’t simply accept the token the client presents. It validates the token with IAM Identity Center and resolves the caller’s identity before the session is established. These calls originate from Amazon Redshift, not from your client, and enhanced VPC routing changes the network path they take.

Authentication flow with enhanced VPC routing

With enhanced VPC routing enabled, the calls Amazon Redshift makes to IAM Identity Center traverse your VPC and follow your networking configuration. The flow is as follows:

  1. The user signs in through Query Editor V2 or a SQL client and authenticates against your identity provider through IAM Identity Center.
  2. IAM Identity Center issues an access token, which the client presents to Amazon Redshift on the database connection.
  3. Amazon Redshift validates the access token against the IAM Identity Center OpenID Connect (OIDC) endpoint, confirming the token’s scopes and the user’s entitlement to the Amazon Redshift application. It doesn’t trust the token the client presented without verification.
  4. Amazon Redshift calls the same OIDC endpoint again to exchange that token for one scoped to Amazon Redshift.
  5. Amazon Redshift calls the IAM Identity Center identity store to resolve the user and their group membership.
  6. Amazon Redshift maps the resolved identity to a database identity, applies role-based access control, and establishes the session.

The following diagram illustrates this authentication flow, showing how each call from Amazon Redshift to IAM Identity Center traverses the VPC through interface endpoints.

Authentication flow showing Amazon Redshift reaching the IAM Identity Center OIDC and identity store endpoints through VPC endpoints

Figure 1: IAM Identity Center authentication flow with enhanced VPC routing enabled

As shown in the diagram, steps 3–5 represent calls that Amazon Redshift makes through your VPC to the IAM Identity Center OIDC and identity store endpoints.

Because a cluster with no public IP address doesn’t use an internet gateway route, Amazon Redshift has no path to IAM Identity Center by default. You provide one with interface VPC endpoints for the two services it needs, the IAM Identity Center OIDC endpoint and the identity store endpoint, which keep the traffic on the AWS network over AWS PrivateLink.

This solution covers the following steps:

  1. Enable enhanced VPC routing.
  2. Verify the DNS attributes on your VPC.
  3. Create the interface VPC endpoints required for IAM Identity Center authentication.
  4. Create interface VPC endpoints for AWS Glue and AWS Lake Formation (optional, if you query a data lake or lakehouse).
  5. Create an Amazon Simple Storage Service (Amazon S3) gateway endpoint.
  6. Validate that the endpoints are available and using private DNS.
  7. Test single sign-on with Amazon Redshift Query Editor V2.
  8. Test single sign-on with a SQL client using the Amazon Redshift JDBC driver.
  9. Verify the calls on AWS CloudTrail.

Prerequisites

You should have the following prerequisites:

  • An AWS account with an Amazon Redshift provisioned cluster. Amazon Redshift Serverless also supports enhanced VPC routing, and the same endpoints apply, but you substitute the equivalent workgroup commands and settings.
  • A working IAM Identity Center integration with Amazon Redshift, as described in Integrate Identity Provider (IdP) with Amazon Redshift Query Editor V2 and SQL Client using AWS IAM Identity Center for seamless Single Sign-On.
  • A cluster running patch 204 or later, which is the minimum maintenance version that supports IAM Identity Center authentication with enhanced VPC routing.
  • Permissions to create VPC endpoints in the VPC where the cluster runs, specifically ec2:CreateVpcEndpoint and ec2:DescribeVpcEndpoints.
  • Optionally, an Amazon Elastic Compute Cloud (Amazon EC2) instance inside the same VPC with SQL Workbench/J and the Amazon Redshift JDBC driver, version 2.1.0.30 or later with its dependent libraries, to test the SQL client flow.

Walkthrough

The examples in this post use the Canada (Central) AWS Region (ca-central-1). Replace all placeholder values with your own.

Step 1: Enable enhanced VPC routing and turn off public access

To control network traffic with Amazon Redshift enhanced VPC routing, you enable enhanced VPC routing in Amazon Redshift. The cluster or workgroup must also not be publicly accessible, so that traffic to IAM Identity Center and other services goes through your VPC endpoints rather than an internet gateway. Follow the instructions in Enable enhanced VPC routing to enable it for a new provisioned cluster or serverless workgroup. For an existing cluster or workgroup, follow these steps:

  1. Sign in to the AWS Management Console and open the Amazon Redshift console at https://console.aws.amazon.com/redshiftv2/.
  2. Open the provisioned cluster or serverless workgroup you want to modify:
    1. For an existing provisioned cluster – choose the Properties tab.
    2. For an existing serverless workgroup – choose the Data access tab.
  3. In the Network and security section, choose Edit.
    1. Select Turn on enhanced VPC routing to route network traffic through the VPC.
    2. If Turn on Publicly accessible is enabled, clear it so the cluster or workgroup is not publicly accessible.
  4. Choose Save changes.

The following screenshot shows the Network and security section with enhanced VPC routing enabled and public accessibility turned off.

Amazon Redshift Network and security section with enhanced VPC routing turned on and public access turned off

Figure 2: Enable enhanced VPC routing in Amazon Redshift

Note: Amazon Redshift restarts the cluster automatically when you change enhanced VPC routing. Make this change during a maintenance window.

Step 2: Verify the DNS attributes on your VPC

Private DNS is what redirects the public AWS service hostnames to your interface endpoints, and it depends on two VPC attributes. Follow these steps:

  1. Navigate to Amazon Redshift and choose the Properties tab for Amazon Redshift provisioned, or the Data access tab for Amazon Redshift Serverless.
  2. Under Network and security setting, choose the associated VPC.
  3. Your VPC details open in a new browser tab.
  4. Review the Details section, where the attributes appear as DNS hostnames and DNS resolution. Make sure that both properties are set to Enabled. The following screenshot shows the VPC Details page with both DNS attributes set to Enabled.
VPC Details page showing DNS hostnames and DNS resolution both set to Enabled

Figure 3: DNS hostnames and DNS resolution enabled on the VPC Details page

  1. If either of the properties is Disabled, choose Actions, choose Edit VPC settings, select Enable on the attribute you need, and choose Save. The following screenshot shows the Edit VPC settings page where you enable these DNS attributes.
Edit VPC settings page with the DNS hostnames and DNS resolution attributes being enabled

Figure 4: Enable DNS hostnames and DNS resolution

Step 3: Create the interface VPC endpoints for IAM Identity Center authentication

Create the two interface endpoints that the authentication flow needs. Each corresponds to one of the two IAM Identity Center calls in the authentication flow described earlier:

Service endpoint Used for
com.amazonaws.<region>.sso-oauth Validating and exchanging the IAM Identity Center access token
com.amazonaws.<region>.identitystore Resolving the user and their group membership

To create an interface endpoint for an AWS service

  1. Open the Amazon Virtual Private Cloud (Amazon VPC) console at https://console.aws.amazon.com/vpc/.
  2. In the navigation pane, choose Endpoints.
  3. Choose Create endpoint.
  4. For Type, choose AWS services.
  5. IAM Identity Center is a Regional service, so these endpoints must reach the AWS Region where your IAM Identity Center instance is available. If you’re using IAM Identity Center multi-Region replication (your instance is replicated to the Region where your Amazon Redshift cluster runs), leave Enable Cross Region endpoint unchecked.
  6. For Service name, search for sso-oauth and select the service for your Region (com.amazonaws.<region>.sso-oauth). The following screenshot shows the top section of the Create endpoint page with the sso-oauth service selected.
Create endpoint page with the sso-oauth service selected for the Region

Figure 5: Create an interface VPC endpoint, part 1

  1. For VPC, select the VPC from which you will access the AWS service. In our use case, we choose the Amazon Redshift VPC.
  2. To enable private DNS support, select Additional settings and choose Enable private DNS name.
  3. For Subnets, select the subnets in which to create endpoint network interfaces. You can select one subnet per Availability Zone. You can’t select multiple subnets from the same Availability Zone. For more information, see Subnets and Availability Zones.
  4. For IP address type, choose IPv4. This assigns IPv4 addresses to the endpoint network interfaces. This option is supported only if all selected subnets have IPv4 address ranges and the service accepts IPv4 requests.
  5. For Security groups, select the security groups to associate with the endpoint network interfaces. For this post, we have selected default security group associated with Redshift. The following screenshot shows the VPC, subnet, and security group selections for the endpoint.
Create endpoint page showing the VPC, subnet, and security group selections

Figure 6: Create an interface VPC endpoint, part 2

  1. For Policy, to allow all operations by all principals on all resources over the interface endpoint, select Full access. To restrict access, select Custom and enter a policy. This option is available only if the service supports VPC endpoint policies. For more information, see Endpoint policies.
  2. (Optional) To add a tag, choose Add new tag and enter the tag key and the tag value.
  3. Choose Create endpoint. The following screenshot shows the policy and tag settings before you create the endpoint.
Create endpoint page showing the policy set to Full access and the tag settings

Figure 7: Create an interface VPC endpoint, part 3

Repeat steps 1–14 for the identity store endpoint, search for identitystore and select the service for your Region (com.amazonaws.<region>.identitystore).

Two settings in the preceding steps are important:

  • Enable private DNS name is required. Amazon Redshift resolves the public service hostname, for example, oidc.<region>.amazonaws.com. Private DNS is what points that hostname at your interface endpoint, so the traffic stays inside your VPC.
  • Use the cluster’s security group, because the cluster is the caller. The endpoint’s security group must allow inbound HTTPS on port 443 from the cluster. Reusing the cluster’s own security group is the simplest approach when it already allows traffic from itself. A dedicated security group needs an explicit port 443 inbound rule from the cluster’s security group.

(Optional) To create an interface endpoint using the command line

Step 4 (optional): Create endpoints for AWS Glue and AWS Lake Formation

Complete this step only if your cluster queries external data through the AWS Glue Data Catalog and AWS Lake Formation. Common examples include Amazon S3 Tables, a capability of Amazon S3, and data lakes registered with Lake Formation. If you only need single sign-on, you can skip to Step 5. Amazon Redshift calls the AWS Glue Data Catalog to enumerate databases and tables, and calls AWS Lake Formation to check permissions and vend temporary credentials for the underlying data. Like the authentication calls, these are made by the cluster, so with enhanced VPC routing enabled they travel through your VPC and need a path of their own.

Repeat steps 1–14 from Step 3 for:

  • com.amazonaws.<region>.glue.
  • com.amazonaws.<region>.lakeformation.

With these endpoints in place, Amazon Redshift routes external catalog operations such as listing external tables through the VPC endpoints rather than the public internet, keeping metadata traffic on the AWS network.

Step 5: Create an Amazon S3 gateway endpoint

With enhanced VPC routing enabled, anything the cluster does against Amazon S3 (COPY, UNLOAD, and Amazon S3 Tables) also travels through your VPC. Create a gateway endpoint and associate it with the route table(s) used by your cluster’s subnets:

  1. Open the Amazon VPC console at https://console.aws.amazon.com/vpc/.
  2. In the navigation pane, choose Endpoints, then choose Create endpoint.
  3. For Type, choose AWS services.
  4. For Service name, search for s3 and select the service for your Region with Type: Gateway (com.amazonaws.<region>.s3). The following screenshot shows the Create endpoint page with the Amazon S3 gateway service selected.
Create endpoint page with the Amazon S3 gateway service selected

Figure 8: Create an Amazon S3 gateway endpoint, part 1

  1. For VPC, choose your Amazon Redshift VPC.
  2. For Route tables, select the route table(s) associated with the subnets your cluster runs in.
  3. Choose Create endpoint. The following screenshot shows the VPC and route table selections for the S3 gateway endpoint.
Create endpoint page showing the VPC and route table selections for the S3 gateway endpoint

Figure 9: Create an Amazon S3 gateway endpoint, part 2

Step 6: Validate the endpoints

Confirm in the Amazon VPC console that every endpoint you created is available, and that private DNS is enabled on the interface endpoints.

  1. Open the Amazon VPC console at https://console.aws.amazon.com/vpc/.
  2. In the navigation pane, choose Endpoints.
  3. In the endpoints list, use the filter bar to filter by VPC ID (choose VPC ID and select your Amazon Redshift VPC). Then locate the endpoints you created for this walkthrough, sso-oauth, identitystore, the Amazon S3 gateway endpoint, and (if you created them) glue and lakeformation.
  4. Confirm each endpoint shows a Status of Available.
  5. Select each interface endpoint (sso-oauth, identitystore, glue, lakeformation) and, on the Details tab, confirm Private DNS names enabled is Yes. The following screenshot shows the completed endpoints list with each endpoint in the Available state.
VPC endpoints list showing the interface and gateway endpoints in the Available state

Figure 10: VPC endpoints created in this walkthrough, in the Available state

Step 7: Test single sign-on with Amazon Redshift Query Editor V2

  1. On the Amazon Redshift console, choose Query editor v2.
  2. Choose your cluster and then choose IAM Identity Center as the connection method.
  3. Sign in with your corporate credentials when prompted.
  4. Expand the cluster in the tree view to list databases, schemas, and tables.

The database list populates within a few seconds. Confirm the login on the server side by querying the connection log. Run this as a user who does not use IAM Identity Center, for example a database user with a password, or through the Amazon Redshift Data API:

SELECT record_time, user_name, auth_method, driver_version, remote_host, event
FROM sys_connection_log
WHERE auth_method LIKE '%Idc%'
AND record_time > dateadd(minute, -15, getdate())
ORDER BY record_time DESC;

A successful sign-in shows user_name as <idc_namespace>:<[email protected]> with event of authenticated, which confirms that the identity was resolved through the endpoints you created. The following screenshot shows the sys_connection_log query results, where each IAM Identity Center sign-in appears with a user_name in the <idc_namespace>:<[email protected]> format.

Query Editor V2 connected through IAM Identity Center, showing the expanded database list

Figure 11: Query Editor V2 connected with IAM Identity Center, showing the database list

Step 8: Test single sign-on with a SQL client

Testing from a SQL client on an EC2 instance inside your VPC is the stronger validation, and we recommend doing both. Query Editor V2 connects through an Amazon Redshift managed proxy, so its connections are recorded with a loopback address. A client running inside your VPC connects to the cluster endpoint directly, which is exactly the path the endpoints you created are there to serve.

Set up SQL Workbench/J

SQL Workbench/J connects through the Amazon Redshift JDBC driver. On an EC2 instance in the same VPC as your cluster, download and install SQL Workbench/J.

  1. Download the latest Amazon Redshift JDBC driver together with its dependent libraries, and extract the archive to a folder on the instance.
  2. Start SQL Workbench/J, and choose File, then Manage Drivers.
  3. Choose the Create a new entry icon, and for Name, enter Amazon Redshift.
  4. For Library, choose the folder icon, and select the driver JAR file along with every JAR file in the dependent libraries folder. Keep only one version of the driver in the list, and remove any previous entries.
  5. Choose File, then Connect window, and choose the Create a new connection profile icon. Enter a name for the profile, such as redshift-idc.
  6. For Driver, choose the Amazon Redshift driver that you created.
  7. For URL, enter your cluster endpoint in the form jdbc:redshift://<cluster endpoint>:5439/<database>, for example jdbc:redshift://my-redshift-cluster.abc123xyz789.ca-central-1.redshift.amazonaws.com:5439/dev.
  8. Leave Username and Password empty. The browser plugin obtains the identity interactively.
  9. Choose Extended Properties, and add the following three properties:
Property Value
plugin_name com.amazon.redshift.plugin.BrowserIdcAuthPlugin
issuer_url https://identitycenter.amazonaws.com/ssoins-<instance-id>
idc_region The Region of your IAM Identity Center instance, such as ca-central-1
  1. Clear Separate connection per tab, so that each editor tab reuses the same physical connection rather than prompting you to sign in again.
  2. Choose Test. Your default browser opens. Sign in with your corporate credentials, and then choose Allow access so that the Amazon Redshift JDBC driver can access your data.
  3. If the connection succeeds, you see a prompt confirming the connection to your Amazon Redshift endpoint, as shown in the following screenshot.
SQL Workbench/J connection profile for Amazon Redshift using the IAM Identity Center browser plugin

Figure 12: SQL Workbench/J connection for Amazon Redshift using the IAM Identity Center browser plugin

In the browser, you will see the following message once the authentication is successful.

Congratulations! You have IAM Identity Center single sign-on working on an Amazon Redshift cluster with enhanced VPC routing enabled.

Step 9: Verify the calls on AWS CloudTrail

You can confirm from AWS CloudTrail that these calls travel through your interface endpoints rather than the internet. Each event includes a vpcEndpointId field naming the endpoint the call traversed, along with a vpcEndpointAccountId field identifying the account that owns it.

The following table maps each interface endpoint to the CloudTrail event you’ll see:

Service endpoint Event source CloudTrail event
com.amazonaws.<region>.sso-oauth sso-oauth.amazonaws.com CreateTokenWithIAM
com.amazonaws.<region>.identitystore identitystore.amazonaws.com DescribeUser, ListGroupMembershipsForMember, BatchDescribeGroup

The following screenshot shows the snippet from the CloudTrail logs showing the CreateTokenWithIAM event that Amazon Redshift generates when it exchanges the IAM Identity Center access token. The eventSource is sso-oauth.amazonaws.com, and the vpcEndpointId field confirms the call traversed your interface VPC endpoint rather than the public internet. The invokedBy field shows the call originated from Amazon Redshift (redshift.amazonaws.com), not from the client.

CloudTrail CreateTokenWithIAM event with event source sso-oauth.amazonaws.com and a vpcEndpointId field

Figure 13: CloudTrail CreateTokenWithIAM event traversing the sso-oauth interface endpoint

Similarly, the following screenshot shows a DescribeUser event (event source identitystore.amazonaws.com) generated when Amazon Redshift resolves the authenticated user against the identity store. As with the previous event, the invokedBy field shows the call originated from Amazon Redshift, and the vpcEndpointId field confirms it traversed the identitystore interface endpoint.

CloudTrail DescribeUser event with event source identitystore.amazonaws.com and a vpcEndpointId field

Figure 14: CloudTrail DescribeUser event traversing the identitystore interface endpoint

Note: where the events appear depends on how your IAM Identity Center instance is deployed:

  • CreateTokenWithIAM (event source sso-oauth.amazonaws.com) is recorded in the same account as your Amazon Redshift cluster.
  • Identity Store API calls (DescribeUser, ListGroupMembershipsForMember, BatchDescribeGroup) are recorded in the account that owns your IAM Identity Center instance. The event source is identitystore.amazonaws.com. If you use a centralized instance in a delegated administrator or management account, these events appear in that account and not in the account running your cluster. Searching the cluster’s own account returns nothing, even when authentication is working normally. To confirm which account to look in, run aws sso-admin list-instances and check OwnerAccountId.

Clean up

To avoid incurring future charges, delete the resources you created for this walkthrough. These endpoints provide the network path for single sign-on while enhanced VPC routing is enabled, so remove them only if you no longer need the integration.

  • On the Amazon VPC console, choose Endpoints.
  • Select the sso-oauth and identitystore interface endpoints you created, and choose Actions, then Delete VPC endpoints.
  • Select the glue and lakeformation interface endpoints, if you created them, and delete them.
  • Select the Amazon S3 gateway endpoint and delete it. This also removes its route table entries.
  • Terminate the EC2 instance you used to test the SQL client connection, if you created one for this walkthrough.
  • If you no longer need the integration, remove the IAM Identity Center application assignment for Amazon Redshift and delete the associated IAM role and policy.

Conclusion

In this post, we showed you how to enable AWS IAM Identity Center authentication for Amazon Redshift on clusters with enhanced VPC routing enabled. Your users get single sign-on with their corporate credentials, and the authentication traffic stays private to your VPC. The key concept is that Amazon Redshift, not your client, validates the access token. Because enhanced VPC routing is enabled, Amazon Redshift routes that validation call through your VPC. On a cluster running patch 204 or later, interface endpoints for sso-oauth and identitystore give Amazon Redshift a private path over AWS PrivateLink. Adding endpoints for AWS Glue, AWS Lake Formation, and Amazon S3 extends the same benefit to data lake and lakehouse queries.

Try this setup in your own environment and let us know what you think in the comments. For more information, see the following resources:


About the authors

Maneesh Sharma

Maneesh Sharma

Maneesh is a Senior Analytics Specialist Solutions Architect at AWS with more than 15 years of experience designing and implementing large-scale data warehouse and analytics solutions. He works with FSI and Enterprise customers to implement modern analytics architectures using Amazon Redshift, Amazon SageMaker Unified Studio, Amazon S3 Tables, AWS Glue, AWS Lake Formation, and AWS IAM Identity Center.

Laura Reith

Laura Reith

Laura is an Identity Solutions Architect at AWS, where she thrives on helping customers overcome security and identity challenges. In her free time, she enjoys wreck diving and traveling around the world.

Suchintya Dandapat

Suchintya Dandapat

Suchintya is a Principal Product Manager for AWS where he partners with enterprise customers to solve their toughest identity challenges, enabling secure operations at global scale.

Jonathan Glaser

Jonathan is a Software Development Engineer on the Amazon Redshift Connectivity team, where he works on authentication and the Redshift client drivers. He focuses on secure authentication for Redshift, including its integration with IAM Identity Center in Enhanced VPC Routing environments. Jonathan holds master’s degrees in biotechnology and computer science, and in his spare time enjoys reading fiction and exploring NYC’s food scene.

Nishtha Mehrotra

Nishtha is a Senior Software Development Engineer on the Redshift Connectivity team at AWS. With over 10 years of software engineering experience, she specializes in database driver development, performance optimization, and identity integration. Nishtha works on Amazon Redshift’s ODBC, JDBC, and Python drivers, ensuring reliable and performant connectivity for customers at scale. She is passionate about improving developer experience and building secure, high-performance data infrastructure that powers analytics workloads across AWS.

Automate IAM Identity Center governance with continuous discovery and reporting

Post Syndicated from Jonathan Nguyen original https://aws.amazon.com/blogs/security/automate-iam-identity-center-governance-with-continuous-discovery-and-reporting/

AWS IAM Identity Center integrates with external identity provider (IdP) to provide customers with a centralized authentication and authorization solution for AWS resources across AWS Organizations. AWS continues to invest into IAM Identity Center with a growing number of AWS services that natively integrate with IAM Identity Center. As your AWS organization scales, maintaining visibility into who has access to which applications and enforcing governance policies across accounts and Regions becomes increasingly complex. Identity Center helps address this by centralizing authentication and authorization for AWS resources across your organization, integrating with your external identity provider and a growing number of AWS services. However, as adoption scales, tracking access assignments and enforcing governance policies consistently becomes its own challenge.

This blog post focuses on planning your integration between an identity provider and IAM Identity Center for managed applications in your organization. We also walk through deploying and using an automated Identity Center discovery and reporting sample solution to help answer the governance and security questions:

  1. Which users or groups have access to which AWS applications?
  2. Who last accessed a specific AWS application and when?
  3. Which users and groups are assigned to which IAM Identity Center applications across organization and AWS Regions?
  4. How can you quickly generate reports to assist with compliance audits or security reviews?

The sample solution will identify associated AWS applications and the corresponding user and group assignments for the IAM Identity Center instances within your organization. The output is stored in a queryable format and generates CSV files for downstream analysis or reporting.

Plan identity governance for Identity Center application assignments

There are four key areas to start on when planning how to manage delegation and provisioning access across IAM Identity Center managed AWS applications. Bring together key stakeholders across security, governance, application, and business teams to make sure the implementation and integration will fit into the overall identity governance strategy.

  1. Who can provision managed AWS applications: You can implement the IAM restrictions for creation of new AWS resources within AWS accounts in your organization. For example, if you restrict provisioning into a production AWS account to only infrastructure as code (IaC) IAM roles, you would continue implementing restrictions using AWS identity policies, service control policies (SCP), resource control policies (RCP), or IaC policy evaluation tools like Open Policy Agent (OPA) or Checkov.
  2. Who manages user and group assignments: The managed application administrator handles authorization to managed applications within an AWS account. It’s recommended to clearly define roles and responsibilities across the workflow. You would have an IaC pipeline manage the integrated AWS resource provisioning with IAM Identity Center, then another workflow to allow requests to manage user and group membership for the managed application.
  3. How authentication flows from the IdP to AWS resources: Users will authenticate into Identity Center, then be authorized to access AWS managed applications. From there, they will be authorized to access the associated AWS service and resources tied to the managed application. Depending on the AWS service, the associated downstream resources might have their own IAM principals that the users can access.
  4. Mapping IdP identities to AWS resource access: There needs to be a link for workforce users and groups in your IdP, to Identity Center managed applications, and to downstream resources and permissions. Identifying the relationship will help you understand access within your AWS environment. Trusted identity propagation (TIP) is an additional feature of Identity Center that provides an end to end trail of the identity to the downstream service.

Create and manage an Identity Center application assignment lifeycle

As a security best practice, you should enable delegated administration when managing Identity Center within an AWS organization instances.

After you have IAM Identity Center set up within an organization instance, your member AWS accounts can start creating associated AWS resources. Within each member AWS account, the IAM principals that provision AWS resources will need two types of service-specific IAM permissions:

  • The first type of IAM permissions will be specific to the AWS service you want to provision. For example, to create an Amazon SageMaker AI domain, you would need the same IAM permissions to create the SageMaker AI domain and the downstream AWS resources SageMaker AI might use.
  • The second type of IAM permissions is specific to IAM Identity Center. The IAM principal used to create the resource, in this example SageMaker AI, will also need permissions to manage applications within the Identity Center instance.
{
	"Version": "2012-10-17",
	"Statement":
	[
		{
            "Effect": "Allow",
            "Action": [
                "sso:CreateManagedApplicationInstance",
                "sso:GetManagedApplicationInstance",
                "sso:DeleteManagedApplicationInstance",
                "sso:DescribeRegisteredRegions"
            ],
            "Resource": "*"
        },
        {
            "Effect": "Allow",
            "Action": [
                "sso:CreateApplication",
                "sso:DescribeApplication",
                "sso:DeleteApplication",
                "sso:PutApplicationGrant",
                "sso:PutApplicationAuthenticationMethod",
                "sso:PutApplicationAccessScope"
            ],
            "Resource": 
            [
                "arn:aws:sso::<INSERT-ACCOUNT-ID>:application/ssoins-<INSERT-INSTANCE-ID>/apl-*"
            ]
        }
    ]
}

IAM Identity Center application Amazon Resource Names (ARNs) follow a different standard naming convention that isn’t based on the original resource name that was provided during resource creation. For example, when a user creates an Amazon Simple Storage Service (Amazon S3) bucket and sets a specific bucket name, that bucket name is included in the ARN: arn:[partition]:s3:::[bucket-name]. Identity Center application ARNs use unique identifiers (GUIDs) generated at creation time.

Manage access for an Identity Center application

After the IAM Identity Center application is created, you will need to manage access to the Identity Center application and associated AWS resources. To continue with the SageMaker AI domain example, after the domain is created, an authorized IAM principal will need to assign Identity Center users or groups from the Identity Center instance to the domain. For Identity Center, you will need two types of Identity Center IAM permissions.

The first type of IAM permissions is used to list IAM Identity Center users and groups within the Identity Center instance. This is needed to read and select specific IAM users or groups to assign to an Identity Center application.

{
    "Version": "2012-10-17",
    "Statement":
    [
        {
            "Sid": "ListIdentityCenterUsers",
            "Effect": "Allow",
            "Action":
            [
                "identitystore:ListUsers",
                "identitystore:DescribeUser",
                "identitystore:ListGroups",
                "identitystore:DescribeGroup",
                "identitystore:ListGroupMemberships"
            ],
            "Resource": "*"
        }
    ]
}

Although IAM Identity Center users and groups have a GUID, the GUIDs aren’t clearly linked to the resource friendly names. For example, a group name could be Read-Only and the resource GUID could be 1234567890-abcdef12-3456-7890-abcd-ef1234567890 in the identity store. Additionally, the IAM actions to list users or groups require the AllUsers or AllGroups parameter. Because List actions require access to users and groups, a restrictive IAM policy can’t be used to prevent IAM principals from seeing a subset of users or groups within the identity store. The second type of IAM permission is used to create and manage application assignments for the Identity Center application within the Identity Center instance.

{
    "Version": "2012-10-17",
    "Statement":
    [
        {
            "Sid": "ManageApplicationAssignments",
            "Effect": "Allow",
            "Action": 
            [
                "sso:CreateApplicationAssignment",
                "sso:DeleteApplicationAssignment",
                "sso:ListApplicationAssignments",
                "sso:PutApplicationAssignmentConfiguration"
            ],
            "Resource":
            [
                "arn:aws:sso::<INSERT-ACCOUNT-ID>:application/ssoins-<INSERT-INSTANCE-ID>/apl-*"
            ]
        }
    ]
}

Because the IAM Identity Center application ARN is created using a unique application ID during creation, it’s not recommended to implement an IAM policy restricting authorized IAM principals to manage specific Identity Center applications. For example, to limit the application assignments to only a specific set of applications, you would need to:

  1. Create the AWS resource with IAM Identity Center as the authentication mechanism
  2. Query the Identity Center application ARN for the associated AWS resource
  3. Identify the IAM principal that will be used for application assignments
  4. Create or update an IAM policy associated to that IAM principal to allow application assignments for that specific application
  5. Create or update an SCP to restrict application assignment to that specific IAM principal

In lieu of implementing resource restrictions within identity policies, you should limit management of IAM Identity Center application and application assignments to a limited number of authorized IAM principals. In addition, it is recommended to implement detective and reactive capabilities to manage Identity Center application assignments.

Plan your naming conventions and automation strategy

IAM Identity Center provides several APIs to capture information about your AWS organization instances, applications, and assignments. Before implementing automation or guardrails, you should develop a methodical approach and understand what outcome you’re working backwards from. Start by defining naming conventions and deciding what parts of the workflow you want to centralize.

  1. Determine a naming convention for groups within your IdP: For example: AWS_<ACCT#>_<AWS_Service>_<LOB>_<ENV>_<AppName>. The IdP group name would look like: AWS_123412341234_SageMaker_Data_PROD_GTLabel.
  2. Define the naming convention for AWS resources for your Identity Center integrated applications: For example: <AWS_Service>_<LOB>_<AppName>. The AWS resource name would look like: SageMaker_Data_GTLabel.
  3. Define the naming convention for Identity Center application names: For example: <AWS_Service>_<LOB>_<ENV>_<AppName>. The Identity Center application name would look like: SageMaker_Data_PROD_GTLabel.
  4. Decide on the restrictions that you want to implement within your AWS environment. Depending on your enterprise’s security standard, you can implement specific restrictions based on mapping of a similar combination of ENV (environment), AWS service, LOB (line of business), or application name.
  5. Choose the portions of the application workflow that you want to centralize. This could include creating the application, making application assignments, or remediating issues.

As more configurations and permissions are centralized, additional overhead and bottlenecks can be introduced. It’s important to find the right balance for your enterprise. For example, if you centralize application assignments, each application team will need to submit a request to modify assignments that will be reviewed by a centralized team and could result in a delayed response. Conversely, if each application team handles their own assignments, there’s a risk that application assignments won’t align to enterprise security standards.

By understanding your goals and how you want to reach them, you can tailor the sample solution accordingly. Getting alignment on this requires planning and coordination across multiple teams within your organization. When thinking about more customized authorization logic—such as using provisioned AWS resource metadata—you should review how the specific AWS service integrates with IAM Identity Center managed applications. For example, if you want to find the Identity Center application ARN for a specific AWS resource, such as a SageMaker AI domain, use the following approach. A reverse lookup is necessary because AWS services create Identity Center applications with GUID-based ARNs that aren’t easily discoverable.

#!/bin/bash

DOMAIN_ID="d-xxxxxxxxxxxx"

REGION="xx-xxxx-x"

# Step 1: Get SageMaker domain details
echo "=== SageMaker Domain Details ==="
DOMAIN_INFO=$(aws sagemaker describe-domain \
--region $REGION \
--domain-id $DOMAIN_ID)

# Step 2: Extract Identity Center application ARN
SSO_APP_ARN=$(echo $DOMAIN_INFO | jq -r '.SingleSignOnApplicationArn')
echo "Identity Center App ARN: $SSO_APP_ARN"

IAM Identity Center automation sample solutions

The sample-iam-idc-application-discovery-reporting solution hosted on GitHub consists of two separate AWS CDK stacks:

  1. IAM Identity Center governance reporting stack (/identity-center-reporting directory) – Provides automated discovery and report generation (using CSV files)
  2. IAM Identity Center remediation stack (/identity-center-remediation directory) – Provides real-time enforcement and notifications

The recommendation is to deploy the reporting stack first to establish baseline visibility, then deploy the remediation stack for enforcement.

The following diagram depicts that IAM Identity Center governance architecture.

The reporting sample deploys the following resources:

  1. Amazon EventBridge – Rule invokes the discovery workflow daily at 2:00 AM UTC (configurable)
  2. AWS Step Functions – Orchestrates the multi-stage discovery workflow across instances, applications,and assignments
  3. AWS Lambda – Takes the following actions:
    1. Discovers IAM Identity Center instances across the organization and member accounts
    2. Application discovery that enumerates the applications configured in each Identity Center instance
    3. Assignment discovery maps users and groups to applications, resolving friendly names from the Identity Store
  4. Amazon DynamoDB – Stores the discovered instances, applications, and assignments, encrypted with an AWS Key Management Service (AWS KMS) customer-managed key
  5. Amazon API Gateway – Provides an IAM-authenticated REST API for a Lambda function to generate and export reports as CSV files
  6. Amazon S3 – Stores the encrypted CSV file exports, with lifecycle policies and time-limited Amazon S3 presigned download URLs

Deploy the IAM Identity Center reporting sample

The following procedure deploys the automated discovery and reporting infrastructure using AWS Cloud Development Kit (AWS CDK). Make sure you have the following prerequisites in place, then continue with the steps to set up the solution.

Prerequisites

You need to have the following to test the solution in this post.

  1. An AWS organization with an IAM Identity Center organization instance with delegated administrator access configured
  2. IAM Identity Center configured with at least one instance
  3. AWS Command Line Interface (AWS CLI) configured with appropriate credentials
  4. Python 3.12 & Node.js 18 or later installed for CDK deployment

To deploy the IAM Identity Center reporting solution, run the following commands:

  1. Clone the solution repository:
    git clone https://github.com/aws-samples/sample-iam-idc-application-discovery-reporting
    cd identity-center-reporting

  2. Install dependencies:
    python3.12 -m venv .venv && source .venv/bin/activate
    pip install -r requirements.txt

  3. Bootstrap the CDK (if not already done):
    cdk bootstrap aws://<INSERT-ACCOUNT-ID>/<INSERT-REGION>

  4. Deploy the sample solution:
    export IDC_EXTERNAL_ID="$(uuidgen)" # alternatively you can set this value — member-account roles need the same value
    
    cdk deploy --parameters AllowedIpRange=10.0.0.0/8 --parameters CrossAccountExternalId="$IDC_EXTERNAL_ID"

    Note: AllowedIPRange is optional but recommended as a security best practice. The parameter will add a network restriction to download the Amazon S3 presigned URL export.

  5. Optional: For AWS account-level Identity Center instance discovery, a cross-account IAM role is required.
    python scripts/deploy-cross-account-roles.py --external-id "$IDC_EXTERNAL_ID"

Figure 2: Successful AWS CDK deployment of the reporting stack

Figure 2: Successful AWS CDK deployment of the reporting stack

After the stack is successfully deployed, obtain the CDK output values for the API Gateway URL and S3 bucket name. If using a command line to deploy, these values will be displayed after the stack successfully deploys. It can also be found in the AWS Management Console as AWS CloudFormation stack output. The output will be used for generating reports in the following sections.

Note that this stack is for the reporting stack only. Reactive monitoring and deployment are described in the next section.

After the reporting stack is successfully deployed, the automation will run on a daily schedule. The first discovery run executes immediately after deployment. You can monitor discovery execution history and detailed logs through the the AWS Step Functions console. Review the detailed Lambda function logs in Amazon CloudWatch Logs. Query discovered instances, applications, and assignments through the DynamoDB console for one-time analysis.

Generate reports for Identity Center application assignments

To generate on-demand reports as CSV files from the REST API:

  1. Set env variables for Sigv4 authentication
      export AWS_REGION="<REPLACE-REGION>"
      export API_ID="<REPLACE-API-ID>"
      eval "$(aws configure export-credentials --profile "<YOUR-PROFILE>" --format env)"

  2. Export applications
      curl -sS --fail-with-body \
        --aws-sigv4 "aws:amz:${AWS_REGION}:execute-api" \
        --user "${AWS_ACCESS_KEY_ID}:${AWS_SECRET_ACCESS_KEY}" \
        --header "x-amz-security-token: ${AWS_SESSION_TOKEN}" \
        "https://${API_ID}.execute-api.${AWS_REGION}.amazonaws.com/prod/export/applications" \
        -o applications.json

  3. Export assignments with user and group names
      curl -sS --fail-with-body \
        --aws-sigv4 "aws:amz:${AWS_REGION}:execute-api" \
        --user "${AWS_ACCESS_KEY_ID}:${AWS_SECRET_ACCESS_KEY}" \
        --header "x-amz-security-token: ${AWS_SESSION_TOKEN}" \
        "https://${API_ID}.execute-api.${AWS_REGION}.amazonaws.com/prod/export/assignments" \
        -o assignments.json

  4. The API returns a JSON response with a presigned Amazon S3 URL that’s valid for 15 minutes:
    {
        "message": "CSV export generated successfully",
        "download_url": "https://<bucket>.s3.amazonaws.com/exports/applications/2026/06/22/applications_export_20260722_184538.csv?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Expires=900&...",
        "filename": "applications_export_20260722_184538.csv",
        "s3_key": "exports/applications/2026/07/22/applications_export_20260722_184538.csv",
        "file_size_bytes": 6514,
        "export_type": "applications",
        "generated_at": "2026-07-22T18:45:38Z",
        "expires_at": "2026-07-22T19:00:38Z",
        "request_id": "a1b2c3d4-...."
    }

    {
        "message": "CSV export generated successfully",
        "download_url": "https://<bucket>.s3.amazonaws.com/exports/applications/2026/07/22/applications_export_20260722_184538.csv?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Expires=900&...",
        "filename": "applications_export_20260722_184538.csv",
        "s3_key": "exports/applications/2026/07/22/applications_export_20260722_184538.csv",
        "file_size_bytes": 6514,
        "export_type": "applications",
        "generated_at": "2026-07-22T18:45:38Z",
        "expires_at": "2026-07-22T19:00:38Z",
        "request_id": "a1b2c3d4-...."
    }

The generated CSV files include enriched data with friendly names:

Instance ARN Account ID Application name Principal type Principal name Status
arn:aws:sso:::instance/… 123456789012 SageMaker_PROD GROUP Engineering-Team-Dev ACTIVE
arn:aws:sso:::instance/… 123456789012 OpenSearch_PROD USER [email protected] ACTIVE

You can use the generated CSV files to help identify anomalies or non-compliant assignments, such as:

  1. Each PROD application should only have GROUP assignments. OpenSearch_PROD has a USER principal type and so is non-compliant.
  2. Each PROD application should only allow PROD groups assigned. SageMaker_PROD has a DEV group name (Engineering-Team-Dev) assigned and so is non-compliant.

Based on the testing and analysis of the output from the IAM Identity Center governance reporting sample solution, it’s important to start thinking about what restrictions to put in place for application assignments. It’s also important to conduct this exercise before taking action within the Identity Center remediation sample solution in the next section.

IAM Identity Center remediation

The following diagram shows the IAM Identity Center remediation architecture.

The IAM Identity Center remediation sample solution deploys the following resources:

  1. Amazon EventBridge – Matches IAM Identity Center assignment and profile events from CloudTrail (sso.amazonaws.com) and invokes the monitor function across the following IAM actions:
    1. CreateApplicationAssignment
    2. DeleteApplicationAssignment
    3. PutApplicationAssignmentConfiguration
    4. AssociateProfile
    5. DisassociateProfile
    6. CreateProfile
    7. UpdateProfile
    8. DeleteProfile
  2. Lambda – Resolves the application and group names, validates the assignment against your naming convention, and notifies or remediates based on the configured mode
  3. Amazon Simple Notification Service (Amazon SNS) – Publishes alerts for non-compliant assignments to subscribers (for example, email)
  4. Amazon Simple Queue Service (Amazon SQS) – Captures events the Lambda function fails to process for later inspection
  5. AWS KMS – Customer-managed key to encrypt the Lambda environment variables, CloudWatch logs, SNS topic, and dead-letter queue
  6. Amazon CloudWatch – Log group stores the function’s structured, encrypted logs as an audit trail

Flexible naming policies support regex-based pattern matching for specific organizational requirements. The automation actions are logged to CloudWatch with structured JSON for additional analysis and reporting.

The following procedure deploys the remediation infrastructure using AWS Cloud Development Kit (AWS CDK). Make sure you have the following prerequisites in place, then continue with the steps to set up the solution.

Prerequisites

You need the following to run the remediation solution:

  1. An AWS organization with an IAM Identity Center organization instance with delegated administrator access configured
  2. IAM Identity Center configured with at least one instance and an IdP
  3. Access to create groups within the integrated IdP
  4. AWS Command Line Interface (AWS CLI) configured with appropriate credentials
  5. Python 3.12 & Node.js 18 or later installed for CDK deployment

Provide your IAM instance ARN and the account ID where IAM Identity Center is administered:

git clone https://github.com/aws-samples/sample-iam-idc-application-discovery-reporting # only needed if you did not clone in the previous reporting section
cd identity-center-remediation
cdk deploy --context enableAutoDeletion=false --parameters IdentityCenterInstanceArn=arn:aws:sso:::instance/ssoins-<INSERT-ORG-INSTANCE-ID> --parameters ManagementAccountId=<INSERT-MANAGEMENT-ACCOUNT>

Note: If you don’t pass a parameter for GroupNameRegex, the default action of the sample solution is to verify the group name appears as a whole word in the application name: Case-insensitive, splitting on -, _, and spaces, so ReadOnly matches sagemaker_readonly but read does not. If different validation is needed, the sample can be deployed with the regex value for GroupNameRegex.

After the solution is deployed, we will walk through testing both a compliant and non-compliant application assignment.

Gather Identity Center and application information

For this blog, we have already created two groups within the IdP that is integrated into an IAM Identity Center instance. We also already created two applications within Identity Center instance to use. Next, we’ll need to gather information specific to the environment to run through each example.

  1. Obtain the IAM Identity Center instance ARN and set the value.
    INSTANCE_ARN=$(aws sso-admin list-instances --region <REPLACE-REGION> --query "Instances[0].InstanceArn" --output text)
    
    echo "$INSTANCE_ARN"

  2. Obtain the IAM Identity Center identity store ID

    IDENTITY_STORE_ID=$(aws sso-admin list-instances --region <REPLACE-REGION> --query "Instances[0].IdentityStoreId" --output text)
    
    echo "$IDENTITY_STORE_ID"

  3. Get existing groups in IAM Identity Center
    aws identitystore list-groups --identity-store-id $IDENTITY_STORE_ID --query "Groups[].{Name:DisplayName,Id:GroupId}" --output table

  4. Get existing enabled applications in IAM Identity Center
    aws sso-admin list-applications --instance-arn $INSTANCE_ARN --query "Applications[?Status=='ENABLED'].{Name:Name,ARN:ApplicationArn}" --output table

After you have the output for IAM Identity Center groups and applications, select two groups and one application that you want to test with. You will need to set additional variables for each group GUID and application ARN. In this example, I select the following two groups (ReadOnly and Developer) for testing and set the environment variables using export:

  1. Group #1 Name: ReadOnly
    export GRP_READONLY=abc12345-1234-1234-1234-abcdef123456
    export GRP_DEVELOPER=abc12345-1234-1234-1234-abcdef123457
    export APP_READONLY="arn:aws:sso::<INSERT-ACCOUNT-ID>:application/<INSERT-INSTANCE-ARN>/<INSERT-APPLICATION-ARN>"

    • Group #2 Name: Developer
    • Application Name: sagemaker_readonly

    As part of this validation, the sample solution verifies the group name appears as a whole word in the application name: Case-insensitive, splitting on the -, _, characters and spaces, so ReadOnly matches sagemaker_readonly but read does not. For different use-cases, The GroupNameRegex parameter can be used during deployment.

    Test compliant and non-compliant assignments

    Run the following command to add the ReadOnly group assignment to the sagemaker_readonly application:

    aws sso-admin create-application-assignment --application-arn $APP_READONLY --principal-id $GRP_READONLY --principal-type GROUP

    The group assignment request meets the validation criteria because the application name sagemaker_readonly contains the group name ReadOnly. The output logs for this validation exist within the associated lambda function CloudWatch log group /aws/lambda/identity-center-app-monitor”.

    In this example, the logs will show:

    ✓ COMPLIANT - Group name found in application name

    applicationName="sagemaker_readonly” groupName="ReadOnly”

    Remediation action determined: NONE

    Run the following command to try to add the Developer group assignment to the sagemaker_readonly application:

    aws sso-admin create-application-assignment --application-arn $APP_READONLY --principal-id $GRP_DEVELOPER --principal-type GROUP

    The group assignment request doesn’t meet the validation criteria because the application name sagemaker_readonly doesn’t contain the group name Developer. The output logs for this validation exists within the associated lambda function CloudWatch log group /aws/lambda/identity-center-app-monitor. Note that the remediation action listed shows NOTIFICATION_ONLY, meaning it only sent a notification to the configured SNS topic and did not take action. If you want the group assignment to be deleted, the value should be set to enableAutoDeletion=true.

    In this example, the logs will show:

    ✗ NON-COMPLIANT - Group name not found in application name

    applicationName="sagemaker_readonly” groupName="Developer”

    Remediation action determined: NOTIFICATION_ONLY

    SNS notification sent successfully

    The SNS message will look like:

    {
    	"eventType": "NON_COMPLIANT_ASSIGNMENT",
    	"applicationName": "sagemaker_readonly",
    	"groupName": "Developer",
        "action": "NOTIFICATION_ONLY",
        "status": "SUCCESS",
        "applicationArn": "arn:aws:sso::1234:application/ssoins-1234/apl-1234",
        "groupId": "abc12345-1234-1234-1234-abcdef123457",
        "initiatedBy": { 
        	"type": "AssumedRole", 
        	"arn": "arn:aws:sts::1234:assumed-role/.../you" 
    	}
    }

    Scheduled reporting gives baseline visibility into IAM Identity Center managed applications. Event-driven monitoring can provide near real-time notification or enforcement. Together, these sample solutions can help align and scale Identity Center with your governance and security standards through both historical analysis and immediate response.

    Clean up

    For each deployed CDK stack, run the following commands in the AWS account where it was deployed.

    To delete the remediation stack, run the following commands:

    cd sample-iam-idc-application-discovery-reporting/identity-center-remediation
    cdk destroy

    To delete the reporting stack, run the following commands:

    cd sample-iam-idc-application-discovery-reporting/identity-center-reporting
    cdk destroy

    IAM governance automation at scale

    Achieving effective IAM Identity Center governance at scale requires moving beyond manual processes to automated, continuous monitoring and reporting. The following high-level steps can provide an Identity center governance framework:

    1. Deploy the sample automation with an IAM principal that has access in your delegated administrator account.
    2. Establish a baseline by running your first discovery and reviewing the generated reports.
    3. Configure naming policies to match your organization’s security conventions.
    4. Deploy the event-driven monitoring capabilities to enable real-time policy enforcement and automated response based on the security policies.
    5. Start in notification mode to establish a baseline before enabling auto-remediation.
    6. Integrate with your governance tools by connecting the API endpoints to your compliance dashboards or ITSM tools.
    7. Move to auto-remediation once you have validated policies are working as expected.

    Conclusion

    Managing AWS IAM Identity Center at scale doesn’t have to be a manual, time-consuming process. By implementing automated discovery and reporting combined with real-time event-driven monitoring, you can maintain continuous visibility into your organization’s identity and access landscape, respond immediately to policy violations, and enforce governance policies consistently across your organization. Automation reduces operational work, strengthens security, speeds up incident response, and maintains compliance. Start by deploying these solutions to gain visibility and enable real-time enforcement.

    If you have feedback about this post, submit comments in the Comments section below. If you have questions about this post, start a new thread on AWS re:Post or contact AWS Support.


    Author

    Jonathan Nguyen

    Jonathan is a Principal WWSO AI Security Solution Architect at AWS. He helps customers develop a comprehensive AI security strategy so they can deploy secure AI workloads at scale, integrate AI-powered security services, and defend against AI-powered threats.

    Build a real-time event pipeline with Spark Real-Time Mode on AWS Glue 6.0

    Post Syndicated from Shoukat Ghouse original https://aws.amazon.com/blogs/big-data/build-a-real-time-event-pipeline-with-spark-real-time-mode-on-aws-glue-6-0/

    Real-time event pipelines rarely get to work with a uniform schema. Whether it’s IoT metrics, ecommerce clickstreams, or financial pricing vectors, each event type brings its own schema. An equity trade and a rates trade, for instance, carry almost entirely different fields. Ingesting these multi-schema streams has traditionally forced suboptimal architectural choices. You build separate tables for each event type or maintain a wide STRUCT where every possible field across all event types must be declared upfront (fast reads, but sparse and rigid). The other option is to flatten everything into an unwieldy schema with hundreds of columns. To sidestep that maintenance burden, many teams dump events into a plain JSON string column that introduces significant performance penalty. Querying a single nested field requires your engine to deserialize the entire JSON blob for every row. At scale, you burn compute and budget scanning terabytes of raw text to extract a few bytes of data.

    Adding to the challenge, these pipelines typically demand mixed processing speeds. You need a real-time path (not near-real-time) to flag anomalies or high-risk events with sub-second latency, while simultaneously pushing those same events into analytical storage for deep historical analysis in batch.

    With AWS Glue 6.0, you can tackle all of these challenges (schema heterogeneity, JSON scanning overhead, and mixed-latency requirements) from a single pipeline. Built on Apache Spark 4.1 with Apache Iceberg v3 support, AWS Glue 6.0 brings Variant columns, Variant shredding, Spark Real-Time Mode (RTM), and Arrow-native user-defined functions (UDFs) to a fully managed, serverless environment.

    In this post, we walk you through how to build this multi-layer architecture using a financial services use case: a market risk pipeline processing trade pricing vectors. While the example is finance, the patterns apply wherever you deal with heterogeneous schemas, expensive JSON parsing, and mixed real-time/batch requirements such as IoT device fleets, multi-tenant SaaS platforms, logistics tracking, and beyond. We will show you how to flag high-risk trades with sub-second latency, stream everything into an Iceberg v3 data lake as Variants, and run batch Value at Risk (VaR) computations efficiently using Arrow-native UDFs.

    Solution overview

    A bank’s Market Risk team receives a continuous stream of trade pricing vectors from front-office systems. Each trade event carries:

    1. A trade ID and book/desk IDs.
    2. A pricing vector as semi-structured data. The schema varies by asset class (for example, equities carry risk sensitivities known as Greeks such as delta/gamma, foreign exchange (FX) carries volatility surfaces, rates carry curve sensitivities).
    3. A region ID for jurisdictional reporting (uses a column DEFAULT value, so rows that omit it get auto-populated).

    The team needs three things from this stream, each at a different speed. We build the pipeline in three layers, each addressing a distinct requirement with a purpose-built AWS Glue 6.0 capability.

    Layer 1: Real-time trade position breach detection (sub-second latency)

    Positions must be updated in sub-second time, not seconds of traditional micro-batch streaming. For a team monitoring position limits, those seconds mean trades can breach limits before the system reacts. Spark Real-Time Mode (RTM) eliminates the micro-batch boundary entirely, letting records flow continuously through the pipeline so that high-risk trades trigger alerts within sub-second latency of arrival.

    Layer 2: Near-real-time analytical lakehouse (seconds latency)

    Every trade must land in a queryable data lake within seconds, with heterogeneous pricing vectors stored without declaring a fixed schema upfront. The Iceberg v3 Variant type handles this natively. The raw semi-structured payload goes into a single column regardless of asset class schema. At write time, Variant shredding automatically extracts fields observed in the data into typed Parquet columns, so downstream analytical queries read only the columns they need without deserializing the full blob. Trade amendments and cancellations are handled at a lower cost with deletion vectors (merge-on-read), and column DEFAULT values reduce boilerplate in ingestion code.

    Layer 3: Batch risk computation (minutes to hours latency)

    Risk metrics like Value at Risk (VaR) must be computed in Python across millions of trades. Traditional row-by-row pickle serialization between the Java Virtual Machine (JVM) and Python is the bottleneck. Arrow-native UDFs process data as vectorized columnar batches, eliminating serialization overhead and accelerating Python-based risk calculations.

    The solution uses three separate AWS Glue 6.0 jobs, each independently scalable:

    • Real-time path (Scala, gluestreaming): Reads trades from Amazon Managed Streaming for Apache Kafka (Amazon MSK), enriches them with risk scores and breach flags, and writes alerts to a downstream Kafka topic. It runs with a fixed set of workers that are always on. Downstream fraud detection and position limit systems consume the alerts topic for real-time blocking decisions.
    • Near-real-time path (PySpark, gluestreaming): Reads from the same MSK topic and lands the full trade history into an Iceberg v3 table. It uses Glue auto scaling and can scale down between batches, keeping costs lower.
    • Batch analytics (PySpark, glueetl): Reads from the Iceberg v3 table, extracts fields using variant_get, computes VaR across the portfolio, and writes aggregated risk reports to a downstream summary table.

    The following diagram illustrates the solution architecture.

    Architecture diagram of a real-time market risk pipeline on AWS Glue 6.0. All compute runs inside a VPC within an AWS Account. A Sample Trades Producer (AWS Glue job, simulating front office trading systems) publishes to an Amazon MSK topic named trade-risk-vectors. From MSK, three processing paths branch out. The Real-Time Path uses an AWS Glue 6.0 Spark Real-Time Mode job in Scala for continuous processing (JSON extraction, risk scoring, breach detection), writing alerts to an Amazon MSK trade-alerts topic that feeds CloudWatch Alarms, SNS notifications, and position limit systems. The Near-Real-Time Path uses an AWS Glue 6.0 micro-batch PySpark job that applies PARSE_JSON to Variant, TIMESTAMP_NTZ with nanosecond precision, and shredding, writing to an Amazon S3 Apache Iceberg v3 table named trade_risk_vectors. The Batch Consumption path reads that table with an AWS Glue 6.0 PySpark job using variant_get extraction and an Arrow UDF for Value at Risk computation and jurisdiction classification, writing to an Amazon S3 Iceberg v3 table named daily_risk_summary that feeds downstream analytics. Amazon S3, AWS Glue Data Catalog, and CloudWatch are regional services shown outside the VPC but inside the AWS Account, accessed privately through VPC endpoints.

    Figure 1: Real-time market risk pipeline on AWS Glue 6.0

    Prerequisites

    To follow along with this post, you need the following:

    1. An AWS account in a Region where AWS Glue 6.0 is available.
    2. An AWS Identity and Access Management (IAM) role with permissions to deploy AWS CloudFormation stacks and create resources including AWS Glue, Amazon MSK, AWS Lambda, Amazon Simple Storage Service (Amazon S3), and the AWS Glue Data Catalog.

    Deploy the CloudFormation stack

    We provide an AWS CloudFormation template that provisions all the resources needed for this walkthrough.

    The stack provisions the following resources:

    • An Amazon MSK cluster with two topics: trade-risk-vectors (input) and trade-alerts (real-time alerts output).
    • An Amazon S3 bucket for Iceberg table storage and streaming checkpoints.
    • An AWS Glue database (risk_analytics_<account-id>_glue6b1).
    • An IAM role (GlueRole-<account-id>-glue6b1) with permissions for Glue, MSK, S3, and CloudWatch.
    • Virtual private cloud (VPC) networking: A Glue network connection (connection-<account-id>-glue6b1), S3 gateway endpoint, and Glue interface endpoint.
    • AWS Glue job rtm-alerts-<account-id>-glue6b1 (Scala): This job reads trades from MSK, scores risk in real time using Spark RTM, writes alerts to the trade-alerts topic.
    • AWS Glue job nrt-ingestion-<account-id>-glue6b1 (PySpark): This job reads trades from MSK, writes to Iceberg v3 table with Variant + shredding enabled.
    • AWS Glue job batch-var-<account-id>-glue6b1 (PySpark): This job reads from Iceberg v3 table, computes VaR with Arrow UDF, demonstrates deletion vectors.
    • AWS Glue job producer-<account-id>-glue6b1-helper (PySpark): This job generates sample trade events (equities, FX, rates) to the trade-risk-vectors topic.

    Deploy the CloudFormation stack:

    1. Download the CloudFormation template from the GitHub repository.
    2. Sign in to the AWS CloudFormation console
    3. Choose Create stack > With new resources > Upload a template file, and upload the downloaded template.
    4. Enter the following parameters:
      • VpcId: Your VPC ID.
      • SubnetIds: At least two subnets in different Availability Zones.
      • SecurityGroupId: A dedicated security group that allows all inbound TCP traffic from itself (self-referencing rule).
      • RouteTableId: The main route table for your VPC.
    5. Acknowledge the IAM capabilities and choose Create stack.

    Stack creation takes approximately 20 minutes.

    After the stack completes, open the AWS Glue console and start the jobs in this order:

    1. Start rtm-alerts-<account-id>-glue6b1 and nrt-ingestion-<account-id>-glue6b1.
    2. Once both show RUNNING, start producer-<account-id>-glue6b1-helper.
    3. After the producer finishes (~3.5 minutes), run batch-var-<account-id>-glue6b1 for risk aggregation.

    The consumers must be running before the producer starts so that trades are scored in real time and landed in the Iceberg table as they arrive. The batch job runs last because it reads from the Iceberg table that the near-real-time path populates.

    Understand the Iceberg v3 table design

    The CloudFormation stack provisions Glue jobs that create two Iceberg v3 tables, trade_risk_vectors (primary trade store) and daily_risk_summary (batch VaR output), using new data types and features:

    1. VARIANT: Stores semi-structured pricing vectors without requiring a fixed schema.
    2. DEFAULT values: Automatically applies provided defaults when fields aren’t provided.
    3. Deletion vectors (merge-on-read): Enables fast row-level updates and deletes.

    Open the AWS Glue console under Data Catalog > Tables > trade_risk_vectors.

    AWS Glue Data Catalog console showing the trade_risk_vectors table with its Variant and default-valued columns

    Figure 2: The trade_risk_vectors table in the AWS Glue Data Catalog

    The following is the Create Table command:

    CREATE TABLE {TABLE} (
        trade_id STRING, book_id STRING, desk STRING,
        asset_class STRING DEFAULT 'UNKNOWN',
        execution_time STRING,
        pricing_vector VARIANT,
        var_contribution DOUBLE DEFAULT 0.0,
        risk_weight DOUBLE DEFAULT 1.0,
        trade_date DATE, region STRING DEFAULT 'EMEA'
    ) USING iceberg
    TBLPROPERTIES ('format-version'='3', 'write.delete.mode'='merge-on-read',
        'write.update.mode'='merge-on-read',
        'write.parquet.shred-variants'='true')
    PARTITIONED BY (trade_date, asset_class)

    Note the use of DEFAULT values for asset_class, var_contribution, risk_weight, and region. This is an Iceberg v3 feature that applies defaults automatically when values aren’t provided during writes, reducing boilerplate in ingestion code. The pricing_vector column is defined as a Variant type, and write.parquet.shred-variants='true' automatically extracts Variant fields into separate typed Parquet columns at write time for faster downstream queries.

    Sample trade event generator

    The CloudFormation stack includes a Glue job (producer-<accountid>-glue6b1-helper) that produces realistic trade events to the trade-risk-vectors MSK topic. Each event carries a pricing_vector with a completely different schema per asset class. This is exactly the problem Variant solves.

    Equity trade (greeks, scenarios with sector/region breakdowns):

    JSON pricing vector for an equity trade showing greeks and per-sector and per-region scenario breakdowns

    Figure 3: Sample equity trade pricing vector

    Rates trade (curve sensitivities per tenor, calibration params):

    JSON pricing vector for a rates trade showing curve sensitivities per tenor and calibration parameters

    Figure 4: Sample rates trade pricing vector

    Completely different structures: greeks vs curve sensitivities, BlackScholes vs HullWhite. Both land in the same pricing_vector VARIANT column with no schema changes required.

    Ingest trades with Spark Real-Time Mode

    Traditional Spark Structured Streaming uses micro-batches: collect records, schedule a job, process, commit, wait. Even with small batches, the fixed overhead of planning and scheduling adds noticeable latency per batch. For a risk team monitoring position limits, the delay can let a trade breach a limit before the system reacts.

    The following Scala job reads trade events from Amazon MSK, applies lightweight risk rules based on data directly available in the event, and writes alerts to a Kafka topic, all with sub-second latency. The real-time path intentionally avoids external lookups (market data, volatility surfaces) to stay fast. The full VaR computation happens later in the batch layer where latency is less critical.

    You can view the complete job code in the AWS Glue console under the rtm-alerts-<accountid>-glue6b1 job. Additionally, all the scripts are available in the GitHub repository.

    Scala real-time job code that reads from Kafka, scores risk, and writes alerts to a Kafka topic

    Figure 5: Scala real-time job that scores trades and writes alerts

    The Trigger.RealTime("1 minute") is what distinguishes this from a traditional micro-batch. Records flow through the pipeline continuously. Records are processed the instant they arrive. The 1-minute parameter controls how often Spark checkpoints its progress for recovery. It does not control how often records are processed. RTM on AWS Glue 6.0 currently supports Kafka-source, stateless, Scala workloads with fixed workers (no auto scaling) and update output mode only. This makes it ideal for stateless transformations that require sub-second latency, such as the filter, enrich, score, and route pattern shown here. The heavier computation (VaR, aggregations) runs in the micro-batch/batch layer where sub-second latency is less critical.

    The real-time path acts as a circuit breaker: trades over $50M notional are flagged CRITICAL, over $25M flagged HIGH. Downstream systems consume the trade-alerts topic and can block or escalate before the next trade executes. The detailed VaR computation (which requires market data, volatility surfaces, and the full pricing vector) runs in the batch consumption layer where latency is less sensitive.

    After the streaming phase completes, the job reads back from the trade-alerts topic and measures end-to-end latency. It compares two MSK timestamps: when the trade was received by MSK from the producer, and when the alert was received by MSK from RTM.

    To verify the alerts and latency, open the Amazon CloudWatch console > Log groups > /aws-glue/jobs/output and select the RTM job’s log stream. You will see the alert summary showing each flagged trade with its end-to-end latency. The following is a sample.

    CloudWatch log output listing flagged trades with CRITICAL and HIGH labels and their end-to-end latency

    Figure 6: CloudWatch output showing flagged trades and end-to-end latency

    Store trades in Iceberg v3 with Variant shredding enabled

    The near-real-time path reads from the same MSK topic but writes to an Iceberg v3 table using standard micro-batch streaming. This job runs separately with auto scaling enabled, scaling between batches, keeping costs lower than the always-on real-time path.

    You can view the complete job code in the AWS Glue console under the nrt-ingestion-<accountId>-glue6b1 job. The critical aspects are the Variant conversion and the Iceberg write:

    PySpark code applying PARSE_JSON to build a Variant column and writing to the Iceberg v3 table

    Figure 7: Near-real-time PySpark job writing trades to Iceberg v3 as a Variant

    The PARSE_JSON() function converts the raw pricing vector into a native Variant, regardless of the asset class schema. Whether the incoming trade is an equity with greeks, an FX option with a volatility surface, or a rates swap with curve sensitivities, it all goes into the same column. Since the table has write.parquet.shred-variants enabled, fields observed in the initial sample are automatically extracted into typed Parquet columns for fast downstream queries.

    How shredding works

    During the write process, Spark automatically extracts the Variant fields it observes into separate typed Parquet columns at write time, a feature called shredding. At the start of each write, the engine buffers a sample of rows (controlled by write.parquet.variant-inference-buffer-size), infers which fields exist and their types, then uses that schema to shred all subsequent rows in the file. Every field observed in that sample gets its own typed column, including nested objects. Rows that lack a particular field simply store NULL in that shredded column. For our risk table, fields like $.greeks.delta, $.dv01, and $.model all live in their own typed Parquet columns, even if only one asset class carries a specific field. The result: faster read performance because queries access only the typed columns they need, skipping the rest of the document entirely. Shredding is transparent to queries. variant_get() calls work the same way whether the field is shredded or not. The query engine automatically routes to the shredded column when available, falling back to the binary Variant blob for fields that aren’t part of the inferred schema.

    Note: Shredding adds write latency because the engine must infer the schema and write additional typed columns. In this pipeline, we enable shredding on the near-real-time path and absorb that cost, since the downstream read benefits (batch VaR, ad-hoc queries, audit) far outweigh the write penalty. For latency-sensitive pipelines where every millisecond on the write path matters, you can disable shredding on the streaming table and instead write shredded data in a separate batch job that reads from the unshredded table and inserts into a shredded copy. This approach trades architectural simplicity for lower ingestion latency.

    Build the batch consumption layer

    The third AWS Glue 6.0 job reads from the Iceberg v3 table, extracts risk metrics from the Variant column, computes VaR using an Arrow-native UDF, and writes aggregated results to a summary table.

    You can view the complete job code in the AWS Glue console under the batch-var-<accountid>-glue6b1 job. The key aspects are the variant_get extraction from deeply nested structures and the Arrow-native UDF:

    PySpark code using variant_get to extract deeply nested fields from the Variant column

    Figure 8: Extracting nested Variant fields with variant_get

    Notice how variant_get reaches into arbitrarily nested structures: $.greeks.delta (2 levels), $.scenarios[0].breakdown.by_sector.financials (5 levels), $.model_params.calibration.fit_error (4 levels). All with the same function call. No pre-flattening, no schema-per-asset-class tables, no ETL to restructure the data before querying.

    Once the risk metrics are extracted, we need to run a Monte Carlo-style Historical VaR that simulates 1,000 daily profit and loss (P&L) scenarios per trade and returns the 99th percentile loss. This is where the @arrow_udf decorator comes in.

    Python Arrow UDF code running a Monte Carlo Historical VaR simulation for each trade

    Figure 9: Arrow-native UDF computing Historical VaR

    The @arrow_udf decorator is new in Spark 4.1. Your function receives and returns pyarrow.Array directly, operating on the entire batch of rows at once. There is no pickle serialization, no row-by-row invocation, and no Pandas conversion. Data flows as native Arrow columnar arrays between the JVM and Python. For compute-heavy operations like VaR across hundreds of thousands of rows, this can be significantly faster than traditional scalar UDFs. Additionally, you can use the built-in UDF profilers to identify performance and memory bottlenecks in compute-heavy UDFs such as VaR calculations.

    Handle late trade corrections with deletion vectors

    In financial markets, trade amendments and cancellations are common. The batch VaR job demonstrates this after completing the risk computation. It amends one trade and cancels another.

    PySpark code amending one trade and cancelling another in the Iceberg table

    Figure 10: Amending and cancelling trades with merge-on-read

    Prior to Iceberg v3, row-level deletes required either rewriting entire data files (copy-on-write) or maintaining separate positional delete files that store (file_path, row_position) pairs as Parquet rows (merge-on-read). Both approaches are expensive at scale. Copy-on-write rewrites gigabytes for a single amendment, and positional deletes degrade read performance as delete files accumulate (each read must parse and hash-join all delete records against the data file).

    Because we configured the table with write.delete.mode='merge-on-read', UPDATEs and DELETEs write deletion vectors instead of positional delete files used in Iceberg v2. A deletion vector is a Roaring Bitmap stored in a Puffin file (.puffin), one per affected data file, marking which row positions are deleted. At read time, the engine loads a single bitmap and skips flagged positions with a bit check. No file joins, no linear scan through multiple delete files. The bitmap is compact regardless of how many rows are deleted, and read performance remains predictable as amendments accumulate.

    The batch job also verifies the deletion vectors were created. You can see the results in the job’s output logs.

    Job output confirming deletion vector Puffin files were created for the affected data files

    Figure 11: Output verifying deletion vectors were created

    Clean up

    To avoid incurring further charges, delete the CloudFormation stack. This removes all resources provisioned as part of this post, including the S3 bucket, Glue jobs, Iceberg tables, MSK cluster, and IAM roles.

    Conclusion

    In this post, we built a multi-layer market risk pipeline using AWS Glue 6.0 (real-time alerting, near-real-time ingestion, and batch analytics):

    • Spark Real-Time Mode (RTM) on the real-time path delivers sub-second trade scoring and breach alerting, eliminating the micro-batch boundary so position limits are enforced before the next trade executes.
    • Iceberg v3 Variant on the near-real-time path stores heterogeneous pricing vectors without schema flattening. One table handles equities, FX, and rates with different schemas per row.
    • Variant shredding delivers faster reads by automatically extracting fields into separate typed Parquet columns at write time with no manual tuning required.
    • Arrow-native UDFs eliminate pickle serialization overhead for Python-based risk calculations, processing data as vectorized columnar batches on the batch layer.
    • Deletion vectors handle trade amendments and cancellations without costly data file rewrites, using compact Roaring Bitmaps instead of accumulating positional delete files.
    • Default values reduce boilerplate in ingestion code.

    To get started with AWS Glue 6.0, see the AWS Glue documentation. For more information about Apache Iceberg v3, see the Iceberg specification.


    About the authors

    Shoukat Ghouse

    Shoukat Ghouse

    Shoukat is a Senior Specialist Solutions Architect for Big Data, Analytics, and Data Governance at Amazon Web Services (AWS). He partners with enterprise and financial services customers worldwide to design and scale production-grade data lakehouse platforms on Apache Spark, Apache Iceberg, AWS Glue, Amazon Athena, Amazon EMR and Amazon SageMaker Unified Studio. His focus spans distributed data processing, fine-grained data governance, and helping organizations build AI-ready data foundations that power analytics and machine learning at scale.

    Shrey Malpani

    Shrey Malpani

    Shrey is a Senior Product Manager Technical at Amazon Web Services (AWS), where he works at the intersection of distributed data processing and data integration. He is focused on building and scaling data integration and data management capabilities across services like AWS Glue, Amazon EMR, and Amazon Redshift that help customers build AI-ready data platforms for their analytics and machine learning workflows.

    Danylo Prozorov

    Danylo Prozorov

    Danylo is a Software Development Engineer at Amazon Web Services (AWS), where he works at the intersection of distributed data processing, AI-powered Spark troubleshooting, and AI-driven engineering automation. He focuses on the AWS Glue data integration libraries and AI-powered Spark troubleshooting capabilities across AWS Glue and Amazon EMR, delivering scalable and reliable data integration for customers’ ETL and analytics workloads.

    Kartik

    Kartik

    Kartik is a Software Development Manager on the AWS Glue team. His team builds generative AI features for the Data Integration and distributed system for data integration.

    Extend your data perimeter to the AWS Management Console with Private Access

    Post Syndicated from Madhur Kulkarni original https://aws.amazon.com/blogs/security/extend-your-data-perimeter-to-the-aws-management-console-with-private-access/

    Organizations in regulated industries such as financial services, government, defense, and healthcare restrict their sensitive workloads to isolated network environments with no access to the public internet. Until now, customers could restrict AWS Management Console access to authorized AWS accounts and corporate networks, but the console itself required internet connectivity. This was creating tension between operational convenience and network security controls.

    We’re happy to announce that AWS Management Console Private Access is now generally available with support for virtual private clouds (VPCs) without internet connectivity. Organizations in regulated industries that restrict workloads to isolated network environments can now route all traffic for supported service consoles—including authentication flows, static assets (JavaScript, CSS, images), console-only APIs, and AWS service API calls—through AWS PrivateLink VPC endpoints, eliminating the need for an internet gateway, NAT gateway, or any route to the public internet. This capability is available in all AWS commercial Regions for a select set of supported service consoles.

    In 2023, we launched AWS Management Console Private Access, which you can use to connect to the console by routing console, sign-in, and service API calls through VPC endpoints. However, accessing the console required internet connectivity for static assets and console-only APIs. This meant security teams faced a choice: allow internet connectivity to use the console or deny console access to operators working in network-isolated environments.

    With this launch, AWS Management Console Private Access addresses two common scenarios:

    • Console traffic over internet restricted networks: Traffic for supported service consoles now flows entirely through your VPC endpoints—no proxy allowlists to maintain, no TLS-intercepting proxies to operate, and no CLI-only workflows to accept as a compromise. The same path works seamlessly from Amazon WorkSpaces, Amazon Elastic Compute Cloud (Amazon EC2) instances, and on-premises networks connected through AWS Direct Connect or AWS Site-to-Site VPN. Combined with sign-in resource control policies (RCPs) and sign-in resource policies, you can ensure that console authentication only succeeds from expected networks—even if valid credentials are presented elsewhere, the session is denied. Teams that previously relied on restricted egress rules or manual domain allowlists now get full console access with the same network controls they already trust.
    • Data-exfiltration prevention: Private Access enables you to restrict which AWS accounts and organizational identities can use the AWS Management Console from within your VPC. This prevents access from personal accounts and from accounts outside your organization. Attach a VPC endpoint policy with an aws:ResourceOrgID condition, and console actions are automatically scoped to resources inside your organization. Sign-in RCPs add a second layer by ensuring authentication only succeeds from networks within your perimeter. Together, these controls prevent supported service consoles from being used to access resources in accounts outside your organization—such as personal accounts—without requiring complex network-layer workarounds.

    In this post, you will learn how AWS Management Console Private Access works in environments without internet connectivity, and how to layer access controls using VPC endpoint policies and sign-in resource control policies (RCPs) to strengthen your data perimeter.

    Solution overview

    AWS Management Console Private Access and sign-in resource control policies are a natural extension of the service control policies (SCPs), resource control policies, and VPC endpoint policies you already use for API traffic; now applied to the console session itself. The same data perimeter controls for identity, resource, and network that protect your programmatic access now protect interactive browser sessions too.

    Perimeter Control objective Policy construct Implementation Steps
    Identity Only trusted identities can access my resources Sign-In RCPs and RBPs Restrict which principals can sign in to the console. Before authentication, signin:PrincipalArn is available for exemptions only. After authentication, RCPs restrict at the organization, account, or principal level (aws:PrincipalOrgID, aws:PrincipalAccount, aws:PrincipalArn); RBPs restrict at the account or principal level.
    Identity Only trusted identities are allowed from my network Console VPC endpoint policy and Sign-In VPC endpoint policy Console endpoint: aws:PrincipalOrgID or aws:PrincipalAccount on signed-in identities. Sign-In endpoint: aws:ResourceOrgID or aws:ResourceAccount before authentication, principal and resource keys after authentication. Blocks sign-in to accounts outside your organization, such as personal accounts, from your network.
    Resource My identities can access only trusted resources SCP Resource perimeter SCP with aws:ResourceOrgID follows your principals into every console session; each service API call the console makes on their behalf is denied if the target resource is outside your organization.
    Resource Only trusted resources can be accessed from my network Console VPC endpoint policy and service VPC endpoint policies Console endpoint policy with aws:ResourceOrgID and aws:ResourceAccount scopes what the console can reach through your network.
    Network My identities can access resources only from expected networks SCP Network perimeter SCPs that use aws:SourceVpc deny your principals’ service calls from outside expected networks. With Private Access, requests proxied by the console to supported services carry aws:SourceVpc set to the VPC hosting your Private Access endpoints. Direct browser requests carry VPC context only when the service has its own VPC endpoint, so configure endpoints for every service you use. AWS recommends conditioning on aws:SourceVpc rather than specific aws:SourceVpce values.
    Network My resources can only be accessed from expected networks Sign-In RBPs and RCPs and network perimeter RCPs Sign-In policies deny console authentication from unexpected networks using aws:SourceIp, aws:SourceVpc, aws:SourceVpce, and aws:VpcSourceIp in both pre-authentication and post-authentication statements. Network perimeter RCPs apply the same network conditions to your data resources for any access path.

    With this launch, Console Private Access routes browser traffic for supported service consoles through VPC endpoints, including:

    • Authentication flows – Sign-in, credential exchange, and session token requests
    • Static assets – JavaScript, CSS, and images that render the console UI
    • Service console API calls – The backend requests made when users interact with service consoles

    How traffic flows from a workload in a private VPC through the three Private Access endpoints, with no path to the public internet (shown in Figure 1):

    1. The operator’s browser requests <region>.console.aws.amazon.com.
    2. The corporate DNS forwarder forwards the query to an Amazon Route 53 Resolver inbound endpoint configured within the VPC, which forwards the traffic to the console VPC endpoint.
    3. Browser traffic flows from on-premises through Direct Connect (or AWS Site-to-Site VPN) to the VPC, and the VPC endpoint routes traffic to the console service over the AWS private network.
    4. The console service redirects to the SignIn endpoint <region>.signin.aws.amazon.com to establish a browser session.
    5. The DNS now resolves to the SignIn VPC endpoint’s private IP addresses, and browser traffic flows to the SignIn service over the AWS private network.
    6. After entering credentials, the SignIn service evaluates VPC endpoint policies, in addition to resource-based policies (RBPs) and RCPs, then redirects back to the console.
    7. The console evaluates VPC endpoint policies, loads static content from the console API VPC endpoint, and enforces identity and resource restrictions when making calls to AWS service APIs.
    8. Users can now access the AWS Management Console over Private Access.
    Figure 1: Network isolation architecture

    Figure 1: Network isolation architecture

    Deploy a pilot of AWS Management Console Private Access

    This high-level walkthrough sets up AWS Management Console Private Access for a single AWS Region within one organizational unit (OU). We recommend rolling out incrementally; validate each step before you expand to additional Regions and OUs.

    If you want to validate the mechanics of a Private Access deployment before you build out the full solution, the Getting started with a test environment guide walks you through a minimal configuration: a single VPC with the three Private Access endpoints and a permissive policy. This gives you a working setup to experiment with, independent of the deployment described in the rest of this post. To understand how sign-in policies can verify a user’s network location when they access the console, see Controlling console access with resource-based policies and resource control policies.

    Prerequisites

    You must have the following prerequisites:

    Step 1: Baseline current console access

    Before changing anything, use CloudTrail to map how your users access the console today. Search for eventName = ConsoleLogin over a representative window (we recommend 30 days) and review the sourceIPAddress, vpcEndpointId, and awsRegion fields. Identify which identity types are in use: root user, IAM user, SAML federation, and AWS IAM Identity Center. Decide which OU or account you will pilot with.

    Note: A misconfigured sign-in policy can lock users out of the console. Avoid piloting in a production or shared account. Instead, use a dedicated test account and configure a break-glass principal (covered in Step 5) before enabling access enforcement.

    Step 2: Create the Private Access VPC endpoints

    In your chosen Region, create or identify a VPC to host the endpoints, then create three interface VPC endpoints in that VPC:

    • com.amazonaws.<region>.console for the console.
    • com.amazonaws.<region>.signin for AWS Sign-In.
    • com.amazonaws.<region>.console-static for console-only APIs. This endpoint is required only if your VPC has no internet path.

    Step 3: Configure private DNS for AWS Management Console Private Access

    To use AWS Management Console Private Access, you must configure private DNS so that the console domains—.console.aws.amazon.com, .signin.aws.amazon.com, and the associated static-content domains—resolve to your interface endpoints’ network interfaces within your VPC.

    • For workloads inside your VPC: If the workloads in your VPC use the default Amazon Route 53 Resolver, no additional DNS configuration is required. When you create each interface endpoint, enable the private DNS name option (set PrivateDnsEnabled = true). The public console domains will then resolve automatically to the endpoint network interfaces inside your VPC. If you use a custom DNS resolver or a private hosted zone, you must configure it explicitly to map the console domains to the endpoint addresses. See Working with private hosted zones for more information. For the complete list of domains and detailed DNS configuration steps, see the AWS Management Console Private Access required endpoints documentation.
    • For workloads outside your VPC: For workloads that reach the endpoints from outside the VPC—such as corporate offices connecting over AWS Direct Connect or AWS Site-to-Site VPN—ensure that your corporate DNS resolver returns the endpoint addresses for these domains. See Simplify DNS management in a multi-account environment with Route 53 Resolver for more information.

    Step 4: Verify private connectivity

    Sign in to the console from a workload inside your VPC. The console should load normally. To confirm that traffic is routing through your VPC endpoints, look for the lock icon in the console navigation bar, shown in Figure 2.

    Figure 2: Console Private Access

    Figure 2: Console Private Access

    You can also verify in CloudTrail that recent ConsoleLogin events show the vpcEndpointId field populated with one of your endpoint IDs. Here’s an example CloudTrail ConsoleLogin event snippet showing the vpcEndpointId field:

    {
      "eventVersion": "1.08",
      "userIdentity": {
        "type": "AssumedRole",
        "principalId": "AROA3XFRBF23EXAMPLE:john.doe",
        "arn": "arn:aws:sts::123456789012:assumed-role/Admin/john.doe",
        "accountId": "123456789012"
      },
      "eventTime": "2026-07-08T19:15:32Z",
      "eventSource": "signin.amazonaws.com",
      "eventName": "ConsoleLogin",
      "awsRegion": "us-east-1",
      "sourceIPAddress": "10.0.1.47",
      "userAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)...",
      "requestParameters": null,
      "responseElements": {
        "ConsoleLogin": "Success"
      },
      "additionalEventData": {
        "LoginTo": "https://console.aws.amazon.com/console/home",
        "MobileVersion": "No",
        "MFAUsed": "Yes",
        "vpcEndpointId": "vpce-0abc123def456789a"
      },
      "eventID": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
      "eventType": "AwsConsoleSignIn",
      "recipientAccountId": "123456789012"
    }
    

    If the AWS Management Console doesn’t load, work through the following checks.

    Private DNS is enabled on each interface endpoint (or your custom resolver returns the endpoint addresses)

    When Private DNS is enabled, AWS automatically creates the DNS entries that resolve the service domains (such as console.aws.amazon.com) to the private IP addresses of your VPC endpoints. Without it, your browser still routes to the public AWS endpoints, bypassing your private access setup entirely.

    1. Confirm that each endpoint shows PrivateDnsEnabled:
      aws ec2 describe-vpc-endpoints \
      --filters "Name=vpc-endpoint-type,Values=Interface" \
      --query "VpcEndpoints[].{Id:VpcEndpointId,Service:ServiceName,PrivateDns:PrivateDnsEnabled}" \
      --output table
      

    2. Then, from within your VPC, verify that the domains resolve to private addresses:
      nslookup console.aws.amazon.com
      nslookup signin.aws.amazon.com
      
      # Should return a private IP (e.g., 10.x.x.x), not a public one
      

    Each query should return a private IP address from your VPC CIDR range. If you use a custom DNS resolver instead of the Amazon-provided DNS, ensure your forwarding rules direct the AWS domain queries to the Route 53 Resolver inbound endpoints in your VPC.

    The endpoint security groups allow HTTPS (TCP 443) from your workload subnets

    Each VPC endpoint creates elastic network interfaces (ENIs) in your subnets, and these ENIs are governed by security groups. If those security groups don’t permit inbound HTTPS traffic from your workloads, the connection fails silently.

    1. Identify the security groups attached to your endpoints:
      aws ec2 describe-vpc-endpoints --vpc-endpoint-ids vpce-0abc123def456789a \
        --query "VpcEndpoints[].Groups[].GroupId" --output text
      

    2. Then verify that each security group allows inbound TCP 443 from your workload subnets:
      aws ec2 describe-security-groups --group-ids sg-xxxxxxxx \
        --query "SecurityGroups[].IpPermissions[?ToPort==\`443\`]" \
        --output json
      

    For traffic from outside the VPC (Direct Connect or Site-to-Site VPN), corporate DNS returns the endpoint IPs and the route propagates correctly

    If you access the console from an on-premises workstation connected over AWS Direct Connect or AWS Site-to-Site VPN, two additional conditions must be met.

    1. Your corporate DNS must resolve the AWS domains to the VPC endpoint private IPs. From your on-premises machine, run:

      nslookup console.aws.amazon.com

      If this returns public AWS IPs, your corporate DNS isn’t forwarding queries through Route 53 Resolver. Configure conditional forwarding for the aws.amazon.com and amazonaws.com domains to your Resolver inbound endpoint IPs.

    2. Second, network routes must propagate correctly. Ensure the route table associated with your endpoint subnets has propagated routes from your virtual private gateway (VGW) or transit gateway, so return traffic can reach your on-premises network. Verify this with:
      aws ec2 describe-route-tables \
        --filters "Name=association.subnet-id,Values=subnet-xxxxx" \
        --query "RouteTables[].PropagatingVgws"
      

    A quick end-to-end validation: Run traceroute console.aws.amazon.com from your workstation and confirm the path uses private hops only—no traffic should traverse the public internet.

    If the console loads but the lock icon is missing

    If the console loads but the connection isn’t private (for example, the lock icon is missing), the browser is reaching the console over the public internet instead of through your VPC endpoints.

    • Run nslookup console.aws.amazon.com from a workload inside the VPC. The result should be a private IP from your VPC CIDR range. A public IP means DNS is bypassing the endpoint, which usually happens because Private DNS has not been enabled on the interface endpoint (set PrivateDnsEnabled = true).
    • For workloads outside the VPC, make sure your corporate DNS forwards the console domains into the VPC, for example, through an Amazon Route 53 Resolver inbound endpoint.

    Step 5: Apply VPC endpoint policies

    Attach an endpoint policy to the console and AWS Sign-In endpoints that limits access to identities in your organization. The static-content endpoint doesn’t support endpoint policies.

    Begin with a permissive Allow * policy and confirm that traffic routes through the endpoints (you should see the vpcEndpointId field populated in CloudTrail console events). After confirming the routing, add restrictions to your VPC endpoint policy and observe the traffic.

    A starter policy uses two condition keys: aws:PrincipalOrgID to restrict identities to your organization and aws:ResourceOrgID to restrict the resources the console can reach to your organization’s resources. The full reference, including additional condition keys and resource-restriction patterns, is in the AWS Management Console Private Access user guide.

    For policies beyond the pilot, see Data perimeters on AWS. The data perimeter policy examples GitHub repository covers service-specific considerations for implementing data perimeters in your environment.

    Step 6: Apply a Sign-In policy

    Sign-In policies deny console authentication requests that don’t match your network or principal conditions. The policy is composed of a pre-authentication statement covering signin:Authenticate and a post-authentication statement covering signin:AuthorizeOAuth2Access and signin:CreateOAuth2Token. Include both statements.

    For your pilot, deploy the policy as an RCP from your AWS Organizations management account. When enabled, the RCP applies to all accounts in your organization, so we recommend piloting in a dedicated test organization before rolling it out broadly. Activate enforcement by calling the signin:PutConsoleAuthorizationConfiguration API for the organization in the us-east-1 Region (AWS Sign-In replicates policies globally from there). Resource permission statements have no effect until console authorization is enabled.

    Important: Configure at least one excluded principal as a break-glass path before you enable the RCP. The recommended principal is a dedicated IAM role.

    1. Write the permission statements that define the network conditions:
      Example – Restrict access to corporate VPC:

      aws signin put-resource-permission-statement \
        --source-vpc vpc-0abc123def456789 \
        --requested-region us-west-2 \
        --excluded-principal "arn:aws:iam::123456789012:user/EmergencyAdmin" \
        --region us-east-1
      

      Example – Restrict access to specific IP range:

      aws signin put-resource-permission-statement \
        --source-ip "IP_ADDRESS" \
        --excluded-principal "arn:aws:iam::123456789012:role/BreakGlassRole" \
        --region us-east-1
      

    2. Enable console authorization for the organization to start enforcing the policy.
      aws signin put-console-authorization-configuration \
        --target-id <your-target-id> \
        --region us-east-1
      

    3. Review the consolidated policy that’s now in effect: 
      aws signin get-resource-policy --region us-east-1
      

    For policy examples, the AWS Command Line Interface (AWS CLI) reference, and the lockout-recovery procedure, see the sign-in RBP blog post and the Controlling console access with resource-based policies documentation. The same documentation also covers the per-account alternative, which uses an RBP attached to a single account instead of an organization-wide RCP.

    Step 7: Add a service VPC endpoint

    So far, the console shell loads, the lock icon appears, and your Sign-In policy lets approved identities through. If you sign in to a service console such as the AWS Key Management Service (AWS KMS) console, the page might fail to load resources or hang. The Private Access endpoints carry the console shell, not the service API calls that the console makes on your behalf. In a VPC without an internet gateway, those calls have nowhere to go.

    Add a VPC endpoint for the service itself. For the pilot, create an AWS KMS interface endpoint (com.amazonaws.<region>.kms) in the same VPC, with Private DNS enabled. Open the AWS KMS console from inside the VPC and confirm the list of keys loads. Repeat for each service your users need on day one. Please note that a single service console often calls more than one AWS service API. If a console loads but parts of the page show errors or stay empty, the most common cause is a missing endpoint for one of the services it depends on.

    The current list of services that support PrivateLink is in the AWS PrivateLink documentation. Service consoles whose services don’t support PrivateLink will not work in a no-internet VPC and need to be handled separately.

    Step 8: Hide Regions and services you haven’t configured (optional)

    Console links to a service or Region that you don’t have endpoints for will fail inside your VPC. To prevent users from navigating to broken pages, use User Experience Customization (UXC) to hide Regions and services that aren’t part of your Private Access deployment. UXC is configured at the account level and applies to navigation, search results, and service-selection drop-downs.

    Step 9: Validate, then expand

    After applying the endpoint policies and the Sign-In RCP to one pilot account:

    1. Sign in from inside the corporate network. The session should succeed.
    2. Sign in from outside the corporate network. The session should be denied at the Sign-In step, before reaching the console.
    3. In CloudTrail, confirm ConsoleLogin events show vpcEndpointId populated for traffic from inside the network.
    4. For unexpected denials, look in CloudTrail for ConsoleLogin events with the error message Authorization denied because of a resource-based policy or Authorization denied because of a resource control policy to identify which statement was responsible.

    Considerations

    A few items worth mentioning before you commit to this design:

    • AWS IAM Identity Center: IAM Identity Center sign-in support isn’t yet available through a VPC endpoint. Initial single sign-on (SSO) authentication must still transit over the internet.
    • Programmatic access: Sign-In RBPs and RCPs gate interactive console sign-in. AWS SDK and AWS CLI requests signed with SigV4 aren’t affected. This is also your recovery path: a principal with signin:DeleteConsoleAuthorizationConfiguration permission can disable enforcement programmatically if console authorization is misconfigured.
    • Apps integrated with AWS Sign-In: Sign-In policies also apply to Amazon Connect, Amazon WorkSpaces, Amazon QuickSight, AWS Health Dashboard, Amazon AppStream 2.0, and Amazon Lightsail when those applications use AWS Sign-In to authenticate.
    • AWS Management Console Private Access is available in all commercial AWS Regions but supports only a subset of AWS service consoles. See Supported AWS Regions, service consoles, and features in Private Access documentation for more information.
    • For services that aren’t supported, you can still navigate to other consoles, but will require internet connectivity for the unsupported service consoles and console-only APIs.
    • Costs: You pay regular AWS PrivateLink endpoint pricing and data processing for each endpoint and each Region you deploy in. The three Private Access endpoints (console, signin, and console-static) plus the service endpoints you already use are the relevant line items.

    Conclusion

    In this post, we showed you how to extend the AWS data perimeter framework to the AWS Management Console. You routed console traffic through VPC endpoints with AWS Management Console Private Access, restricted console sign-in by network and organization with Sign-In RBPs and RCPs, and configured the console to operate in a VPC without an internet gateway. The four control objectives that you already enforce for API traffic now also apply to the console.

    To get started, see the AWS Management Console Private Access documentation. For deployment patterns and Region-by-Region considerations, see the AWS Management Console Private Access reference architectures. For background on the broader pattern, see Establishing a data perimeter on AWS.

    If you have feedback about this post, submit comments in the Comments section below. If you have questions about this post, start a new thread on the IAM forum on AWS re:Post or contact AWS Support.


    Madhur Kulkarni

    Madhur Kulkarni

    Madhur is a Sr. Customer Solutions Manager at AWS, working with Strategic Accounts customers to accelerate cloud adoption and drive business outcomes. He partners with cross-functional teams across customer engineering, AWS service teams, and specialists organizations to deliver enterprise-scale cloud solutions.

    Mateusz Jaworski

    Mateusz Jaworski

    Mateusz is a Principal Engineer at AWS, where he works on AWS Management Console.

    Sujay Ghosh

    Sujay Ghosh

    Sujay is a Software Development Manager at AWS, where he leads a team responsible for enabling secure, reliable access to the AWS Management Console. He is passionate about building scalable infrastructure that helps millions of customers manage their cloud resources safely and efficiently.

    Abhijit Barde

    Abhijit Barde

    Abhijit is a Principal Product Manager at AWS, where he focuses on making it straightforward for all AWS users to discover, monitor, and operate their AWS infrastructure using conversational assistants and generative AI.

    How Picnic configured multiple OAuth providers for Amazon MQ

    Post Syndicated from Oscar Mapfumo Sibanda original https://aws.amazon.com/blogs/big-data/how-picnic-configured-multiple-oauth-providers-for-amazon-mq/

    This post is co-written with Oscar Mapfumo Sibanda from Picnic.

    Picnic is an Amsterdam-based tech scale-up that reinvents how people buy food. It isn’t a supermarket with a digital layer but a tech company that happens to deliver groceries. Picnic is engineered in-house: the customer app, the fulfillment platform, the supply chain, and the routing technology that guides a fleet of thousands of electric vehicles through the Netherlands, Germany, and France. Software doesn’t merely support business. Software is a business.

    At the center of this system, RabbitMQ is the core component. It’s the communication backbone connecting hundreds of microservices across the entire business lifecycle, from ordering and logistics to delivery and finance. At peak, Picnic’s platform processes close to one million messages per second. At this scale, messaging is no longer only background infrastructure. It becomes part of the company’s operational nervous system. To keep that system highly available, scalable, and resilient as Picnic grows, the company decided to use Amazon MQ as a managed service.

    The next challenge was identity. Picnic’s authentication strategy clearly distinguishes between people and services. Operators sign in through Keycloak, the company’s single sign-on provider, while Picnic’s Amazon Elastic Kubernetes Service (Amazon EKS) workloads are adopting AWS Identity and Access Management (IAM) authentication to eliminate static credentials. A single broker therefore must trust two identity providers at once. The Amazon MQ documentation covers configuring OAuth 2.0 with a single provider. This post extends that guidance to a multi-provider setup on the same broker.

    In this post, we show how Picnic solved that problem. You will learn how to configure an Amazon MQ for RabbitMQ broker to accept tokens from multiple OAuth 2.0 identity providers, using Keycloak and IAM as the working example. You will also see how to map each provider’s scopes to RabbitMQ permissions and how to roll the change out on a running broker without disrupting connected users.

    Background and prerequisites

    Amazon MQ for RabbitMQ supports OAuth 2.0 authentication and authorization, where broker users and their permissions are managed by an external identity provider. User authentication and resource permissions for vhosts, exchanges, queues, and topics are centralized through the OAuth 2.0 provider’s scope system.

    RabbitMQ’s OAuth 2.0 plugin supports multiple resource servers and audiences, allowing different OAuth 2.0 providers to issue tokens that a single broker can validate. This capability is essential if you operate in multiple environments or have teams registered with separate identity providers.

    Prerequisites

    To follow along with this post, you need:

    1. An active AWS account.
    2. An Amazon MQ for RabbitMQ broker with OAuth 2.0 configured for at least one identity provider (see Using OAuth 2.0 authentication and authorization for Amazon MQ for RabbitMQ).
    3. A second OAuth 2.0 identity provider configured and operational.
    4. Outbound web identity federation enabled for your AWS account (if using IAM as a provider).
    5. Basic familiarity with RabbitMQ configuration and OAuth 2.0 concepts.
    6. AWS Command Line Interface (AWS CLI) version 2.27 or later (required for the get-web-identity-token command used in the testing section).

    Note: The information in this post reflects Amazon MQ for RabbitMQ features and behavior at the time of publication. We recommend checking the Amazon MQ documentation, release notes and best practices before implementation.

    Solution architecture

    The design rests on a single idea: a RabbitMQ broker can trust more than one identity provider at the same time, and it decides which one to apply per token rather than per broker. RabbitMQ does this by reading the aud (audience) claim of each incoming token and matching it against a configured resource server. Each resource server is bound to one OAuth 2.0 provider, so the audience determines both which signing keys validate the token and which permission rules apply.

    Architecture diagram

    The following two diagrams show how services and operators authenticate the broker through their respective identity providers.

    Services authentication flow from an Amazon EKS workload through AWS STS to the Amazon MQ for RabbitMQ broker over AMQPS

    Figure 1: Services (IAM) flow

    Services authenticate through IAM. An Amazon EKS workload assumes an IAM role and generates a web identity token (1), which AWS Security Token Service (AWS STS) issues with an audience of rabbitmq-iam (2). The workload presents that token as its password when it connects to the broker over Advanced Message Queuing Protocol (AMQPS) on port 5671 (3). The broker selects the matching resource server, verifies the token’s signature against the AWS STS signing keys (4), and maps the role’s Amazon Resource Name (ARN) to the permissions the workload needs (5).

    Operators authentication flow from the RabbitMQ management console through Keycloak single sign-on to the broker

    Figure 2: Operators (Keycloak) flow

    Operators authenticate through Keycloak. An operator opens the RabbitMQ management console and initiates login (1), and the console redirects the browser to Keycloak (2). Keycloak authenticates the operator and issues a token whose audience targets the console resource server, rabbitmq-keycloak (3). The browser presents that token to the broker (4), which verifies the signature against Keycloak’s signing keys (5). The broker then reads the operator’s group membership and grants access (6): the Operator group receives read-only permissions, while the Administrator group receives full control.

    Two constraints follow this design. First, audience verification is a single broker-wide setting that applies to every provider at once, so each provider must issue tokens carrying the exact audience its resource server expects. Second, the broker is private, deployed inside an Amazon Virtual Private Cloud (Amazon VPC) with no public exposure. Both providers’ endpoints must be resolvable, either through publicly addressable JSON Web Key Set (JWKS) endpoints or through private networking, because the broker fetches signing keys from those endpoints.

    Implementation walkthrough

    This walkthrough configures one Amazon MQ for RabbitMQ broker to trust two identity providers: Keycloak for operators and AWS IAM for services. The steps assume you already have a running broker, a Keycloak realm, and outbound web identity federation enabled for your AWS account. All configurations are applied through a RabbitMQ configuration revision using the AWS Command Line Interface (AWS CLI).

    Enable OAuth 2.0 on the broker

    The first block activates the OAuth 2.0 backend and keeps the internal backend in place. Internal authentication remains active deliberately: Amazon MQ creates an administrator user when the broker is provisioned, and that user is needed for break-glass access.

    auth_backends.1 = oauth2
    auth_backends.2 = internal
    auth_oauth2.verify_aud = true

    Setting verify_aud = true tells RabbitMQ to reject any token whose aud claim does not match a configured resource server. This single broker-wide setting governs every provider you add.

    Add the first identity provider (Keycloak)

    A resource server binds an audience value to a provider and a set of permission rules. The Keycloak resource server uses the id rabbitmq-keycloak, which is the audience the realm must place in its tokens. RabbitMQ reads the operator’s group membership from the group_membership claim and resolves it through scope aliases.

    auth_oauth2.resource_servers.1.id = rabbitmq-keycloak
    auth_oauth2.resource_servers.1.oauth_provider_id = keycloak
    auth_oauth2.resource_servers.1.scope_prefix = rabbitmq.
    auth_oauth2.resource_servers.1.additional_scopes_key = group_membership
    auth_oauth2.resource_servers.1.preferred_username_claims.1 = email
    auth_oauth2.resource_servers.1.scope_aliases.1.alias = Operator
    auth_oauth2.resource_servers.1.scope_aliases.1.scope = rabbitmq.read:*/* rabbitmq.write:^$ rabbitmq.configure:^$ rabbitmq.tag:monitoring
    auth_oauth2.resource_servers.1.scope_aliases.2.alias = Administrator
    auth_oauth2.resource_servers.1.scope_aliases.2.scope = rabbitmq.read:*/* rabbitmq.write:*/* rabbitmq.configure:*/* rabbitmq.tag:administrator

    The Operator group is read-only: it can read any resource and view the management UI through the monitoring tag. The Administrator group receives full permissions plus the administrator tag. This role is least privilege by design.

    The provider is configured with its issuer and JWKS endpoint:

    auth_oauth2.oauth_providers.keycloak.https.hostname_verification = wildcard
    auth_oauth2.oauth_providers.keycloak.issuer = https://keycloak.example.com/auth/realms/test
    auth_oauth2.oauth_providers.keycloak.jwks_uri = https://keycloak.example.com/auth/realms/test/protocol/openid-connect/certs

    To let operators sign in from the management console, expose Keycloak as a management resource:

    management.oauth_enabled = true
    management.oauth_disable_basic_auth = false
    management.oauth_scopes = openid email profile
    management.oauth_resource_servers.1.id = rabbitmq-keycloak
    management.oauth_resource_servers.1.oauth_client_id = rabbitmq-keycloak
    management.oauth_resource_servers.1.label = Keycloak SSO

    Add the second identity provider (AWS IAM)

    Adding a second provider means adding a second resource server and a second entry under oauth_providers. The IAM resource server uses the id rabbitmq-iam because the audience is set when minting the token.

    auth_oauth2.resource_servers.2.id = rabbitmq-iam
    auth_oauth2.resource_servers.2.oauth_provider_id = aws_iam
    auth_oauth2.resource_servers.2.scope_prefix = rabbitmq/
    auth_oauth2.resource_servers.2.additional_scopes_key = sub
    auth_oauth2.resource_servers.2.scope_aliases.1.alias = arn:aws:iam::123456789012:role/EKSWorkloadRole
    auth_oauth2.resource_servers.2.scope_aliases.1.scope = rabbitmq/read:*/* rabbitmq/write:*/* rabbitmq/configure:*/* rabbitmq/tag:policymaker
    auth_oauth2.oauth_providers.aws_iam.https.hostname_verification = wildcard
    auth_oauth2.oauth_providers.aws_iam.issuer =
    auth_oauth2.oauth_providers.aws_iam.jwks_uri =

    The IAM workload receives the policymaker tag. It can publish, consume, and manage policies but does not receive the administrator tag.

    Apply the configuration and restart the broker:

    CONFIG_ID=$(aws mq describe-broker --broker-id $BROKER_ID \
      --query 'Configurations.Current.Id' --output text)
    REVISION=$(aws mq update-configuration --configuration-id $CONFIG_ID \
      --data "$(cat rabbitmq.conf | base64 | tr -d '\n')" \
      --query 'LatestRevision.Revision' --output text)
    aws mq update-broker --broker-id $BROKER_ID \
      --configuration Id=$CONFIG_ID,Revision=$REVISION
    aws mq reboot-broker --broker-id $BROKER_ID

    Note: The base64 command syntax differs between Linux and macOS. The preceding command (cat file | base64 | tr -d '\n') is portable on both operating systems. If running exclusively on Linux, you can also use base64 --wrap=0 rabbitmq.conf. On macOS, the equivalent command is base64 -i rabbitmq.conf.

    Testing and validation

    Validate each provider independently. For IAM, assume the role and request a token from AWS STS, then present it as the AMQP password:

    TOKEN=$(aws sts get-web-identity-token \
      --audience "rabbitmq-iam" \
      --signing-algorithm ES384 \
      --duration-seconds 300 \
      --query 'WebIdentityToken' --output text)
    # Username is empty (ignored by the OAuth plugin); the token is passed as the password
    curl -u ":$TOKEN" https://<broker-id>.mq.<region>.on.aws/api/overview

    Note: The get-web-identity-token API requires outbound web identity federation to be enabled on your AWS account and AWS CLI version 2.27 or later.

    A successful response confirms the IAM resource server accepted the token. For Keycloak, open the management console, choose Keycloak SSO, and sign in as an operator.

    When a login fails, decode the JSON Web Token (JWT) and check two claims. The aud claim must exactly match a resource server id. With verify_aud = true, a missing or mismatched audience is the most common cause of rejection. If the audience is correct but permissions are missing, verify the scope_prefix is set correctly.

    Operational considerations

    A few points deserve attention before you run this pattern in production.

    1. Key rotation: When rotating signing keys at a provider, publish the new key in the JWKS endpoint before revoking the old one. The broker caches keys, so overlapping both during the transition window prevents authentication failures while the cache refreshes.
    2. Audience validation: Audience remains the linchpin. With verify_aud enabled, every provider must issue tokens carrying the audience its resource server expects, so confirm this whenever you onboard a new one. Don’t disable audience validation in production. The RabbitMQ OAuth 2.0 plugin does not perform token revocation checks, which makes audience binding a critical control that prevents tokens issued for other services from granting access.
    3. Scope prefix: scope_prefix values are optional. They’re needed only if the tokens don’t follow the default format. RabbitMQ only reads scopes carrying the expected prefix, so a token can authenticate yet grant nothing if the prefix is missing. Map each provider to the least privilege its principals need. For example, prefer narrow scopes like read:orders over blanket read:all to limit the scope of impact if a single provider’s credentials are compromised.
    4. Token lifetime: Because the plugin does not support token revocation, token lifetime is your primary control over leaked credentials. Issue short-lived access tokens and have your client applications refresh them proactively at approximately 75 percent of the token’s lifetime to avoid connection disruptions when a token expires mid-session.
    5. Monitoring: Authentication failures and refused tokens are recorded in the broker’s connection log group in Amazon CloudWatch, which can be reached through the Amazon CloudWatch Logs link on the broker’s page in the Amazon MQ console. Beyond logs, set up CloudWatch alarms on RabbitMQMemUsed, RabbitMQDiskFree, and ConnectionCount. An unexpected spike in failed connections is often the first sign of a token or audience misconfiguration. For unaggregated, per-node visibility, consider enabling the Prometheus metrics endpoint: metrics such as rabbitmq_auth_attempts_failed_total surface OAuth rejections faster than the CloudWatch one-minute polling interval.
    6. Network controls: Enforce defense in depth by restricting broker access using security groups so that only authorized VPCs and IP ranges can reach the AMQPS and management endpoints. This matters especially in an OAuth setup because, once a token has been issued, the broker cannot revoke it before it expires.

    Cleanup

    To avoid incurring future costs, delete the resources created during this walkthrough if you no longer need them:

    1. Delete Amazon MQ broker and configurations.
    2. Remove test OAuth application registrations from your identity providers.
    3. Delete any IAM roles created for testing.

    Conclusion

    In this post, we demonstrated how Picnic configured an Amazon MQ for RabbitMQ broker to authenticate tokens from two OAuth 2.0 identity providers: Keycloak for human operators and AWS IAM for machine-to-machine services on a single broker instance. The key mechanism is RabbitMQ’s support for multiple resource servers, where the audience claim in each token determines which provider’s signing keys and permission rules apply.

    With this approach, the Picnic team was able to cleanly separate human and machine authentication without the operational overhead of running separate brokers, while retaining fine-grained access control for both token issuers.

    This pattern works with any combination of OAuth 2.0 providers and is particularly valuable for organizations looking to consolidate messaging infrastructure while maintaining distinct identity boundaries.

    To learn more about Amazon MQ for RabbitMQ and OAuth 2.0 authentication, see Authentication and authorization for Amazon MQ. For a hands-on walkthrough of configuring OAuth 2.0 with Amazon MQ for RabbitMQ, see Using OAuth 2.0 authentication and authorization for Amazon MQ for RabbitMQ. The configuration examples in this post are broker-level settings applied through the Amazon MQ API. No standalone code repository is required.


    About the authors

    Oscar Mapfumo Sibanda

    Oscar Mapfumo Sibanda

    Oscar is a Senior Site Reliability Engineer at Picnic Technologies in the Netherlands. He builds infrastructure that supports rapid scaling, empowers engineering teams to move independently, and strengthens the security posture across the organization. Outside of work he paints and takes photographs; he is a technology enthusiast in the pursuit of happiness.

    Ayush Kumar

    Ayush Kumar

    Ayush is a Technical Account Manager at Amazon Web Services based in the Netherlands. He works with enterprise customers to optimize their cloud architectures and accelerate innovation on AWS. You’ll find him experimenting in the kitchen in his spare time.

    Amit Singh

    Amit Singh

    Amit is a Senior Solutions Architect at AWS, working with enterprise retail customers in the Benelux region. He helps customers design cloud-native architectures, navigate complex modernization journeys, and adopt AI/ML capabilities at scale. Outside of work, he enjoys exploring new places and chasing the perfect shot, whether through a camera lens or on a running trail.

    Build with geospatial and variant types in Iceberg v3 on AWS Glue 6.0

    Post Syndicated from Shoukat Ghouse original https://aws.amazon.com/blogs/big-data/build-with-geospatial-and-variant-types-in-iceberg-v3-on-aws-glue-6-0/

    As organizations build data lakes that combine geospatial data, high-frequency event streams, and heterogeneous payloads, the limitations of older table formats become acute. Without a native geospatial type, coordinates require separate float columns (latitude/longitude) with no spatial predicates. Without nanosecond-precision timestamps, sub-microsecond event ordering is lost. Without a variant type, semi-structured data forces a choice between rigid flattening and untyped JSON strings. Each workaround adds complexity, slows queries, and increases maintenance burden.

    AWS Glue 6.0, powered by Apache Spark 4.1, removes these workarounds by adding support for Apache Iceberg v3, bringing new column-level capabilities to your data lake tables. These include new data types: native geospatial types (GEOMETRY with spatial predicates, and GEOGRAPHY), nanosecond-precision timestamps, and the VARIANT type for semi-structured data with automatic shredding. Iceberg v3 also adds support for DEFAULT column values. These are table format features. After they’re written, they’re readable by any Iceberg v3-compatible engine that supports these features.

    In this post, we build a connected vehicle fleet monitoring pipeline that uses these capabilities in a single Iceberg v3 table. Vehicles emit telemetry events with GPS coordinates (geospatial), sub-microsecond event times (nanosecond), and sensor payloads that vary by vehicle type (variant). We ingest these events, run spatial queries to detect geofence violations, sequence events at nanosecond precision, and extract typed metrics from heterogeneous payloads, all without workarounds, flattening, or external libraries.

    Solution overview

    A logistics company operates a mixed fleet of delivery vehicles: vans, electric bikes, and delivery robots. Each vehicle type produces telemetry events with a different sensor payload schema. The operations team needs to:

    1. Detect geofence violations: flag vehicles that enter restricted zones (airports, pedestrian areas, private property).
    2. Sequence events precisely: at fleet scale, many events land in the same microsecond window. Nanosecond timestamps give a deterministic order and prevent ties when sequencing or deduplicating events during processing.
    3. Extract metrics from heterogeneous payloads: query battery level from delivery robots, fuel level from vans, and pedal cadence from bikes, all stored in the same column.

    We address all three requirements with a single Iceberg v3 table on AWS Glue 6.0. The following data definition language (DDL) shows the table structure. The AWS Glue job we provision in subsequent steps executes this statement.

    CREATE TABLE fleet_monitoring_db.vehicle_telemetry (
    event_id STRING,
    vehicle_id STRING,
    vehicle_type STRING DEFAULT 'UNKNOWN',
    event_time TIMESTAMP_NTZ(9),
    location GEOMETRY(4326),
    service_area GEOGRAPHY(4326),
    sensor_payload VARIANT,
    speed_kmh DOUBLE DEFAULT 0.0,
    region STRING DEFAULT 'EMEA'
    ) USING ICEBERG
    TBLPROPERTIES (
    'format-version' = '3',
    'write.delete.mode' = 'merge-on-read'
    )
    PARTITIONED BY (days(event_time), vehicle_type)

    In the preceding statement, the database is shown as fleet_monitoring_db for readability. The deployed stack creates it as fleet_monitoring_<account-id>.

    The following list describes the key columns:

    • event_time TIMESTAMP_NTZ(9): Stores the event timestamp at nanosecond precision.
    • location GEOMETRY(4326): Stores GPS coordinates as native spatial objects using (SRID 4326). You can use predicates like ST_Intersects directly in SQL, replacing hand-coded spatial math on raw latitude/longitude doubles (WGS 84).
    • service_area GEOGRAPHY(4326): Stores geographic coordinates using a spherical (geodesic) model, distinct from GEOMETRY’s planar model. AWS Glue 6.0 writes and reads GEOGRAPHY in Iceberg v3, and the type is portable to any Iceberg v3-compatible engine. Geodesic spatial predicates over GEOGRAPHY are engine-dependent today. In this post we run spatial queries on the GEOMETRY location column, which Glue 6.0 supports natively.
    • sensor_payload VARIANT: Each vehicle type produces a different JSON schema. Vans report fuel and engine metrics, robots report battery and camera status, bikes report cadence and heart rate. All land in this single column without schema unions or separate tables using variant data type.
    • vehicle_type STRING DEFAULT ‘UNKNOWN’ and speed_kmh DOUBLE DEFAULT 0.0: When an ingestion writer omits these fields, Iceberg applies the declared defaults automatically. Useful when multiple producers write to the same table and not all of them populate every column.

    The table uses PARTITIONED BY (days(event_time), vehicle_type) so that analytical queries can prune by date range and vehicle type without scanning the full table. 'write.delete.mode' = 'merge-on-read' supports fast row-level corrections (for example, correcting a misreported GPS coordinate) through compact deletion vectors (Roaring Bitmaps) instead of accumulating positional delete files.

    In this post, we insert sample data directly to focus on the new Iceberg data types and how to use them together. In production, these events would stream from Amazon Managed Streaming for Apache Kafka (Amazon MSK) into an AWS Glue 6.0 streaming job.

    The following diagram illustrates the production architecture for reference:

    Architecture diagram showing a vehicle fleet of vans, delivery robots, and electric bikes sending telemetry through Amazon MSK into an AWS account. Within a VPC, a hot path uses AWS Glue 6.0 Spark Real-Time Mode to detect geofence violations and send alerts to a Kafka topic, while a cold path uses a Glue 6.0 micro-batch job to write events into an Apache Iceberg v3 table with GEOMETRY, TIMESTAMP_NTZ(9), VARIANT, and DEFAULT columns. Amazon S3 stores the Iceberg data and the AWS Glue Data Catalog holds metadata. A batch analytics Glue job reads the Iceberg table for geofence detection, nanosecond event sequencing, and per-vehicle-type metric extraction using variant_get

    Figure 1: Reference architecture for a fleet telemetry pipeline on AWS Glue 6.0

    The architecture processes vehicle telemetry through two paths, with a downstream batch analytics layer:

    Hot path (real-time, milliseconds): A Spark Real-Time Mode (RTM) job reads telemetry from Amazon MSK and evaluates geofence violations using spatial predicates like ST_Intersects, routing alerts to a downstream Kafka topic within milliseconds.

    Cold path (near-real-time, seconds): A micro-batch job reads the same MSK topic and writes events into an Iceberg v3 table, converting payloads to GEOMETRY, TIMESTAMP_NTZ(9), and VARIANT columns with DEFAULT values applied.

    Batch analytics: An AWS Glue job reads the Iceberg v3 table to run batch analytics on geofence detection, nanosecond event sequencing, and per-vehicle-type metric extraction.

    Prerequisites

    To follow along, you need:

    • An AWS account and an AWS Region where AWS Glue 6.0 is available.
    • An AWS Identity and Access Management (IAM) role with permissions to deploy AWS CloudFormation stacks and create resources including AWS Glue, Amazon Simple Storage Service (Amazon S3), and Amazon CloudWatch Logs.

    Deploy the CloudFormation stack

    We provide an AWS CloudFormation template that provisions all the resources needed for this walkthrough.

    The stack provisions the following resources:

    • An Amazon S3 bucket for Iceberg table storage.
    • An IAM role with permissions for AWS Glue, Amazon S3, and Amazon CloudWatch Logs.
    • An AWS Glue database (fleet_monitoring_<account-id>).
    • An AWS Glue job fleet-telemetry-ingest-<account-id> (PySpark): creates the Iceberg v3 table vehicle_telemetry described earlier and inserts sample telemetry from three vehicle types.
    • An AWS Glue job fleet-telemetry-queries-<account-id> (PySpark): demonstrates geofence detection, nanosecond sequencing, variant extraction, and default values.

    Deploy the CloudFormation stack:

    1. Download the CloudFormation template from the GitHub repository.
    2. Sign in to the AWS CloudFormation console.
    3. Choose Create stack, With new resources, Upload a template file, and upload the downloaded template.
    4. Acknowledge the IAM capabilities and choose Create stack.

    Stack creation takes approximately 2–5 minutes. No parameters are required.

    After the stack completes, navigate to the AWS Glue console and run the jobs in this order:

    1. Run fleet-telemetry-ingest-<account-id>. This job creates the Iceberg v3 table and inserts sample data (approximately 2 minutes).
    2. After it succeeds, run fleet-telemetry-queries-<account-id>. This job executes all demonstration queries (approximately 2 minutes).

    The following sections describe each job in detail.

    Job 1: Ingest sample telemetry data

    The ingestion job creates the Iceberg v3 table described earlier and inserts four sample telemetry events: one for each of the three vehicle types (van, robot, bike), plus one with omitted fields to demonstrate DEFAULT values. You can view the complete script in the GitHub repository. Note that the geospatial types require one additional Spark configuration (spark.sql.geospatial.enabled=true), which is already set in the job’s --conf argument by the CloudFormation template. All other types work with no extra configuration.

    The following are the key snippets from the script:

    Van telemetry: GPS coordinates with engine metrics and route information:

    spark.sql(f"""
    INSERT INTO {TABLE} VALUES (
    'EVT-001', 'VAN-042', 'VAN',
    CAST('2026-07-28 09:15:30.123456789' AS TIMESTAMP_NTZ(9)),
    ST_SetSrid(ST_GeomFromWKB(X'0101000000E17A14AE47E1C0BF1F85EB51B84E4940'), 4326),
    ST_SetSrid(ST_GeogFromWKB(X'0101000000E17A14AE47E1C0BF1F85EB51B84E4940'), 4326),
    PARSE_JSON('{{"fuel_pct": 0.72, "cargo_kg": 450, "door_open": false,
    "engine": {{"rpm": 2100, "temp_c": 88.5}},
    "route": {{"stops_remaining": 4, "eta_minutes": 35}}}}'),
    35.2, 'EMEA'
    )
    """)

    Delivery robot telemetry: Same table, completely different sensor schema (battery, cameras, navigation):

    spark.sql(f"""
    INSERT INTO {TABLE} VALUES (
    'EVT-002', 'ROB-117', 'ROBOT',
    CAST('2026-07-28 09:15:30.123456790' AS TIMESTAMP_NTZ(9)),
    ST_SetSrid(ST_GeomFromWKB(X'01010000000000000000001040000000000000F03F'), 4326),
    ST_SetSrid(ST_GeogFromWKB(X'01010000000000000000001040000000000000F03F'), 4326),
    PARSE_JSON('{{"battery_pct": 0.62, "obstacle_distance_m": 2.8,
    "navigation_mode": "autonomous",
    "cameras": {{"front": "active", "rear": "recording"}}}}'),
    48.0, 'EMEA'
    )
    """)

    Note: EVT-001 and EVT-002 are exactly 1 nanosecond apart (.123456789 vs .123456790). Without TIMESTAMP_NTZ(9), both would round to the same microsecond and be indistinguishable.

    Default values test: Event inserted with vehicle_type, speed_kmh, and region omitted:

    spark.sql(f"""
    INSERT INTO {TABLE}
    (event_id, vehicle_id, event_time, location, service_area, sensor_payload)
    VALUES (
    'EVT-004', 'UNK-999',
    CAST('2026-07-28 10:00:00.000000000' AS TIMESTAMP_NTZ(9)),
    ST_SetSrid(ST_GeomFromWKB(X'0101000000000000000000F03F000000000000F03F'), 4326),
    ST_SetSrid(ST_GeogFromWKB(X'0101000000000000000000F03F000000000000F03F'), 4326),
    PARSE_JSON('{{"status": "initializing"}}')
    )
    """)

    The omitted columns automatically receive their DEFAULT values: vehicle_type = 'UNKNOWN', speed_kmh = 0.0, region = 'EMEA'.

    Job 2: Query the data

    The query job demonstrates all four data types working together. After the job succeeds, select the run in the AWS Glue console and choose Output logs to see the results.

    The following sections walk through the key queries from the job and the results of each.

    Geofence detection with ST_Intersects

    The job defines a polygon and finds all vehicles inside it:

    POLY = "010300...."
    SELECT event_id, vehicle_id, vehicle_type, speed_kmh
    FROM fleet_monitoring_db.vehicle_telemetry
    WHERE ST_Intersects(
    location,ST_SetSrid(ST_GeomFromWKB(X'{POLY}'), 4326)
    )
    ORDER BY event_id

    The polygon covers coordinates (0,0)-(5,0)-(5,2)-(0,2). Three vehicles are inside (ROBOT at (4,1), BIKE at (3,1), UNKNOWN at (1,1)). The VAN at (-0.1278, 51.5074) is outside.

    Query results listing the ROBOT, BIKE, and UNKNOWN vehicles inside the geofence polygon, with the VAN excluded

    Figure 2: Geofence query results showing the three vehicles inside the polygon

    Nanosecond event sequencing

    Order events by their sub-microsecond timestamps:

    SELECT event_id, vehicle_id, CAST(event_time AS STRING) AS precise_time
    FROM fleet_monitoring_db.vehicle_telemetry
    WHERE event_id IN ('EVT-001', 'EVT-002', 'EVT-003')
    ORDER BY event_time ASC

    EVT-001 and EVT-002 are correctly distinguished and ordered despite being only 1 nanosecond apart. With standard TIMESTAMP_NTZ (microsecond precision), both would show .123456 and their relative order would be undefined.

    Query results showing EVT-001 and EVT-002 ordered by nanosecond-precision timestamps one nanosecond apart

    Figure 3: Nanosecond-precision ordering distinguishing two events one nanosecond apart

    Variant extraction with variant_get

    Different sensor schemas per vehicle type, all extracted with variant_get:

    SELECT vehicle_id, vehicle_type,
    CASE vehicle_type
    WHEN 'VAN' THEN variant_get(sensor_payload, '$.fuel_pct', 'DOUBLE')
    WHEN 'ROBOT' THEN variant_get(sensor_payload, '$.battery_pct', 'DOUBLE')
    WHEN 'BIKE' THEN variant_get(sensor_payload, '$.battery_pct', 'DOUBLE')
    ELSE NULL
    END AS energy_level,
    variant_get(sensor_payload, '$.engine.temp_c', 'DOUBLE') AS engine_temp,
    variant_get(sensor_payload, '$.cameras.front', 'STRING') AS front_cam,
    variant_get(sensor_payload, '$.deliveries.completed', 'INT') AS deliveries_done
    FROM fleet_monitoring_db.vehicle_telemetry
    WHERE vehicle_type != 'UNKNOWN'
    ORDER BY vehicle_id
    Query results showing variant_get extracting energy level, engine temperature, and camera status for each vehicle type

    Figure 4: Variant extraction returning typed values from heterogeneous sensor payloads

    variant_get takes three arguments: the column, a dot-path expression, and the expected return type. It supports arbitrary nesting depth. $.engine.temp_c reaches two levels deep, $.deliveries.completed reaches into a different structure entirely. When a path doesn’t exist in a particular row’s payload, it returns NULL.

    Default values

    Confirm that omitted columns received their defaults:

    SELECT event_id, vehicle_type, speed_kmh, region
    FROM fleet_monitoring_db.vehicle_telemetry
    WHERE event_id = 'EVT-004'
    Query results showing event EVT-004 with the default values UNKNOWN, 0.0, and EMEA applied

    Figure 5: Default column values applied to the event inserted with omitted fields

    EVT-004 was inserted without vehicle_type, speed_kmh, or region. The declared defaults were applied automatically.

    Combined query: Combining spatial, temporal, and variant operations

    The following query runs a geospatial predicate, nanosecond ordering, and variant extraction in a single SELECT statement:

    SELECT vehicle_id, vehicle_type,
    CAST(event_time AS STRING) AS precise_time,
    CASE vehicle_type
    WHEN 'VAN' THEN variant_get(sensor_payload, '$.fuel_pct', 'DOUBLE')
    WHEN 'ROBOT' THEN variant_get(sensor_payload, '$.battery_pct', 'DOUBLE')
    WHEN 'BIKE' THEN variant_get(sensor_payload, '$.battery_pct', 'DOUBLE')
    ELSE NULL
    END AS energy_level,
    speed_kmh
    FROM fleet_monitoring_db.vehicle_telemetry
    WHERE ST_Intersects(location, ST_SetSrid(ST_GeomFromWKB(X'0103000000...'), 4326))
    ORDER BY event_time ASC
    Query results combining spatial filtering, nanosecond ordering, and variant extraction in a single query

    Figure 6: Combined query results over a single Iceberg v3 table

    This single query combines a spatial predicate, nanosecond ordering, and variant extraction over one table, with no external libraries, pre-processing, or joins to separate geometry or payload tables.

    Clean up

    To avoid ongoing charges from the AWS Glue jobs and Amazon S3 storage, delete the CloudFormation stack when you’re done:

    1. Open the AWS CloudFormation console.
    2. Select the stack you deployed earlier and choose Delete.

    Conclusion

    In this post, we stored and analyzed geospatial coordinates, nanosecond timestamps, and heterogeneous sensor payloads in a single Iceberg v3 table on AWS Glue 6.0, with sensible defaults applied automatically, no external libraries, and no schema flattening.

    • GEOMETRY columns replace latitude/longitude doubles and support native spatial predicates like ST_Intersects for geofence detection. GEOGRAPHY is stored natively.
    • TIMESTAMP_NTZ(9) preserves full nanosecond precision for event sequencing where microsecond resolution is insufficient.
    • VARIANT stores heterogeneous payloads (different schema per vehicle type) in one column with typed extraction through variant_get.
    • DEFAULT values keep field population consistent across multiple ingestion writers without duplicating logic.

    All capabilities require Iceberg format-version 3. Geospatial requires one additional configuration (spark.sql.geospatial.enabled=true). Nanosecond timestamps, Variant, and DEFAULT values work with no extra configuration.

    These capabilities apply wherever schemas vary by source (IoT fleets, multi-tenant software as a service (SaaS), event-driven architectures), timestamps need sub-microsecond precision (trading, sensor fusion, autonomous systems), or spatial operations replace coordinate workarounds (logistics, real estate, delivery networks).

    For more information, see the AWS launch announcement (launch URL to be added before publishing), the AWS Glue documentation, and the Apache Iceberg v3 specification. AWS Glue 6.0 includes additional capabilities such as Spark Real-Time Mode and Spark Declarative Pipelines, which we cover in separate posts.


    About the authors

    Shoukat Ghouse

    Shoukat Ghouse

    Shoukat is a Senior Specialist Solutions Architect for Big Data, Analytics, and Data Governance at Amazon Web Services (AWS). He partners with enterprise and financial services customers across EMEA to design and scale production-grade data lakehouse platforms on Apache Spark, Apache Iceberg, AWS Glue, Amazon EMR, and Amazon SageMaker Unified Studio. His focus spans distributed data processing, fine-grained data governance, and helping organizations build AI-ready data foundations that power analytics and machine learning at scale.

    Shrey Malpani

    Shrey Malpani

    Shrey is a Senior Product Manager Technical at Amazon Web Services (AWS), where he works at the intersection of distributed data processing and data integration. He is focused on building and scaling data integration and data management capabilities across services like AWS Glue, Amazon EMR, and Amazon Redshift that help customers build AI-ready data platforms for their analytics and machine learning workflows.

    Kartik

    Kartik

    Kartik is a Software Development Manager on the AWS Glue team. His team builds generative AI features for the Data Integration and distributed system for data integration.

    Creating and testing an End User Messaging RCS agent with AWS CLI

    Post Syndicated from Bruno Giorgini original https://aws.amazon.com/blogs/messaging-and-targeting/creating-and-testing-an-end-user-messaging-rcs-agent-with-aws-cli/

    A step-by-step walkthrough for setting up a Rich Communication Services (RCS) test agent, from brand assets to verified inbound messaging.

    If you’re still sending plain SMS, you’re leaving a significant experience gap on the table. SMS gives you 160 characters of unformatted text, no branding, and zero confirmation that your message was even read. Rich Communication Services (RCS) changes that entirely. It delivers branded carousels, read receipts, typing indicators, high-resolution images, and verified sender identity, all through the native messaging app your customers already use. No app download required, no new account to create.

    Compared to over-the-top (OTT) platforms like WhatsApp or iMessage for Business, RCS doesn’t fragment your audience. It works on an Android’s default messaging app with RCS enabled or an iPhone on iOS 18 or later, which means you reach users where they already are. You are not limited to the ones who happen to have a specific app installed. And compared to building a custom in-app messaging experience, RCS requires no SDK, no UI work, and no convincing users to enable notifications.

    With AWS End User Messaging, standing up an RCS agent is surprisingly fast. You configure your brand assets, submit a registration, and within minutes you have a test agent sending branded messages through production APIs. This is real infrastructure, not a sandbox. That means you can prototype, validate your integration, and show stakeholders a working demo before committing to a full build.

    This post walks through the entire process of creating an RCS test agent using only the AWS Command Line Interface (AWS CLI). Using the CLI means every step is a repeatable, scriptable command. Need to spin up another agent in a different account or Region? Run the same script and you’re done in minutes. By the end, you will have a working agent that can send branded messages to verified testers and receive inbound messages with automatic responses.

    What you will build

    In this walkthrough, you will:

    1. Create an RCS agent and configure its brand identity (logo, banner, accent color).
    2. Submit a test registration for automated approval.
    3. Add a verified tester device.
    4. Send your first branded RCS message.
    5. Configure and verify inbound messaging with an automatic keyword response.

    Prerequisites

    Before you begin, confirm you have:

    • An AWS account with access to AWS End User Messaging (Amazon Pinpoint SMS and Voice v2 API)
    • AWS CLI v2.35.12 or later installed and configured with credentials that have pinpoint-sms-voice-v2:* permissions. Version 2.35.12 adds the send-rcs-message command, which you will need for rich media messages (rich cards, carousels, and suggestion chips) beyond this walkthrough. For production deployments, scope the IAM policy down to only the specific actions your application requires. The pinpoint-sms-voice-v2:* scope is convenient for testing but broader than necessary.
    • rsvg-convert for generating brand asset images from SVG (install with brew install librsvg on macOS)
    • A test phone that supports RCS messaging.

    Verify your setup:

    # Confirm AWS credentials are working
    aws sts get-caller-identity
    # Verify EUM access
    aws pinpoint-sms-voice-v2 describe-spend-limits --region us-east-1
    # Confirm rsvg-convert is installed
    which rsvg-convert

    If you use a named AWS CLI profile, append --profile <your-profile> to every AWS command in this walkthrough.

    Step 1: Create the RCS agent

    The first step is to create an empty RCS agent container. The agent’s display name and branding come from the registration you will configure in Step 2.

    aws pinpoint-sms-voice-v2 create-rcs-agent \
      --region us-east-1

    Expected output:

    {
      "RcsAgentArn": "arn:aws:sms-voice:us-east-1:123456789012:rcs-agent/rcs-a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4",
      "RcsAgentId": "rcs-a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4",
      "Status": "CREATED",
      "DeletionProtectionEnabled": false,
      "CreatedTimestamp": "2026-07-15T10:00:01.000000-07:00"
    }

    Save the RcsAgentId and RcsAgentArn values. You will use them throughout this walkthrough.

    Next, enable deletion protection to prevent accidental removal. This is especially important once carrier approvals are in place, since re-creating an agent requires a new registration and approval cycle:

    aws pinpoint-sms-voice-v2 update-rcs-agent \
      --rcs-agent-id rcs-a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4 \
      --deletion-protection-enabled \
      --region us-east-1

    Step 2: Generate brand assets

    Your RCS agent needs a logo (224×224 px, must be under 50 KB as PNG) and a banner (1440×448 px, must be under 200 KB as PNG). Both must be JPEG or PNG format. You can use your own designs as long as they meet these dimension and size requirements. In this example, we generate them as SVGs and convert to PNG.

    Create the logo SVG

    Create a file named brand-assets/logo.svg:

    <svg xmlns="http://www.w3.org/2000/svg" width="224" height="224" viewBox="0 0 224 224"><defs><linearGradient id="bg" x1="0%" y1="0%" x2="100%" y2="100%"><stop offset="0%" style="stop-color:#0D47A1"/><stop offset="100%" style="stop-color:#1565C0"/></linearGradient></defs><rect width="224" height="224" rx="40" fill="url(#bg)"/><g transform="translate(112,90)"><path d="M-48,-36 L48,-36 C54,-36 58,-32 58,-26 L58,16 C58,22 54,26 48,26             L10,26 L0,42 L-10,26 L-48,26 C-54,26 -58,22 -58,16 L-58,-26             C-58,-32 -54,-36 -48,-36 Z" fill="white" opacity="0.95"/><path d="M-20,-12 C-14,-20 14,-20 20,-12" stroke="#0D47A1" stroke-width="4" fill="none" stroke-linecap="round"/><path d="M-14,-2 C-9,-8 9,-8 14,-2" stroke="#0D47A1" stroke-width="4" fill="none" stroke-linecap="round"/><circle cx="0" cy="6" r="4" fill="#0D47A1"/></g><text x="112" y="168" text-anchor="middle" font-family="Arial, Helvetica, sans-serif" font-size="16" font-weight="bold" fill="white">AWS EUM</text><text x="112" y="188" text-anchor="middle" font-family="Arial, Helvetica, sans-serif" font-size="12" fill="white" opacity="0.85">DEMO</text></svg>

    Create the banner SVG

    Create a file named brand-assets/banner.svg:

    <svg xmlns="http://www.w3.org/2000/svg" width="1440" height="448" viewBox="0 0 1440 448"><defs><linearGradient id="bannerBg" x1="0%" y1="0%" x2="100%" y2="100%"><stop offset="0%" style="stop-color:#0D47A1"/><stop offset="50%" style="stop-color:#1565C0"/><stop offset="100%" style="stop-color:#0D47A1"/></linearGradient></defs><rect width="1440" height="448" fill="url(#bannerBg)"/><circle cx="200" cy="224" r="300" fill="white" opacity="0.03"/><circle cx="1300" cy="100" r="250" fill="white" opacity="0.04"/><text x="720" y="190" text-anchor="middle" font-family="Arial, Helvetica, sans-serif" font-size="56" font-weight="bold" fill="white">    AWS End User Messaging  </text><text x="720" y="250" text-anchor="middle" font-family="Arial, Helvetica, sans-serif" font-size="48" font-weight="bold" fill="white" opacity="0.9">    Demo  </text><text x="720" y="320" text-anchor="middle" font-family="Arial, Helvetica, sans-serif" font-size="24" fill="white" opacity="0.7">    Rich messaging experiences, powered by AWS  </text></svg>

    Convert to PNG

    rsvg-convert -w 224 -h 224 brand-assets/logo.svg -o brand-assets/logo.png
    rsvg-convert -w 1440 -h 448 brand-assets/banner.svg -o brand-assets/banner.png

    Verify the file sizes. The logo must be under 50 KB and the banner under 200 KB:

    ls -la brand-assets/*.png
    # logo.png   ~9 KB
    # banner.png ~79 KB

    Step 3: Create and configure the registration

    RCS agents require a registration that contains all brand details. For testing, use the TEST_RCS_LAUNCH_REGISTRATION type.

    Create the registration

    aws pinpoint-sms-voice-v2 create-registration \
      --registration-type TEST_RCS_LAUNCH_REGISTRATION \
      --region us-east-1

    Expected output:

    {
      "RegistrationId": "registration-a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4",
      "RegistrationType": "TEST_RCS_LAUNCH_REGISTRATION",
      "RegistrationStatus": "CREATED",
      "CurrentVersionNumber": 1
    }

    Save the RegistrationId.

    aws pinpoint-sms-voice-v2 create-registration-association \
      --registration-id registration-a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4 \
      --resource-id rcs-a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4 \
      --region us-east-1

    Upload brand assets

    Upload the logo and banner as registration attachments. Note that --attachment-body and --attachment-url cannot be used together. Use --attachment-body with the fileb:// prefix:

    # Upload logo
    aws pinpoint-sms-voice-v2 create-registration-attachment \
      --attachment-body fileb://brand-assets/logo.png \
      --region us-east-1
    # Save: RegistrationAttachmentId (e.g., attachment-1111aaaa2222bbbb3333cccc4444dddd)
    # Upload banner
    aws pinpoint-sms-voice-v2 create-registration-attachment \
      --attachment-body fileb://brand-assets/banner.png \
      --region us-east-1
    # Save: RegistrationAttachmentId (e.g., attachment-5555eeee6666ffff7777aaaa8888bbbb)

    Set registration fields

    The registration has 23 fields. Each field has a specific type that determines which CLI parameter to use:

    Field type CLI parameter Example
    TEXT --text-value --text-value "My Brand"
    SELECT --select-choices --select-choices "MULTI_USE"
    ATTACHMENT --registration-attachment-id --registration-attachment-id "attachment-abc123"

    Do not use --field-values. That parameter does not exist in this CLI.

    Set all the TEXT fields:

    REG_ID="registration-a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4"
    REGION="us-east-1"
    
    aws pinpoint-sms-voice-v2 put-registration-field-value \
      --registration-id $REG_ID \
      --field-path "agentDetails.brandName" \
      --text-value "AWS End User Messaging Demo" \
      --region $REGION
    
    aws pinpoint-sms-voice-v2 put-registration-field-value \
      --registration-id $REG_ID \
      --field-path "agentDetails.senderDisplayName" \
      --text-value "AWS End User Messaging Demo" \
      --region $REGION
    
    aws pinpoint-sms-voice-v2 put-registration-field-value \
      --registration-id $REG_ID \
      --field-path "agentDetails.agentDescription" \
      --text-value "Experience the power of rich messaging with AWS End User Messaging" \
      --region $REGION
    
    aws pinpoint-sms-voice-v2 put-registration-field-value \
      --registration-id $REG_ID \
      --field-path "agentDetails.accentColor" \
      --text-value "#0D47A1" \
      --region $REGION
    
    aws pinpoint-sms-voice-v2 put-registration-field-value \
      --registration-id $REG_ID \
      --field-path "agentDetails.contactPhoneNumber" \
      --text-value "+12065550100" \
      --region $REGION
    
    aws pinpoint-sms-voice-v2 put-registration-field-value \
      --registration-id $REG_ID \
      --field-path "agentDetails.contactPhoneLabel" \
      --text-value "Call Us" \
      --region $REGION
    
    aws pinpoint-sms-voice-v2 put-registration-field-value \
      --registration-id $REG_ID \
      --field-path "agentDetails.contactEmailAddress" \
      --text-value "[email protected]" \
      --region $REGION
    
    aws pinpoint-sms-voice-v2 put-registration-field-value \
      --registration-id $REG_ID \
      --field-path "agentDetails.contactEmailLabel" \
      --text-value "Email Us" \
      --region $REGION
    
    aws pinpoint-sms-voice-v2 put-registration-field-value \
      --registration-id $REG_ID \
      --field-path "agentDetails.contactWebsite" \
      --text-value "https://www.example.com" \
      --region $REGION
    
    aws pinpoint-sms-voice-v2 put-registration-field-value \
      --registration-id $REG_ID \
      --field-path "agentDetails.contactWebsiteLabel" \
      --text-value "Visit Website" \
      --region $REGION
    
    aws pinpoint-sms-voice-v2 put-registration-field-value \
      --registration-id $REG_ID \
      --field-path "agentDetails.privacyPolicyUrl" \
      --text-value "https://www.example.com/privacy" \
      --region $REGION
    
    aws pinpoint-sms-voice-v2 put-registration-field-value \
      --registration-id $REG_ID \
      --field-path "agentDetails.privacyPolicyLabel" \
      --text-value "Privacy Policy" \
      --region $REGION
    
    aws pinpoint-sms-voice-v2 put-registration-field-value \
      --registration-id $REG_ID \
      --field-path "agentDetails.termsAndConditionsUrl" \
      --text-value "https://www.example.com/terms" \
      --region $REGION
    
    aws pinpoint-sms-voice-v2 put-registration-field-value \
      --registration-id $REG_ID \
      --field-path "agentDetails.termsAndConditionsLabel" \
      --text-value "Terms and Conditions" \
      --region $REGION
    
    aws pinpoint-sms-voice-v2 put-registration-field-value \
      --registration-id $REG_ID \
      --field-path "agentDetails.serviceName" \
      --text-value "AWS End User Messaging Demo RCS Agent" \
      --region $REGION
    
    aws pinpoint-sms-voice-v2 put-registration-field-value \
      --registration-id $REG_ID \
      --field-path "agentDetails.monthlyRcsVolume" \
      --text-value "1000" \
      --region $REGION
    
    aws pinpoint-sms-voice-v2 put-registration-field-value \
      --registration-id $REG_ID \
      --field-path "complianceKeywords.helpResponse" \
      --text-value "Reply STOP to opt out. For help, contact [email protected]" \
      --region $REGION
    
    aws pinpoint-sms-voice-v2 put-registration-field-value \
      --registration-id $REG_ID \
      --field-path "complianceKeywords.stopResponse" \
      --text-value "You have been unsubscribed. No more messages will be sent." \
      --region $REGION

    Set the SELECT fields. These use --select-choices instead of --text-value:

    aws pinpoint-sms-voice-v2 put-registration-field-value \
      --registration-id $REG_ID \
      --field-path "agentDetails.useCase" \
      --select-choices "MULTI_USE" \
      --region $REGION
    
    aws pinpoint-sms-voice-v2 put-registration-field-value \
      --registration-id $REG_ID \
      --field-path "agentDetails.billingCategory" \
      --select-choices "CONVERSATIONAL" \
      --region $REGION
    
    aws pinpoint-sms-voice-v2 put-registration-field-value \
      --registration-id $REG_ID \
      --field-path "agentDetails.averageMonthlyRcsFrequency" \
      --select-choices "10" \
      --region $REGION

    Set the ATTACHMENT fields. These use --registration-attachment-id:

    aws pinpoint-sms-voice-v2 put-registration-field-value \
      --registration-id $REG_ID \
      --field-path "agentDetails.logoImage" \
      --registration-attachment-id "attachment-1111aaaa2222bbbb3333cccc4444dddd" \
      --region $REGION
    
    aws pinpoint-sms-voice-v2 put-registration-field-value \
      --registration-id $REG_ID \
      --field-path "agentDetails.bannerImage" \
      --registration-attachment-id "attachment-5555eeee6666ffff7777aaaa8888bbbb" \
      --region $REGION

    A note on accent color

    The accent color must meet a 4.5:1 contrast ratio against white. This is the WCAG AA accessibility standard, enforced to make sure the text is readable for users with visual impairments. Colors with an HSL lightness value above ~45% will typically fail this threshold and be rejected with ACCENT_COLOR_CONTRAST_INSUFFICIENT. Safe choices include #0D47A1 (blue), #1B5E20 (green), #BF360C (orange), #B71C1C (red), and #4A148C (purple). If you are using a custom brand color, verify it passes before submitting using the WebAIM Contrast Checker.

    Submit the registration

    aws pinpoint-sms-voice-v2 submit-registration-version \
      --registration-id $REG_ID \
      --region $REGION

    Expected output:

    {
      "RegistrationId": "registration-a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4",
      "VersionNumber": 1,
      "RegistrationVersionStatus": "SUBMITTED"
    }

    Step 4: Wait for approval

    Poll the registration and agent status. Test registrations typically complete within a few minutes.

    # Check registration status
    aws pinpoint-sms-voice-v2 describe-registrations \
      --registration-ids $REG_ID \
      --query 'Registrations[0].{Status:RegistrationStatus,Version:CurrentVersionNumber}' \
      --region $REGION
    
    # Check agent status
    aws pinpoint-sms-voice-v2 describe-rcs-agents \
      --query "RcsAgents[?RcsAgentId=='rcs-a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4'].{Status:Status,TestingStatus:TestingAgent.Status}" \
      --region $REGION

    You will see the status progress through these stages:

    Registration status Agent status Testing status Meaning
    SUBMITTED PENDING PENDING Under review
    REVIEWING PENDING PENDING Automated checks in progress
    COMPLETE TESTING ACTIVE Ready to use

    Wait until TestingAgent.Status shows ACTIVE before proceeding.

    NOTE: If the registration returns REQUIRES_UPDATES, run describe-registration-field-values to find fields with a DeniedReason. Create a new registration version with create-registration-version, re-populate all 23 fields (new versions do not inherit values), fix the issue, and re-submit.

    Step 5: Add a verified tester

    Wait at least 120 seconds after agent creation before adding testers. Then register your test device:

    aws pinpoint-sms-voice-v2 create-verified-destination-number \
      --destination-phone-number +12065550199 \
      --rcs-agent-id rcs-a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4 \
      --region $REGION

    You will receive a tester invitation on your phone within 2 to 20 minutes from “RBM Tester Management.” On iPhone, check the Unknown Senders folder. Tap “Make me a tester” to accept.

    After accepting, verify the status:

    aws pinpoint-sms-voice-v2 describe-verified-destination-numbers \
      --filters Name=rcs-agent-id,Values=rcs-a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4 \
      --region $REGION \
      --query 'VerifiedDestinationNumbers[].{Phone:DestinationPhoneNumber,Status:Status}'

    Expected output once accepted:

    [
      {
        "Phone": "+12065550199",
        "Status": "VERIFIED"
      }
    ]

    Step 6: Send your first RCS message

    Before sending, check for potential blockers.

    Check the protect configuration

    Verify that the US is not blocked in your account’s default protect configuration:

    # List protect configurations
    aws pinpoint-sms-voice-v2 describe-protect-configurations --region $REGION
    
    # Check US status on the default (account-default) protect configuration
    aws pinpoint-sms-voice-v2 get-protect-configuration-country-rule-set \
      --protect-configuration-id <your-protect-config-id> \
      --number-capability SMS \
      --query 'CountryRuleSet.US' \
      --region $REGION

    If the US status is BLOCK, update it to ALLOW:

    aws pinpoint-sms-voice-v2 update-protect-configuration-country-rule-set \
      --protect-configuration-id <your-protect-config-id> \
      --country-rule-set-updates '{"US":{"ProtectStatus":"ALLOW"}}' \
      --number-capability SMS \
      --region $REGION

    Check the opt-out list

    aws pinpoint-sms-voice-v2 describe-opted-out-numbers \
      --opt-out-list-name Default \
      --region $REGION

    If your test number appears in the list, remove it:

    aws pinpoint-sms-voice-v2 delete-opted-out-number \
      --opt-out-list-name Default \
      --opted-out-number +12065550199 \
      --region $REGION

    Now, send the test message:

    aws pinpoint-sms-voice-v2 send-text-message \
      --destination-phone-number +12065550199 \
      --origination-identity rcs-a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4 \
      --message-body "Hello from AWS End User Messaging Demo! This is your first RCS test message." \
      --message-type TRANSACTIONAL \
      --region $REGION

    Expected output:

    {"MessageId": "a1b2c3d4-e5f6-7890-abcd-ef1234567890"}

    Check your phone. You should see a branded message from your agent with the logo and accent color you configured. On iPhone, check the Unknown Senders folder.

    Step 7: Configure and test inbound messaging

    With inbound messaging, your agent can respond to messages that testers send back. Configure an automatic keyword response, then verify it end to end.

    Set up an automatic keyword response

    The put-keyword API configures an automatic reply when someone sends a specific keyword to your agent. With it, you can verify inbound messaging without writing any backend code:

    aws pinpoint-sms-voice-v2 put-keyword \
      --keyword RCSINBOUNDTESTING \
      --keyword-action AUTOMATIC_RESPONSE \
      --keyword-message "Inbound test successful! Your message was received." \
      --origination-identity rcs-a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4 \
      --region $REGION

    Test inbound messaging

    While the previous steps used the CLI exclusively, the inbound testing deep link is most easily accessed through the console. Navigate to your agent and use the Testing tab to generate the deep link:

    1. Open the AWS End User Messaging console: https://console.aws.amazon.com/sms-voice/home?region=[REGION]#/rcs-agents.
    2. Select your agent and choose the Testing tab.
    3. Choose Inbound deep link.
    4. Enter RCSINBOUNDTESTING in the message body field.
    5. Choose Generate link.
    6. Scan the QR code with your test phone. The message is pre-filled.
    7. Send the message.

    You should receive the automatic response: “Inbound test successful! Your message was received.”

    Clean up

    To avoid unexpected charges, remove the resources created during this walkthrough when you are finished testing. You must delete resources in the following order. Attempting to delete the agent before its registration results in a ConflictException: RESOURCE_NOT_EMPTY error.

    # 1. Remove the keyword
    aws pinpoint-sms-voice-v2 delete-keyword \
      --keyword RCSINBOUNDTESTING \
      --origination-identity rcs-a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4 \
      --region $REGION
    
    # 2. Remove verified tester
    aws pinpoint-sms-voice-v2 delete-verified-destination-number \
      --verified-destination-number-id <your-verified-number-id> \
      --region $REGION
    
    # 3. Disable deletion protection
    aws pinpoint-sms-voice-v2 update-rcs-agent \
      --rcs-agent-id rcs-a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4 \
      --no-deletion-protection-enabled \
      --region $REGION
    
    # 4. Delete the registration
    aws pinpoint-sms-voice-v2 delete-registration \
      --registration-id registration-a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4 \
      --region $REGION
    
    # 5. Delete the agent
    aws pinpoint-sms-voice-v2 delete-rcs-agent \
      --rcs-agent-id rcs-a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4 \
      --region $REGION

    If you modified the protect configuration (changed US from BLOCK to ALLOW), revert it to its original state if your account does not need US messaging enabled.

    Summary

    You now have a working RCS test agent that can send and receive branded messages. Here is a recap of the resources created:

    Resource Value
    Agent ID rcs-a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4
    Registration ID registration-a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4
    Region us-east-1
    Console https://us-east-1.console.aws.amazon.com/sms-voice/home?region=us-east-1#/rcs-agents

    Registration field reference

    For reference, here is the complete list of registration fields and their types:

    Field Type Requirement
    agentDetails.brandName TEXT Required
    agentDetails.serviceName TEXT Required
    agentDetails.senderDisplayName TEXT Required
    agentDetails.useCase SELECT Required
    agentDetails.agentDescription TEXT Required
    agentDetails.bannerImage ATTACHMENT Required
    agentDetails.logoImage ATTACHMENT Required
    agentDetails.accentColor TEXT Required
    agentDetails.contactPhoneNumber TEXT Conditional
    agentDetails.contactPhoneLabel TEXT Conditional
    agentDetails.contactEmailAddress TEXT Conditional
    agentDetails.contactEmailLabel TEXT Conditional
    agentDetails.contactWebsite TEXT Conditional
    agentDetails.contactWebsiteLabel TEXT Conditional
    agentDetails.privacyPolicyUrl TEXT Required
    agentDetails.privacyPolicyLabel TEXT Optional
    agentDetails.termsAndConditionsUrl TEXT Required
    agentDetails.termsAndConditionsLabel TEXT Optional
    agentDetails.averageMonthlyRcsFrequency SELECT Required
    agentDetails.billingCategory SELECT Required
    agentDetails.monthlyRcsVolume TEXT Required
    complianceKeywords.helpResponse TEXT Conditional
    complianceKeywords.stopResponse TEXT Conditional

    Troubleshooting

    Error Resolution
    ACCENT_COLOR_CONTRAST_INSUFFICIENT Use a darker accent color with 4.5:1 contrast ratio against white. Create a new registration version and re-populate all fields.
    DESTINATION_COUNTRY_BLOCKED_BY_PROTECT_CONFIGURATION Update the protect configuration to set the US to ALLOW for SMS capability.
    DESTINATION_PHONE_NUMBER_OPTED_OUT Remove the number from the Default opt-out list with delete-opted-out-number.
    Registration REQUIRES_UPDATES Run describe-registration-field-values to find fields with DeniedReason. Create a new version, re-populate all 23 fields, fix the issue, and re-submit.
    No tester invitation received Wait up to 20 minutes. Check the Unknown Senders folder on iPhone. Verify the agent status is ACTIVE.
    Message delivered as SMS instead of RCS Confirm the agent is ACTIVE, the device supports RCS, and you used the correct origination identity.

    Next steps

    With your test agent running, you can explore richer message types such as cards and carousels, set up event destinations for programmatic inbound message handling, or add more verified testers. For production use, submit a full launch registration instead of a test registration.

    For an overview of the business case for RCS and implementation strategy, see Upgrade business messaging with RCS on AWS. For sample code and scripts that automate this walkthrough, see the sample-rcs-agent-setup-and-send-messages repository on GitHub. For more information, see the AWS End User Messaging service page and the RCS documentation.


    About the authors

    Detecting multi-stage attacks on AWS: A guide to cross-service signal correlation

    Post Syndicated from Nisha Kashyap original https://aws.amazon.com/blogs/security/detecting-multi-stage-attacks-on-aws-a-guide-to-cross-service-signal-correlation/

    A single alert from one security service tells you something happened. Read that signal alongside activity from other services and your own business context, and you will know whether what happened is part of a multi-stage attack.

    Consider a short sequence. An identity calls GetCallerIdentity from a source address it hasn’t previously used. Within minutes, that same identity runs a burst of List and Describe calls across several services, and some of them fail with AccessDenied. Soon after, a large volume of data leaves your environment toward a domain that was registered last week. Amazon GuardDuty might already flag pieces of this, such as the reconnaissance from an unfamiliar source, through finding types like Recon:IAMUser/* or Discovery:S3/*. What you gain from correlating the pieces yourself is a single view of the sequence, tied to your own business context, so you can act on the whole rather than triaging findings one at a time.

    This post is for security engineers and security operations teams who run Amazon Web Services (AWS) detection services and want to catch patterns specific to their environment. You will see how AWS detection and your business context fit together, and how to build correlations that use that context. The examples run in Amazon CloudWatch Logs Insights so you can try them today, and the closing section describes how to grow them into an automated pipeline. The walkthrough later in this post lists the prerequisites for these queries.

    Start with AWS detection services

    Begin with the AWS detection services. They cover the threats common across customers, and everything in this post is built on them.

    Turn these on and tune them before you build anything custom. Tuning means adjusting sensitivity to reduce false positives for your environment, choosing which data sources each service monitors, and suppressing findings for known-good patterns.

    GuardDuty correlates multi-stage attacks for you

    Before you build anything by hand, see what GuardDuty already does for you. Amazon GuardDuty Extended Threat Detection correlates signals across multiple data sources including AWS CloudTrail, Amazon S3 data events, runtime monitoring, Amazon Elastic Kubernetes Service (Amazon EKS) audit logs, and more, then raises a single critical severity attack sequence finding when it spots a multi-stage pattern. It recognizes sequences such as credential compromise followed by data exfiltration, maps them to MITRE ATT&CK tactics, and attaches a timeline and remediation guidance. If you have GuardDuty enabled today, then GuardDuty Extended Threat Detection is already enabled by default and needs no queries from you. For details on how GuardDuty charges apply, see Amazon GuardDuty pricing.

    The credential compromise sequence in the opening example is the kind of universal pattern GuardDuty Extended Threat Detection is built to catch, so rely on it for those. Attack sequence findings show up in the GuardDuty console next to your other findings, and they route to Security Hub and your response workflows the same way.

    GuardDuty handles the threats that look the same in every account. What it doesn’t have is the context that makes a given action suspicious in your account. That’s what you provide.

    Add your business context

    Business context is what only you know about your environment: which buckets hold sensitive data, which principals have a reason to touch which resources, which role chains your policy permits, and when your production change windows open. GuardDuty Extended Threat Detection learns from patterns common across customers, but it can’t answer these environment-specific questions. Express them as correlations and you add a detection layer tuned to your environment. Each of the following four patterns turns one of these facts into a query.

    Run these queries in the AWS Management Console for CloudWatch by choosing Logs, then Logs Insights, using the CloudWatch Logs Insights query language. Most read CloudTrail events from a CloudWatch Logs log group that your trail delivers to. If your trail writes only to Amazon S3, add CloudWatch Logs delivery on the trail, or run equivalent queries in Amazon Athena (a serverless query service for analyzing data in Amazon S3 using SQL).

    Note: The queries and code in this post use placeholder values. Replace them with your own before running: your-sensitive-bucket (your S3 bucket name), your-key-id (your AWS KMS key ID), region (your AWS Region, such as us-east-1), account-id (your 12-digit AWS account ID), and aws-cloudtrail-logs-my-trail (your CloudTrail log group name).

    A note on multi-account environments. In AWS Organizations, an organization trail delivers every account’s events to one log group, so these queries work as-is but return cross-account results. Filter by recipientAccountId for account-scoped views. Without an organization trail, run queries per account or use Amazon Security Lake as a central query surface.

    The attack chain mapped to AWS services

    Multi-stage attacks move through five phases, and each phase leaves a signal in a different service. These signals surface across three log sources: CloudTrail, which records API activity in your account; Amazon VPC Flow Logs, which capture network connection metadata; and Amazon Route 53 Resolver query logs, which record DNS queries from your VPCs.

    • Initial access – Stolen credentials reach your environment. CloudTrail records GetCallerIdentity, GetSessionToken, or AssumeRole from an unfamiliar source.
    • Discovery – The threat actor enumerates with List, Describe, and Get calls, often triggering AccessDenied responses.
    • Privilege escalation – The threat actor chains roles or edits policies. CloudTrail records AssumeRole sequences, PutRolePolicy, or CreateAccessKey.
    • Lateral movement – The threat actor moves across accounts or AWS Regions, assuming roles and creating resources in unfamiliar places.
    • Exfiltration – Data leaves through GetObject calls at scale, large outbound transfers in VPC Flow Logs, and DNS queries in Route 53 Resolver query logs to recently registered domains.

    Figure 1 shows the five attack phases mapped to the AWS log source that records each one.

    Figure 1: Attack chain mapped to AWS services

    Figure 1: Attack chain mapped to AWS services

    GuardDuty Extended Threat Detection watches this chain for universal patterns. The four patterns that follow add the dimension you supply: your business context.

    Pattern one: Sensitive data access by an unexpected principal

    Your data classification and access norms drive this detection. One bucket holds customer records, another holds public web assets, and you know which principals have a reason to read the customer records, which are sensitive. Encode that knowledge and an ordinary looking read turns into something worth chasing.

    Three signals converge here. CloudTrail shows GetObject at volume on a bucket you’ve classified as sensitive. The principal isn’t on your list of expected readers for that bucket. And VPC Flow Logs show a large outbound transfer from the same source in the same window, while DNS query logs show a recently registered destination domain, which together increase your confidence that there’s a potential threat.

    CloudTrail management events don’t record GetObject. You must turn on CloudTrail data events for the buckets you care about to capture GetObject. Many teams miss GetObject because data events weren’t enabled on the relevant buckets.

    This query shows bulk reads on a sensitive bucket, grouped by principal. Run it in CloudWatch Logs Insights with your CloudTrail log group selected.

    fields @timestamp, userIdentity.arn, requestParameters.bucketName
    | filter eventSource = "s3.amazonaws.com" and eventName = "GetObject"
    | filter requestParameters.bucketName = "your-sensitive-bucket"
    | stats count(*) as objectReads,
            count_distinct(requestParameters.key) as distinctObjects
            by userIdentity.arn, bin(10m)
    | filter objectReads > 100
    | sort objectReads desc
    

    The threshold of 100 is a placeholder. Run the query over a week of normal activity, find the ninety-fifth percentile read count for that bucket, and set the threshold above it. Then check each principal the query returns against your expected reader list. A principal that isn’t on the list, reading at volume, is the result to investigate.

    To corroborate, look for a matching outbound transfer. Switch the log group selector to your VPC Flow Logs log group and run this.

    fields @timestamp, srcAddr, dstAddr, bytes
    | filter action = "ACCEPT"
    # exclude RFC 1918 private ranges so only external destinations remain
    | filter dstAddr not like /^10\./
            and dstAddr not like /^192\.168\./
            and dstAddr not like /^172\.(1[6-9]|2[0-9]|3[0-1])\./
    | stats sum(bytes) as totalBytes by srcAddr, dstAddr, bin(10m)
    | filter totalBytes > 1000000000
    | sort totalBytes desc

    The Amazon S3 query returns a principal, and the Flow Logs query works on IP addresses, so you translate one into the other. The worked example later in this post covers that translation in full.

    Picture an analytics role that reads a reporting bucket all day. One afternoon, it reads a thousand objects from your customer records bucket instead. GuardDuty stays quiet, because an authenticated role making valid GetObject calls isn’t suspicious anywhere else. Your query flags it, because that role isn’t on the expected reader list for that bucket. The classification you applied is what turns silence into a signal.

    Figure 2 shows a bulk read from a sensitive bucket in CloudTrail, a large outbound transfer in VPC Flow Logs, and a young domain resolution in Route 53 Resolver logs.

    Figure 2: Three signals converging within a single time window to indicate exfiltration

    Figure 2: Three signals converging within a single time window to indicate exfiltration

    Pattern two: A role chain that crosses your access policy

    Picture a deployment that assumes one role to build, then a second to release. For one principal, that two-hop AssumeRole chain is routine; for a different principal it’s a policy violation. This pattern relies on your trust topology—the chains your organization permits—so put that knowledge in the query.

    This pattern needs three conditions:

    • CloudTrail shows several AssumeRole calls from the same source inside a short window
    • The chain ends in a sensitive action such as CreateAccessKey, PutRolePolicy, or AttachUserPolicy
    • The starting identity isn’t one your policy expects to run that chain

    In CloudWatch Logs Insights, select your CloudTrail log group and run this query, which surfaces chains of two or more hops.

    fields @timestamp, userIdentity.arn, requestParameters.roleArn, sourceIPAddress
    | filter eventName = "AssumeRole"
    | stats count(*) as assumeCount,
            count_distinct(requestParameters.roleArn) as rolesAssumed
            by sourceIPAddress, bin(5m)
    | filter assumeCount >= 2 and rolesAssumed >= 2
    | sort assumeCount desc

    Two hops is the minimum for a chain; raise the count if your environment chains roles often. Your deployment pipeline probably assumes several roles an hour, as do AWS service principals such as AWS Security Hub. Exclude the identities you expect to see assuming multiple roles, including your pipeline role and known AWS service principals. What’s left is the set to investigate, such as a person assuming several roles at an odd hour and ending in a new access key. Treat that distinction as data: list the identities and actions you consider normal, and review the chains that fall outside the list.

    Pattern three: An encryption key used outside its owning workload

    Resource ownership is the signal here. A given AWS Key Management Service (AWS KMS) key creates and controls the encryption keys for a workload, and a single key should serve a single workload, such as a payments service. A Decrypt call against it is a valid, authorized API action, so nothing about the call itself looks wrong. The ownership rule you set is what makes another principal’s use of the key worth a second look.

    This pattern applies only to customer-managed keys scoped to one workload. It doesn’t apply to AWS-managed keys (alias/aws/*) or to customer-managed keys intentionally shared across services. Confirm single-workload intent from the key policy’s Principal block before deploying this rule.

    Two conditions indicate misuse:

    • CloudTrail shows Decrypt or GenerateDataKey calls on a key that’s tied to one workload
    • The calling principal isn’t the role that owns that workload

    Against your CloudTrail log group, run this query to list the principals that called a specific key.

    fields @timestamp, userIdentity.arn, eventName
    | filter eventSource = "kms.amazonaws.com"
    | filter eventName in ["Decrypt", "GenerateDataKey", "Encrypt"]
    | filter resources.0.ARN = "arn:aws:kms:region:account-id:key/your-key-id"
    | stats count(*) as keyUses by userIdentity.arn, eventName
    | sort keyUses desc

    Compare what comes back against the one workload role you expect. A principal you don’t recognize on that key is the signal. Because key misuse is an early move in data theft, this correlation catches activity that only your ownership knowledge can flag.

    Consider a key that wraps your payments database. The payments service role calls it in normal operation, and nothing else should. If a developer role or a freshly created role runs Decrypt against it, the call succeeds and reads as ordinary in isolation. The reason it matters is the ownership rule you hold in your head and now state in this query.

    Pattern four: A privileged action outside your change window

    Start with the query, then read what it means.

    fields @timestamp, userIdentity.arn, eventName, sourceIPAddress
    | filter eventName in ["PutRolePolicy", "AttachRolePolicy",
            "CreateAccessKey", "AuthorizeSecurityGroupIngress", "PutBucketPolicy"]
    | stats count(*) as sensitiveChanges by userIdentity.arn, eventName, sourceIPAddress
    | sort sensitiveChanges desc

    Run it against your CloudTrail log group, scoped to your off-hours window when you schedule it, so it returns only activity outside the change window. Your change process defines what normal looks like here: production security and identity changes flow through a pipeline during defined hours, run by a known actor. A console-driven policy change at 2:00 AM, made by a person rather than the pipeline, doesn’t fit those expectations. The signal is a sensitive change such as PutRolePolicy or AuthorizeSecurityGroupIngress, made outside the window, by a person rather than your pipeline role.

    Exclude the actors you expect, such as your deployment pipeline role, your patch automation role, and AWS service principals like AWS CloudFormation and AWS Systems Manager. What remains is privileged change made outside your process, which is both what an attacker does to establish persistence and what your own change discipline says shouldn’t happen.

    Your pipeline might open security group rules during a deployment every weekday afternoon. A person opening a security group rule at midnight on a weekend is the same API call carrying a very different meaning. The schedule and the actor, both facts you define, are what separate the two.

    Build your first correlation rule

    The following walkthrough uses pattern one as a complete example. The other three patterns follow the same design with their own queries.

    Prerequisites

    These prerequisites feed the queries in this walkthrough. Confirm each one before you start:

    • A CloudTrail trail logging management events to a CloudWatch Logs log group
    • CloudTrail data events enabled for your sensitive S3 buckets
    • GuardDuty enabled, with its protection plans and Extended Threat Detection
    • VPC Flow Logs on for your production VPCs
    • Amazon Route 53 Resolver query logging on

    CloudTrail, GuardDuty, VPC Flow Logs, and Route 53 Resolver query logging provide the raw signals that your correlations connect. Without them, the queries in this post return empty results.

    Step 1: Record the bucket and its expected readers

    Choose one sensitive bucket to monitor, and write down the principals allowed to read it. Store the list where your automation can reach it, such as a configuration file in version control or an Amazon DynamoDB table (a managed NoSQL database).

    {
      "customer-records-prod": [
        "arn:aws:iam::123456789012:role/AnalyticsPipeline",
        "arn:aws:iam::123456789012:role/ComplianceAudit"
      ],
      "financial-data-archive": [
        "arn:aws:iam::123456789012:role/FinanceReporting"
      ]
    }

    This example hardcodes the list for simplicity. In production, load it from a DynamoDB table or Parameter Store so you can update it without redeploying.

    Step 2: Baseline before you set a threshold

    Run the pattern one query over one week of normal activity. Find the 95th percentile read count for the bucket and use a value greater than that as your alert threshold. This step keeps legitimate high-volume access from generating false positives later.

    Set the THRESHOLD_READS environment variable to this value when you configure the function in Step 5.

    Step 3: Run the access query

    In the CloudWatch console:

    1. Choose Logs, then choose Logs Insights.
    2. In the Select log group(s) dropdown, select your CloudTrail log group.
    3. Set the time range to 3h (the last three hours).
    4. In the query editor, paste the pattern one query.
    5. Replace your-sensitive-bucket with your bucket name.
    6. Choose Run query.
    7. Review the principals in the results table.
    8. Compare each principal against your expected reader list from step 1, and flag any that are not on it.

    Each result includes a principal that step 4 translates into an IP address.

    Step 4: Correlate with network activity

    CloudTrail logs actions by AWS Identity and Access Management (IAM) principal, while VPC Flow Logs record traffic by IP address. To connect the two signals, translate the principal into its address.

    For a role attached to an Amazon Elastic Compute Cloud (Amazon EC2) instance, the userIdentity.principalId field includes the instance ID after the colon, in the form AROAEXAMPLE:i-1234567890abcdef0. Copy the instance ID and look up its private IP address.

    aws ec2 describe-instances \
      --instance-ids i-1234567890abcdef0 \
      --query "Reservations[0].Instances[0].PrivateIpAddress" \
      --output text

    Other compute types differ. A VPC-connected AWS Lambda function sends traffic through elastic network interfaces in your subnets, so correlate on those interface addresses. An Amazon Elastic Container Service (Amazon ECS) task records its network interface in task metadata. For a plain assumed-role session with no instance behind it, the sourceIPAddress field in CloudTrail already holds the caller’s address, so you correlate on it directly.

    Run the Flow Logs query from pattern one, filtering srcAddr to that address within 10 minutes of the Amazon S3 read timestamp. A match places the same source behind both the sensitive read and a large external transfer in one window. CloudTrail events reach CloudWatch Logs 5–15 minutes after the API call, so correlate on eventTime rather than query time. Query a wider lookback than your correlation window: for example, look back 30 to 60 minutes but correlate on a 10-minute eventTime window. Steps 3 and 4 are manual validation; step 5 automates them.

    Figure 2 shows DNS resolution as a third corroborating signal. This walkthrough implements the CloudTrail and VPC Flow Logs correlation. To add DNS, apply the same run_query() pattern against your Route 53 Resolver query log group.

    Step 5: Automate the check

    Move the query into a Lambda function (serverless compute that runs your code without a server to manage), send results to a notification channel, and schedule regular runs. Work through the following sub-procedures.

    To create the notification channel

    1. Open the Amazon Simple Notification Service (Amazon SNS) console. Amazon SNS is a managed messaging service that delivers notifications to subscribers.
    2. In the navigation pane, choose Topics.
    3. Choose Create topic.
    4. For Type, select Standard.
    5. For Name, enter security-correlation-alerts.
    6. Choose Create topic.
    7. Note the topic Amazon Resource Name (ARN) at the top of the topic details page. You will use it in the function.
    8. Choose Create subscription.
    9. For Protocol, select Email.
    10. For Endpoint, enter your email address or incident management endpoint.
    11. Choose Create subscription, then confirm the subscription from the email AWS sends.

    To create the EventBridge Scheduler execution role

    The schedule needs a role that lets it invoke your function, and its trust policy needs conditions that pin the role to the schedule you own. Without those conditions, another account with access to the scheduler service could theoretically call this role; a class of misuse known as the confused deputy problem.

    1. Create a trust policy file named scheduler-trust-policy.json.

    {
      "Version": "2012-10-17",
      "Statement": [
        {
          "Effect": "Allow",
          "Principal": { "Service": "scheduler.amazonaws.com" },
          "Action": "sts:AssumeRole",
          "Condition": {
            "StringEquals": {
              "aws:SourceAccount": "ACCOUNT-ID"
            },
            "ArnLike": {
              "aws:SourceArn": "arn:aws:scheduler:REGION:ACCOUNT-ID:schedule/*/s3-access-correlation-hourly"
            }
          }
        }
      ]
    }
    

    2. Create the role, then attach permission to invoke the function. Scope Resource to the specific function ARN so this role can’t invoke anything else.

    aws iam create-role \
      --role-name EventBridgeSchedulerRole \
      --assume-role-policy-document file://scheduler-trust-policy.json
    
    aws iam put-role-policy \
      --role-name EventBridgeSchedulerRole \
      --policy-name LambdaInvokePolicy \
      --policy-document '{
        "Version": "2012-10-17",
        "Statement": [
          {
            "Effect": "Allow",
            "Action": "lambda:InvokeFunction",
            "Resource": "arn:aws:lambda:REGION:ACCOUNT-ID:function:CorrelationFunction"
          }
        ]
      }'

    When you create the function, Lambda automatically creates an execution role. You will attach the permissions this function needs to that role in a later step.

    To deploy the correlation function

    1. Open the Lambda console.
    2. Choose Create function.
    3. For Function name, enter CorrelationFunction.
    4. For Runtime, select the latest Python runtime.
    5. Choose Create function.
    6. On the Code tab, replace the default code with the following function, then choose Deploy.
    import os
    import time
    import logging
    import boto3
    from botocore.exceptions import ClientError
    
    logger = logging.getLogger()
    logger.setLevel(logging.INFO)
    
    logs = boto3.client("logs")
    sns = boto3.client("sns")
    ec2 = boto3.client("ec2")
    
    CLOUDTRAIL_LOG_GROUP = os.environ["CLOUDTRAIL_LOG_GROUP"]
    FLOWLOGS_LOG_GROUP = os.environ["FLOWLOGS_LOG_GROUP"]
    SNS_TOPIC = os.environ["SNS_TOPIC_ARN"]
    BUCKET = os.environ["SENSITIVE_BUCKET"]
    THRESHOLD = int(os.environ.get("THRESHOLD_READS", "100"))
    
    # Expected readers per bucket
    EXPECTED_READERS = {
        "customer-records-prod": [
            "arn:aws:iam::123456789012:role/AnalyticsPipeline",
            "arn:aws:iam::123456789012:role/ComplianceAudit",
        ],
    }
    
    
    def run_query(log_group, query, start, end):
        """Start a Logs Insights query and wait for it to finish."""
        started = logs.start_query(
            logGroupName=log_group,
            startTime=start,
            endTime=end,
            queryString=query,
        )
        query_id = started["queryId"]
        while True:
            outcome = logs.get_query_results(queryId=query_id)
            if outcome["status"] in ("Complete", "Failed", "Cancelled"):
                break
            time.sleep(1)
        if outcome["status"] != "Complete":
            raise RuntimeError(f"Query did not complete: {outcome['status']}")
        return [{f["field"]: f["value"] for f in row} for row in outcome["results"]]
    
    
    def private_ip_for_principal(principal_id):
        """Resolve an EC2 instance role principalId to its private IP."""
        if ":" not in principal_id:
            return None
        instance_id = principal_id.split(":", 1)[1]
        if not instance_id.startswith("i-"):
            return None
        reservations = ec2.describe_instances(InstanceIds=[instance_id])
        for reservation in reservations["Reservations"]:
            for instance in reservation["Instances"]:
                return instance.get("PrivateIpAddress")
        return None
    
    
    def egress_bytes(src_addr, start, end):
        """Sum external egress bytes for one source address."""
        query = f"""
        fields srcAddr, dstAddr, bytes
        | filter action = "ACCEPT" and srcAddr = "{src_addr}"
        | filter dstAddr not like /^10\\./
                and dstAddr not like /^192\\.168\\./
                and dstAddr not like /^172\\.(1[6-9]|2[0-9]|3[0-1])\\./
        | stats sum(bytes) as totalBytes
        """
        rows = run_query(FLOWLOGS_LOG_GROUP, query, start, end)
        if rows and rows[0].get("totalBytes"):
            return int(rows[0]["totalBytes"])
        return 0
    
    
    def lambda_handler(event, context):
        try:
            # 1-hour lookback absorbs CloudTrail's 5-15 min delivery latency;
            # correlation happens on eventTime via 10-min bins in the query below.
            end = int(time.time())
            start = end - 3600  # 1 hour lookback
            allowed = EXPECTED_READERS.get(BUCKET, [])
    
            access_query = f"""
            fields userIdentity.arn, userIdentity.principalId
            | filter eventSource = "s3.amazonaws.com" and eventName = "GetObject"
            | filter requestParameters.bucketName = "{BUCKET}"
            | stats count(*) as objectReads
                    by userIdentity.arn, userIdentity.principalId, bin(10m)
            | filter objectReads > {THRESHOLD}
            """
    
            for row in run_query(CLOUDTRAIL_LOG_GROUP, access_query, start, end):
                principal = row.get("userIdentity.arn")
                if not principal or principal in allowed:
                    continue
    
                message = (
                    f"Principal {principal} read {row.get('objectReads')} "
                    f"objects from {BUCKET}."
                )
    
                ip = private_ip_for_principal(row.get("userIdentity.principalId", ""))
                if ip and egress_bytes(ip, start, end) > 1_000_000_000:
                    message += (
                        f" The same source ({ip}) also sent a large volume of "
                        f"data to external destinations in the same window."
                    )
    
                sns.publish(
                    TopicArn=SNS_TOPIC,
                    Subject="Unexpected S3 access detected",
                    Message=message,
                )
        except ClientError as error:
            logger.error(f"AWS API error: {error}")
            raise
        except Exception as error:
            logger.error(f"Unexpected error: {error}")
            raise
        finally:
            logger.info("Correlation check completed")

    1. On the Configuration tab, choose General configuration, then choose Edit. Set Timeout to 5 minutes (300 seconds). CloudWatch Logs Insights queries run asynchronously and can take 30 to 60 seconds against large log groups. Choose Save.
    2. On the Configuration tab, choose Environment variables, then choose Edit, and add CLOUDTRAIL_LOG_GROUP, FLOWLOGS_LOG_GROUP, SNS_TOPIC_ARN, SENSITIVE_BUCKET, and THRESHOLD_READS.
    3. On the Configuration tab, choose Permissions, open the execution role, and attach the following least-privilege policy.
    {
      "Version": "2012-10-17",
      "Statement": [
        {
          "Effect": "Allow",
          "Action": ["logs:StartQuery", "logs:GetQueryResults"],
          "Resource": [
            "arn:aws:logs:REGION:ACCOUNT-ID:log-group:aws-cloudtrail-logs-my-trail:*",
            "arn:aws:logs:REGION:ACCOUNT-ID:log-group:vpc-flow-logs:*"
          ]
        },
        {
          "Effect": "Allow",
          "Action": "ec2:DescribeInstances",
          "Resource": "*"
        },
        {
          "Effect": "Allow",
          "Action": "sns:Publish",
          "Resource": "arn:aws:sns:REGION:ACCOUNT-ID:security-correlation-alerts"
        }
      ]
    }

    Replace REGION, ACCOUNT-ID, and the log-group names with your values. The ec2:DescribeInstances action doesn’t support resource-level permissions, so Resource: "*" is required for that statement; the other statements are scoped to specific ARNs.

    To schedule automated runs

    Amazon EventBridge (a serverless event bus that connects applications using events) runs targets on a schedule. Create one from the command line, using the role you made earlier.

    aws scheduler create-schedule \
      --name s3-access-correlation-hourly \
      --schedule-expression "rate(1 hour)" \
      --target "Arn=arn:aws:lambda:REGION:ACCOUNT-ID:function:CorrelationFunction,RoleArn=arn:aws:iam::ACCOUNT-ID:role/EventBridgeSchedulerRole" \
      --flexible-time-window "Mode=OFF"

    Step 6: Add enrichment context (optional)

    Enrichment cuts triage time by adding an independent signal, but it isn’t required for the correlation to work. This step adds costs. You pay your geolocation provider for API calls, and the additional Lambda execution time increases your Lambda charges. To add IP geolocation, sign up for a geolocation API, add this function to the code, and call it where the handler resolves an IP.

    import urllib.request
    import json
    
    def geo_context(ip_address):
        """Enrich an IP address with geolocation data from your provider."""
        try:
            url = f"https://your-geolocation-api.example/json/{ip_address}"
            with urllib.request.urlopen(url, timeout=5) as response:
                data = json.load(response)
            return {
                "country": data.get("country_name"),
                "city": data.get("city"),
                "org": data.get("org"),
            }
        except Exception as error:
            logger.warning(f"Geolocation lookup failed for {ip_address}: {error}")
            return None

    Inside the handler’s loop, after you resolve ip, append the location to the alert.

                if ip:
                    geo = geo_context(ip)
                    if geo:
                        message += (
                            f" Source location: {geo['city']}, "
                            f"{geo['country']} ({geo['org']})."
                        )

    Step 7: Scale to additional patterns and accounts

    As your library grows, move the logic into automated pipelines with EventBridge, Lambda, and AWS Step Functions (a serverless orchestration service that coordinates multiple services into workflows), and surface correlations next to findings in Security Hub. For cross-service correlation at scale, CloudWatch unified data and telemetry capabilities can convert security and compliance data into the OCSF format and let you query sources such as CloudTrail, VPC Flow Logs, and DNS logs from one interface. Security Lake with Athena is a strong option for long-term analysis. Choose the endpoint that fits your retention and query needs.

    Figure 3 shows a correlation pipeline built on AWS services including EventBridge, Lambda, Step Functions, and AWS Security Hub. The pipeline runs from data sources through scheduled queries and enrichment to automated response and centralized visibility.

    Figure 3: A correlation pipeline built on AWS services

    Figure 3: A correlation pipeline built on AWS services

    Conclusion

    You now have four correlation patterns that layer your business context on top of GuardDuty Extended Threat Detection to catch attacks specific to your environment. A few principles carry across every correlation you build.

    • Identity is your primary correlation key: Track the same principal across services.
    • Time windows matter, but they depend on the attack: Events minutes apart are usually related for fast, automated sequences; the ten-minute bins here work for that pattern. Slow or manual reconnaissance can stretch across hours or days, so widen the window when the pattern is deliberate rather than automated.
    • Context is what you add: Your data classification, access norms, resource ownership, and change windows are signals you bring to detection.
    • Start with one rule: A single well-tuned correlation catches more significant activity than a wall of uncorrelated alerts.

    GuardDuty Extended Threat Detection handles the multi-stage patterns common across customers. The correlations in this post add the layer that only your business context can supply. Start with one pattern this week, validate it against your own traffic, and add the next pattern after the first proves reliable.

    Have you built correlation rules for patterns not covered here? Share your experience in the Comments section below.

    Further reading

     

    Nisha Kashyap

    Nisha Kashyap

    Nisha Kashyap is a Senior Support Security Engineer at AWS. She works on threat detection and security operations, helping customers investigate security events and build detection that connects signals across AWS services and reflects their own environment.

    Enable cross-cloud analytics with Amazon S3 Tables and Google BigQuery, Part 1: IAM-based access control

    Post Syndicated from Lakshmi Nair original https://aws.amazon.com/blogs/big-data/enable-cross-cloud-analytics-with-amazon-s3-tables-and-google-bigquery-part-1-iam-based-access-control/

    Organizations running analytics workloads across multiple clouds often hit the same friction: the data lives on one cloud, but the engine querying it lives on another. Copying data across the boundary creates a second dataset that must be kept in sync, adding cost, latency, and reconciliation overhead. In this post, we address a specific instance of that pattern: your Google BigQuery users need to work with data that lives in Amazon S3 Tables, a capability of Amazon Simple Storage Service (Amazon S3), on AWS. The ideal outcome is a single, governed dataset that serves teams in both clouds without a standing replication pipeline between them.

    With Amazon S3 Tables, you get managed Apache Iceberg tables with built-in compaction, snapshot management, and an integration with the AWS Glue Data Catalog. Because S3 Tables stores data in the open Iceberg format, supported external engines can read it directly if the right access path exists.

    This two-part blog series demonstrates how you can connect Google BigQuery to Amazon S3 Tables using the cross-cloud lakehouse with AWS Glue. We cover two access control approaches:

    1. AWS Identity and Access Management (IAM): You can define a single policy that uses IAM permissions to set up access to both table metadata and data.
    2. AWS Lake Formation: You can use temporary vended credentials for data access, with metadata access managed by Lake Formation permissions.

    This post focuses on the IAM-based approach. Part 2 covers the Lake Formation approach for organizations that need credential-vended access across multiple engines.

    By the end, you will have BigQuery querying Iceberg tables stored on S3 Tables without data copy or duplication, providing live access to Iceberg data.

    Cross-cloud analytics scenarios

    There are several scenarios where organizations benefit from cross-cloud querying capabilities. Here are some of the common patterns this architecture addresses:

    Schema evolution across cloud boundaries

    When source schemas change frequently, streaming pipelines writing to BigQuery-managed store require coordinated DDL changes on the BigQuery table and downstream views. Teams often work around this challenge by storing payloads as untyped columns and parsing them later.

    With Iceberg on S3 Tables, schema evolution is tracked in table metadata. When the writing engine adds a new column, BigQuery’s Lakehouse refresh picks up the updated schema automatically on the next sync cycle.

    Multi-cloud analytics without data duplication

    A company has its production data environment on AWS (data lakes, warehouses, streaming) but acquired a business unit that runs analytics exclusively on BigQuery. In-place querying from BigQuery keeps your data in Amazon S3 Tables, so you pay for one copy, work from live data, and avoid the operational overhead of a synchronized second store.

    Cost optimization for infrequently queried datasets

    An organization has hundreds of datasets on AWS, but only a fraction is queried daily from BigQuery. Replicating all of them to Google Cloud Storage drives unnecessary storage and transfer costs. With Lakehouse catalog federation, you keep your data on S3 Tables. BigQuery reads data only when queried, so you pay per query rather than per-copy storage.

    Decoupled compute across engines

    Data team wants storage on AWS with the flexibility for multiple engines to read the same data: BigQuery and Amazon Redshift for data warehousing use cases, Amazon Athena for interactive ad-hoc querying, Amazon SageMaker AI for machine learning (ML). With Apache Iceberg’s open format, you can use one storage layer, many compute engines, no data copies between them.

    Solution overview

    You use the AWS Glue Iceberg REST Catalog (IRC) as the bridge between BigQuery and S3 Tables. BigQuery’s cross-cloud Lakehouse creates a federated catalog that syncs metadata from the Glue IRC, then uses the synced metadata to read Iceberg data files directly.

    Architecture diagram showing BigQuery connecting to Amazon S3 Tables through the AWS Glue Iceberg REST Catalog

    Figure 1: Architecture diagram showing BigQuery connecting to Amazon S3 Tables through the AWS Glue Iceberg REST Catalog

    The key components in this architecture:

    1. Amazon S3 Tables: With Amazon S3 Tables, you get a fully managed Apache Iceberg table experience in Amazon S3, optimized for analytics workloads. You can register table metadata in the AWS Glue Data Catalog for discovery and governance.
    2. AWS Glue Data Catalog: With AWS Glue Data Catalog, you can access the federated s3tablescatalog catalog that maps S3 Tables resources (table buckets, namespaces, tables) into a catalog hierarchy from supported analytics engines. The standard Iceberg REST endpoint of Glue Data Catalog serves table metadata to external engines. BigQuery connects through this endpoint.
    3. Google Cross-Cloud Lakehouse: With Google Cross-Cloud Lakehouse, you can connect BigQuery to external Iceberg catalogs. It assumes an AWS IAM role using OpenID Connect (OIDC), calls the Glue Iceberg REST endpoint, and syncs metadata on a configurable refresh interval.

    Prerequisites

    Before you begin, you need:

    • An AWS account with Amazon S3 Tables available in your AWS Region.
    • A Google Cloud project with billing enabled and the BigLake API activated.
    • AWS Command Line Interface (AWS CLI) and gcloud CLI installed and configured.
    • An S3 table bucket with at least one namespace and table containing data.

    Setting up Amazon S3 Tables

    If you already have S3 Tables with data, skip to the next section. Otherwise, create a table bucket, namespace, and populate a table.

    Create a table bucket and namespace

    Use the AWS CLI to create resources as follows:

    # Create a Table bucket
    aws s3tables create-table-bucket \
        --name <TABLE_BUCKET_NAME> \
        --region <REGION>
    
    # Create a Namespace (Database)
    aws s3tables create-namespace \
        --table-bucket-arn "arn:aws:s3tables:<REGION>:<AWS_ACCOUNT_ID>:bucket/<TABLE_BUCKET_NAME>" \
        --namespace <NAMESPACE> \
        --region <REGION>

    Integrating S3 Tables with the Glue Data Catalog

    For BigQuery to access S3 Tables, the tables must be discoverable through the Glue Data Catalog. S3 Tables integrates with Glue through a federated catalog called s3tablescatalog.

    Set up S3 Tables integration with the Glue Data Catalog using IAM mode

    Open the Amazon S3 console:

    1. In the navigation pane, choose Table buckets.
    2. Choose Enable integration, and then choose Enable integration again to confirm.

    This creates the s3tablescatalog federated catalog in Glue, where access is controlled entirely by IAM policies on the calling role. This is a one-time setup per account and Region. After you enable it, the analytics integration applies to all table buckets in your account.

    The Enable integration option on the table buckets page of the Amazon S3 console

    Figure 2: Enabling the S3 Tables integration in the Amazon S3 console

    Alternatively, create the catalog using the AWS CLI:

    aws glue create-catalog --region <REGION> --cli-input-json '{
      "Name": "s3tablescatalog",
      "CatalogInput": {
        "FederatedCatalog": {
          "Identifier": "arn:aws:s3tables:<REGION>:<AWS_ACCOUNT_ID>:bucket/*",
          "ConnectionName": "aws:s3tables"
        },
        "CreateDatabaseDefaultPermissions": [
          { "Principal": {"DataLakePrincipalIdentifier": "IAM_ALLOWED_PRINCIPALS"}, "Permissions": ["ALL"] }
        ],
        "CreateTableDefaultPermissions": [
          { "Principal": {"DataLakePrincipalIdentifier": "IAM_ALLOWED_PRINCIPALS"}, "Permissions": ["ALL"] }
        ]
      }
    }'

    Create a table and insert data

    Now, to create the table and insert data, open the Amazon Athena console. In the query editor, select s3tablescatalog/<TABLE_BUCKET_NAME> as your data source and <NAMESPACE> as the database. Then run the following SQL statements one by one:

    CREATE TABLE `<NAMESPACE>`.orders (
        order_id STRING,
        customer_id STRING,
        amount BIGINT,
        order_date DATE,
        region STRING
    )
    TBLPROPERTIES ('table_type' = 'iceberg');
    
    INSERT INTO orders
    VALUES
        ('ORD-001', 'C100', 4500, DATE '2024-06-01', 'EMEA'),
        ('ORD-002', 'C200', 8900, DATE '2024-06-01', 'EMEA'),
        ('ORD-003', 'C100', 3200, DATE '2024-06-02', 'NAMER'),
        ('ORD-004', 'C300', 12000, DATE '2024-06-02', 'NAMER'),
        ('ORD-005', 'C400', 6700, DATE '2024-06-03', 'APJ'),
        ('ORD-006', 'C200', 4100, DATE '2024-06-03', 'APJ'),
        ('ORD-007', 'C500', 9500, DATE '2024-06-04', 'EMEA'),
        ('ORD-008', 'C100', 2800, DATE '2024-06-04', 'LATAM'),
        ('ORD-009', 'C600', 15000, DATE '2024-06-05', 'NAMER'),
        ('ORD-010', 'C300', 7200, DATE '2024-06-05', 'LATAM');

    Configuring cross-cloud access

    BigQuery assumes an AWS IAM role via OIDC federation to access the Glue IRC. This section walks through creating the role, OIDC provider, and permissions.

    Create the OIDC identity provider

    Register Google as an OIDC identity provider in your AWS account. This allows AWS to validate tokens issued by Google’s identity service:

    aws iam create-open-id-connect-provider \
        --url https://accounts.google.com \
        --client-id-list accounts.google.com \
        --thumbprint-list 08745487e891c19e3078c1f2a07e452950ef36f6

    The –thumbprint-list parameter is optional. When omitted, IAM automatically retrieves the thumbprint from the OIDC provider’s certificate. See AWS documentation for details.

    Create the cross-cloud IAM role

    Login into AWS Console, and  create the role with a placeholder trust policy. You will update it with the actual BigLake service account ID after you create the federated catalog in Google Cloud.

    aws iam create-role \
        --role-name bigquery-cross-cloud-role \
        --max-session-duration 43200 \
        --assume-role-policy-document '{
          "Version": "2012-10-17",
          "Statement": [{
            "Effect": "Allow",
            "Principal": {
              "Federated": "arn:aws:iam::<AWS_ACCOUNT_ID>:oidc-provider/accounts.google.com"
            },
            "Action": "sts:AssumeRoleWithWebIdentity",
            "Condition": {
              "StringEquals": {
                "accounts.google.com:sub": ["PLACEHOLDER"],
                "accounts.google.com:aud": ["PLACEHOLDER"]
              }
            }
          }]
        }'

    The --max-session-duration 43200 allows sessions up to 12 hours, which is needed for long-running BigQuery queries.

    Attach permissions

    The permissions policy differs based on your access control approach. For the IAM-based approach, attach the following policy:

    {
      "Version": "2012-10-17",
      "Statement": [
        {
          "Sid": "GlueRead",
          "Effect": "Allow",
          "Action": [
            "glue:GetCatalog", "glue:GetDatabase", "glue:GetDatabases",
            "glue:GetTable", "glue:GetTables", "glue:GetPartition", "glue:GetPartitions"
          ],
          "Resource": [
            "arn:aws:glue:<AWS_REGION>:<AWS_ACCOUNT_ID>:catalog",
            "arn:aws:glue:<AWS_REGION>:<AWS_ACCOUNT_ID>:catalog/s3tablescatalog",
            "arn:aws:glue:<AWS_REGION>:<AWS_ACCOUNT_ID>:catalog/s3tablescatalog/<TABLE_BUCKET>",
            "arn:aws:glue:<AWS_REGION>:<AWS_ACCOUNT_ID>:database/s3tablescatalog/<TABLE_BUCKET>/<NAMESPACE>",
            "arn:aws:glue:<AWS_REGION>:<AWS_ACCOUNT_ID>:table/s3tablescatalog/<TABLE_BUCKET>/<NAMESPACE>/*"
          ]
        },
        {
          "Sid": "S3TablesRead",
          "Effect": "Allow",
          "Action": [
            "s3tables:GetTableBucket", "s3tables:ListTableBuckets",
            "s3tables:ListNamespaces", "s3tables:GetNamespace",
            "s3tables:ListTables", "s3tables:GetTable",
            "s3tables:GetTableMetadataLocation", "s3tables:GetTableData"
          ],
          "Resource": [
            "arn:aws:s3tables:<AWS_REGION>:<AWS_ACCOUNT_ID>:bucket/<TABLE_BUCKET>",
            "arn:aws:s3tables:<AWS_REGION>:<AWS_ACCOUNT_ID>:bucket/<TABLE_BUCKET>/*"
          ]
        },
        {
          "Sid": "S3TablesListBuckets",
          "Effect": "Allow",
          "Action": ["s3tables:ListTableBuckets"],
          "Resource": "*"
        }
      ]
    }

    Connecting BigQuery to S3 Tables

    With the AWS side configured, create the federated catalog in Google Cloud that connects BigQuery to the Glue IRC.

    Create the federated catalog

    Authenticate to Google Cloud using gcloud auth login, or use Cloud Shell, which is pre-authenticated. Verify that the BigLake API is enabled:

    gcloud services enable biglake.googleapis.com --project="<GCP_PROJECT_ID>"

    For IAM mode:

    gcloud alpha biglake iceberg catalogs create <FEDERATED_CATALOG_NAME> \
        --project="<GCP_PROJECT_ID>" \
        --catalog-type=federated \
        --federated-catalog-type=glue \
        --glue-aws-region=<AWS_REGION> \
        --glue-aws-role-arn=arn:aws:iam::<AWS_ACCOUNT_ID>:role/bigquery-cross-cloud-role \
        --glue-warehouse=<AWS_ACCOUNT_ID>:s3tablescatalog/<TABLE_BUCKET> \
        --primary-location=<GCP_REGION>

    The --glue-warehouse parameter uses the format <AWS_ACCOUNT_ID>:s3tablescatalog/<TABLE_BUCKET>. This tells the Glue IRC to scope requests to your specific S3 Tables bucket within the federated catalog hierarchy.

    The --primary-location refers to the Google Cloud region where the federated catalog metadata is stored. Use the AWS to Google Cloud region mapping to find the corresponding GCP region for your AWS Region. For example, AWS us-east-1 maps to GCP us-east4.

    Retrieve the BigLake service account ID

    After catalog creation, Google provisions a dedicated service account for your federated catalog. Retrieve its numeric ID:

    BIGLAKE_SA_ID=$(gcloud alpha biglake iceberg catalogs describe <FEDERATED_CATALOG_NAME> \
        --project="<GCP_PROJECT_ID>" \
        --format="value(biglake-service-account-id)")
    echo $BIGLAKE_SA_ID

    Update the AWS trust policy

    Back on AWS, replace the placeholder in the IAM role’s trust policy with the actual service account ID:

    aws iam update-assume-role-policy \
        --role-name bigquery-cross-cloud-role \
        --policy-document '{
          "Version": "2012-10-17",
          "Statement": [{
            "Effect": "Allow",
            "Principal": {
              "Federated": "arn:aws:iam::<AWS_ACCOUNT_ID>:oidc-provider/accounts.google.com"
            },
            "Action": "sts:AssumeRoleWithWebIdentity",
            "Condition": {
              "StringEquals": {
                "accounts.google.com:sub": ["<BIGLAKE_SA_ID>"],
                "accounts.google.com:aud": ["<BIGLAKE_SA_ID>"]
              }
            }
          }]
        }'

    Register the service account ID in the OIDC provider’s audience list. Without this step, AWS rejects the token because the aud claim doesn’t match any registered client:

    aws iam add-client-id-to-open-id-connect-provider \
        --open-id-connect-provider-arn "arn:aws:iam::<AWS_ACCOUNT_ID>:oidc-provider/accounts.google.com" \
        --client-id "<BIGLAKE_SA_ID>"

    Set up metadata sync

    Wait 3–5 minutes for IAM changes to propagate globally, then set up background refresh:

    gcloud alpha biglake iceberg catalogs update <FEDERATED_CATALOG_NAME> \
        --project="<GCP_PROJECT_ID>" \
        --refresh-interval=300s

    The --refresh-interval (300 seconds in this example) determines how often BigQuery syncs metadata from the Glue IRC. New tables and schema changes appear in BigQuery within this interval.

    Querying from BigQuery

    After the catalog refresh completes, BigQuery automatically creates external datasets corresponding to the synced namespaces. No manual CREATE SCHEMA is required.

    Verify the sync:

    gcloud alpha biglake iceberg namespaces list \
        --catalog="<FEDERATED_CATALOG_NAME>" \
        --project="<GCP_PROJECT_ID>"

    Run a query in BigQuery:

    SELECT * FROM `<GCP_PROJECT_ID>.<FEDERATED_CATALOG_NAME>.<NAMESPACE>.orders` LIMIT 1000

    Sample Query Output:

    SELECT
        customer_id,
        COUNT(*) as order_count,
        SUM(amount) as total_spend
    FROM `<PROJECT_ID>.<FEDERATED_CATALOG_NAME>.<NAMESPACE>.orders`
    GROUP BY customer_id
    ORDER BY total_spend DESC
    BigQuery query results showing order count and total spend per customer from the Amazon S3 Tables data

    Figure 3: BigQuery query results returned directly from the Amazon S3 Tables data

    BigQuery reads the Iceberg metadata to identify which Parquet data files contain relevant data. It also applies partition pruning where applicable, and fetches only the necessary files from S3 Tables managed storage.

    Schema evolution

    When new columns are added to an Iceberg table on the AWS side (through Spark, Athena, or the Glue IRC), the schema change is captured in Iceberg’s metadata. On the next Lakehouse refresh cycle, BigQuery picks up the new columns automatically. No DDL changes are needed in BigQuery.

    Metadata freshness

    The s3tablescatalog in Glue is a federated catalog that resolves table metadata live from the S3 Tables service on each request. When a streaming job commits new data to an S3 Table, the latest metadata is immediately available through the AWS Glue IRC. BigQuery sees the update on its next refresh cycle (as configured by --refresh-interval).

    OIDC identity federation

    The trust relationship between Google Cloud and AWS uses OpenID Connect. When BigQuery Lakehouse needs to access your data, it presents a signed JWT token containing:

    • iss: accounts.google.com (the issuer)
    • sub: The BigLake service account ID (identifies which catalog is making the request)
    • aud: The same service account ID (the intended audience)

    AWS validates this token against the registered OIDC provider and trust policy conditions before issuing temporary credentials. Each federated catalog receives a unique service account ID, providing per-catalog isolation and auditability through AWS CloudTrail.

    Network path

    By default, traffic between BigQuery and AWS travels over the public internet. For workloads requiring private connectivity, Google Cloud supports Cross-Cloud Interconnect or Partner Interconnect. This helps routing queries over a dedicated network path. Refer to the Google Cloud documentation for private interconnect configuration.

    Clean up

    To avoid ongoing charges, remove the resources created in this walkthrough.

    On AWS:

    # Delete the table (if created for this walkthrough)
    aws s3tables delete-table \
        --table-bucket-arn "arn:aws:s3tables:<AWS_REGION>:<AWS_ACCOUNT_ID>:bucket/<TABLE_BUCKET>" \
        --namespace analytics --name orders --region <AWS_REGION>
    
    # Delete namespace and table bucket
    aws s3tables delete-namespace \
        --table-bucket-arn "arn:aws:s3tables:<AWS_REGION>:<AWS_ACCOUNT_ID>:bucket/<TABLE_BUCKET>" \
        --namespace <NAMESPACE> --region <AWS_REGION>
    
    aws s3tables delete-table-bucket --name <TABLE_BUCKET> --region <AWS_REGION>
    
    # Delete IAM role and OIDC provider (if no longer needed)
    aws iam delete-role --role-name bigquery-cross-cloud-role

    On Google Cloud:

    gcloud alpha biglake iceberg catalogs delete <FEDERATED_CATALOG_NAME> \
        --project="<GCP_PROJECT_ID>" --location=<GCP_REGION>

    Conclusion

    This post demonstrated how to query Amazon S3 Tables from Google BigQuery using the open Apache Iceberg format and the AWS Glue Iceberg REST Catalog as the metadata bridge. Using Apache Iceberg’s open format, you can write data once on AWS and read it from supported engines that speak Iceberg, including BigQuery. We used IAM-based access control to govern access to both Glue Data Catalog metadata and the underlying Amazon S3 Tables data. This is the simpler configuration path with fewer components. In Part 2, we walk through configuring AWS Lake Formation to vend temporary, scoped credentials to BigQuery for data access.

    To get started with this pattern in your environment:


    About the authors

    Lakshmi Nair

    Lakshmi Nair

    Lakshmi is a Principal Analytics Specialist Solutions Architect at AWS. She specializes in designing advanced analytics systems across industries. She focuses on crafting cloud-based data platforms, enabling real-time streaming, big data processing, and robust data governance.

    Srividya Parthasarathy

    Srividya Parthasarathy

    Srividya was a Senior Big Data Architect on the AWS Lake Formation team. She works with product team and customer to build robust features and solutions for their analytical data platform. She enjoys building data mesh solutions and sharing them with the community.

    Enable cross-cloud analytics with Amazon S3 Tables and Google BigQuery, Part 2: access control with Lake Formation

    Post Syndicated from Lakshmi Nair original https://aws.amazon.com/blogs/big-data/enable-cross-cloud-analytics-with-amazon-s3-tables-and-google-bigquery-part-2-access-control-with-lake-formation/

    In Part 1, we showed how to connect Google BigQuery to Amazon Simple Storage Service (Amazon S3) Tables, a capability of Amazon S3, using access control based on AWS Identity and Access Management (IAM). A single IAM policy governs both table metadata and data access. We also walked through common cross-cloud analytics scenarios where this pattern adds value. This post covers the approach using AWS Lake Formation. Instead of relying solely on IAM policies for data access, Lake Formation manages fine-grained permissions and vends temporary, scoped credentials to the requesting engine. This is a better fit when multiple engines need different levels of access to the same tables, or when you want to manage grants centrally without touching IAM policies every time a new consumer comes along.

    Solution overview

    You use the AWS Glue Iceberg REST Catalog (IRC) as the bridge between BigQuery and S3 Tables. BigQuery’s cross-cloud Lakehouse creates a federated catalog that syncs metadata from the Glue IRC, then uses the synced metadata to read Iceberg data files directly.

    Architecture diagram showing BigQuery connecting to Amazon S3 Tables through the AWS Glue Iceberg REST Catalog

    Figure 1: Architecture diagram showing BigQuery connecting to Amazon S3 Tables through the AWS Glue Iceberg REST Catalog

    The key components in this architecture:

    1. Amazon S3 Tables: With Amazon S3 Tables, data is stored in table buckets, specifically designed for storing tables in the Apache Iceberg format. Table metadata is registered on AWS Glue Data Catalog for discovery and governance.
    2. AWS Glue Data Catalog: With AWS Glue Data Catalog, you can access the federated s3tablescatalog catalog that maps S3 Tables resources (table buckets, namespaces, tables) into a catalog hierarchy from supported analytics engines. The standard Iceberg REST endpoint of Glue Data Catalog serves table metadata to external engines. BigQuery connects through this endpoint.
    3. AWS Lake Formation: With AWS Lake Formation, you define access permissions at the catalog, database, and table level. Instead of granting broad IAM permissions for data access, Lake Formation evaluates permissions at query time and issues short-lived credentials limited to the resources the caller is authorized to read.
    4. Google Cross-Cloud Lakehouse: With Google Cross-Cloud Lakehouse, you can connect BigQuery to external Iceberg catalogs. It assumes an IAM role using OpenID Connect (OIDC), calls the AWS Glue Iceberg REST endpoint, and syncs metadata on a configurable refresh interval.

    Prerequisites

    Before you begin, you need:

    • An AWS account with Amazon S3 Tables available in your AWS Region.
    • A Google Cloud project with billing enabled and the BigLake API activated.
    • AWS Command Line Interface (AWS CLI) and gcloud CLI installed and configured.
    • An S3 table bucket with at least one namespace and table containing data.

    Setting up Amazon S3 Tables

    If you already have S3 Tables with data, skip to the next section. Otherwise, create a table bucket, namespace, and populate a table.

    Create a table bucket and namespace

    Use AWS CLI to create resources as follows:

    # Create a Table bucket
    aws s3tables create-table-bucket \
        --name <TABLE_BUCKET_NAME> \
        --region <REGION>
    
    # Create a Namespace (Database)
    aws s3tables create-namespace \
        --table-bucket-arn "arn:aws:s3tables:<REGION>:<AWS_ACCOUNT_ID>:bucket/<TABLE_BUCKET_NAME>" \
        --namespace <NAMESPACE> \
        --region <REGION>

    Set up S3 Tables integration with the Glue Data Catalog using Lake Formation mode

    Lake Formation needs its own service role to interact with S3 Tables on your behalf. This is the role Lake Formation assumes internally when it reads or writes data on behalf of authorized callers.

    Create a Lake Formation service IAM role named LakeFormationS3TablesServiceRole with the following policy:

    {
      "Version": "2012-10-17",
      "Statement": [
        {
          "Sid": "LakeFormationPermissionsForS3ListTableBucket",
          "Effect": "Allow",
          "Action": ["s3tables:ListTableBuckets"],
          "Resource": ["*"]
        },
        {
          "Sid": "LakeFormationDataAccessPermissionsForS3TableBucket",
          "Effect": "Allow",
          "Action": [
            "s3tables:CreateTableBucket", "s3tables:GetTableBucket",
            "s3tables:CreateNamespace", "s3tables:GetNamespace",
            "s3tables:ListNamespaces", "s3tables:DeleteNamespace",
            "s3tables:DeleteTableBucket", "s3tables:CreateTable",
            "s3tables:DeleteTable", "s3tables:GetTable",
            "s3tables:ListTables", "s3tables:RenameTable",
            "s3tables:UpdateTableMetadataLocation", "s3tables:GetTableMetadataLocation",
            "s3tables:GetTableData", "s3tables:PutTableData"
          ],
          "Resource": ["arn:aws:s3tables:<AWS_REGION>:<AWS_ACCOUNT_ID>:bucket/*"]
        }
      ]
    }

    Attach the following trust relationship:

    {
      "Version": "2012-10-17",
      "Statement": [
        {
          "Sid": "LakeFormationDataAccessPolicy",
          "Effect": "Allow",
          "Principal": { "Service": "lakeformation.amazonaws.com" },
          "Action": ["sts:AssumeRole", "sts:SetContext", "sts:SetSourceIdentity"],
          "Condition": { "StringEquals": { "aws:SourceAccount": "<AWS_ACCOUNT_ID>" } }
        }
      ]
    }

    In the Lake Formation console, in the navigation pane, choose Catalogs, and then choose Enable S3 Table Integration.

    The Enable S3 Table Integration option on the Catalogs page of the Lake Formation console

    Figure 2: Enabling the S3 Tables integration in the Lake Formation console

    Choose the role you created earlier when prompted for an IAM role, and select Allow external engines to access data in Amazon S3 locations with full table access.

    S3 Tables integration performs the following:

    1. Registers the S3 Tables data location with Lake Formation.
    2. Creates the s3tablescatalog federated catalog in Glue.

    Important: Before enabling the integration, verify your Lake Formation data lake settings have empty default permissions to prevent IAMAllowedPrincipals from being auto-granted on the catalog:

    aws lakeformation put-data-lake-settings \
        --data-lake-settings '{"DataLakeAdmins":[{"DataLakePrincipalIdentifier":"arn:aws:iam::<AWS_ACCOUNT_ID>:role/<ADMIN_ROLE>"}],"CreateDatabaseDefaultPermissions":[],"CreateTableDefaultPermissions":[]}' \
        --region <AWS_REGION>
    The S3 Tables integration dialog in Lake Formation with full table access selected

    Figure 3: Selecting full table access for external engines during S3 Tables integration

    When you select this option, you  allow external engines to access data in Amazon S3 locations with full table access, and Lake Formation grants full table-level access to external engines. Column-level and row-level filtering are not enforced for external engine connections. Access is granted at the whole-table level.

    Verify the integration by confirming the catalog in Lake Formation console.

    Create a table and insert data

    Now, to create the table and insert data, open the Amazon Athena console. In the query editor, select s3tablescatalog/<TABLE_BUCKET_NAME> as your data source and <NAMESPACE> as the database. Then run the following SQL statements one by one:

    CREATE TABLE `<NAMESPACE>`.orders (
        order_id STRING,
        customer_id STRING,
        amount BIGINT,
        order_date DATE,
        region STRING
    )
    TBLPROPERTIES ('table_type' = 'iceberg');
    
    INSERT INTO orders
    VALUES
        ('ORD-001', 'C100', 4500, DATE '2024-06-01', 'EMEA'),
        ('ORD-002', 'C200', 8900, DATE '2024-06-01', 'EMEA'),
        ('ORD-003', 'C100', 3200, DATE '2024-06-02', 'NAMER'),
        ('ORD-004', 'C300', 12000, DATE '2024-06-02', 'NAMER'),
        ('ORD-005', 'C400', 6700, DATE '2024-06-03', 'APJ'),
        ('ORD-006', 'C200', 4100, DATE '2024-06-03', 'APJ'),
        ('ORD-007', 'C500', 9500, DATE '2024-06-04', 'EMEA'),
        ('ORD-008', 'C100', 2800, DATE '2024-06-04', 'LATAM'),
        ('ORD-009', 'C600', 15000, DATE '2024-06-05', 'NAMER'),
        ('ORD-010', 'C300', 7200, DATE '2024-06-05', 'LATAM');

    Configuring cross-cloud access

    BigQuery assumes an AWS IAM role using OIDC federation to access the AWS Glue IRC. This section walks through creating the role, OIDC provider, and permissions.

    Create the OIDC identity provider

    Register Google as an OIDC identity provider in your AWS account. This allows AWS to validate tokens issued by Google’s identity service:

    aws iam create-open-id-connect-provider \
        --url https://accounts.google.com \
        --client-id-list accounts.google.com \
        --thumbprint-list 08745487e891c19e3078c1f2a07e452950ef36f6

    The –thumbprint-list parameter is optional. When omitted, IAM automatically retrieves the thumbprint from the OIDC provider’s certificate. See AWS documentation for details.

    Create the cross-cloud IAM role on AWS

    Sign in to the AWS Management Console. Create the role with a placeholder trust policy. You will update it with the actual BigLake service account ID after you create the federated catalog in Google Cloud.

    aws iam create-role \
        --role-name bigquery-cross-cloud-role \
        --max-session-duration 43200 \
        --assume-role-policy-document '{
          "Version": "2012-10-17",
          "Statement": [{
            "Effect": "Allow",
            "Principal": {
              "Federated": "arn:aws:iam::<AWS_ACCOUNT_ID>:oidc-provider/accounts.google.com"
            },
            "Action": "sts:AssumeRoleWithWebIdentity",
            "Condition": {
              "StringEquals": {
                "accounts.google.com:sub": ["PLACEHOLDER"],
                "accounts.google.com:aud": ["PLACEHOLDER"]
              }
            }
          }]
        }'

    The --max-session-duration 43200 allows sessions up to 12 hours, which is needed for long-running BigQuery queries.

    Attach permissions

    The permissions policy differs based on your access control approach. For the Lake Formation approach, attach the following policy:

    {
      "Version": "2012-10-17",
      "Statement": [
        {
          "Sid": "GlueRead",
          "Effect": "Allow",
          "Action": [
            "glue:GetCatalog", "glue:GetDatabase", "glue:GetDatabases",
            "glue:GetTable", "glue:GetTables", "glue:GetPartition", "glue:GetPartitions"
          ],
          "Resource": [
            "arn:aws:glue:<AWS_REGION>:<AWS_ACCOUNT_ID>:catalog",
            "arn:aws:glue:<AWS_REGION>:<AWS_ACCOUNT_ID>:catalog/s3tablescatalog",
            "arn:aws:glue:<AWS_REGION>:<AWS_ACCOUNT_ID>:catalog/s3tablescatalog/<TABLE_BUCKET>",
            "arn:aws:glue:<AWS_REGION>:<AWS_ACCOUNT_ID>:database/s3tablescatalog/<TABLE_BUCKET>/<NAMESPACE>",
            "arn:aws:glue:<AWS_REGION>:<AWS_ACCOUNT_ID>:table/s3tablescatalog/<TABLE_BUCKET>/<NAMESPACE>/*"
          ]
        },
        {
          "Sid": "S3TablesRead",
          "Effect": "Allow",
          "Action": [
            "s3tables:GetTableBucket", "s3tables:ListTableBuckets",
            "s3tables:ListNamespaces", "s3tables:GetNamespace",
            "s3tables:ListTables", "s3tables:GetTable",
            "s3tables:GetTableMetadataLocation", "s3tables:GetTableData"
          ],
          "Resource": [
            "arn:aws:s3tables:<AWS_REGION>:<AWS_ACCOUNT_ID>:bucket/<TABLE_BUCKET>",
            "arn:aws:s3tables:<AWS_REGION>:<AWS_ACCOUNT_ID>:bucket/<TABLE_BUCKET>/*"
          ]
        },
        {
          "Sid": "LakeFormationCredentialVending",
          "Effect": "Allow",
          "Action": ["lakeformation:GetDataAccess"],
          "Resource": "*"
        }
      ]
    }

    Grant Lake Formation permissions

    Lake Formation permissions work as a layered grant model: you grant access at each level of the catalog hierarchy, from catalog down to table. The cross-cloud role needs DESCRIBE on the catalog and database so it can discover what exists, and SELECT plus DESCRIBE on the table so it can read the actual data. Without grants at every level, Lake Formation denies access even if the IAM policy allows it.

    If using Lake Formation, grant the bigquery-cross-cloud-role access to your tables:

    • Grant catalog permission: DESCRIBE.
    • Grant database permission: DESCRIBE.
    • Grant table permission: SELECT, DESCRIBE.

    Grant Lake Formation permissions on the cross-cloud role (one-time).

    aws lakeformation grant-permissions     --principal '{"DataLakePrincipalIdentifier":"arn:aws:iam::<AWS_ACCOUNT_ID>:role/bigquery-cross-cloud-role"}'     --resource '{"Catalog":{"Id":"<AWS_ACCOUNT_ID>:s3tablescatalog/<TABLE_BUCKET>"}}'     --permissions '["DESCRIBE"]'     --region <AWS_REGION>
    
    aws lakeformation grant-permissions     --principal '{"DataLakePrincipalIdentifier":"arn:aws:iam::<AWS_ACCOUNT_ID>:role/bigquery-cross-cloud-role"}'     --resource '{"Database":{"CatalogId":"<AWS_ACCOUNT_ID>:s3tablescatalog/<TABLE_BUCKET>","Name":"<NAMESPACE>"}}'     --permissions '["DESCRIBE"]'     --region <AWS_REGION>
    
    aws lakeformation grant-permissions     --principal '{"DataLakePrincipalIdentifier":"arn:aws:iam::<AWS_ACCOUNT_ID>:role/bigquery-cross-cloud-role"}'     --resource '{"Table":{"CatalogId":"<AWS_ACCOUNT_ID>:s3tablescatalog/<TABLE_BUCKET>","DatabaseName":"<NAMESPACE>","Name":"orders"}}'     --permissions '["SELECT","DESCRIBE"]'     --region <AWS_REGION>

    Before granting Lake Formation permissions, revoke the default IAMAllowedPrincipals access. By default, Lake Formation grants IAMAllowedPrincipals full access to all databases and tables, so you first need to revoke this to enforce fine grain access. IAMAllowedPrincipals provides backward compatibility when you start using Lake Formation permissions to secure the Data Catalog resources that were earlier protected by IAM policies for AWS Glue.

    Set up Lake Formation for external engines

    For table metadata to sync from Glue to BigLake/BigQuery, the following Lake Formation settings are required. You might notice that a similar setting also appeared during the S3 Table integration setup. The first one registers the data location and enables external access at the catalog level, while this one enables the Lake Formation credential vending mechanism at the account level for all external engines. For a clean cross-cloud setup, we recommend that you enable both.

    In the Lake Formation console, choose Administration, then Application integration settings, and then select Allow external engines to access data in Amazon S3 locations with full table access.

    Application integration settings in the Lake Formation console with external-engine access enabled

    Figure 4: Enabling external-engine access in Lake Formation application integration settings

    Connecting BigQuery to S3 Tables

    With the AWS side configured, create the federated catalog in Google Cloud that connects BigQuery to the AWS Glue IRC.

    Create the federated catalog

    Authenticate to Google Cloud using gcloud auth login, or use Cloud Shell, which is pre-authenticated. Verify the BigLake API is enabled:

    gcloud services enable biglake.googleapis.com --project="<GCP_PROJECT_ID>"

    For Lake Formation mode (with credential vending):

    gcloud alpha biglake iceberg catalogs create <FEDERATED_CATALOG_NAME> \
        --project="<GCP_PROJECT_ID>" \
        --catalog-type=federated \
        --federated-catalog-type=glue \
        --glue-aws-region=<AWS_REGION> \
        --glue-aws-role-arn=arn:aws:iam::<ACCOUNT_ID>:role/bigquery-cross-cloud-role \
        --glue-warehouse=<ACCOUNT_ID>:s3tablescatalog/<TABLE_BUCKET> \
        --primary-location=<GCP_REGION> \
        --credential-mode=vended-credentials

    The --glue-warehouse parameter uses the format <AWS_ACCOUNT_ID>:s3tablescatalog/<TABLE_BUCKET>. This tells the AWS Glue IRC to scope requests to your specific S3 Tables bucket within the federated catalog hierarchy.

    The --credential-mode=vended-credentials flag (Lake Formation mode) instructs BigQuery Lakehouse to request scoped temporary credentials from Lake Formation rather than using the role’s IAM permissions directly for data access.

    The --primary-location refers to the Google Cloud region where the federated catalog metadata is stored. Use the AWS to Google Cloud region mapping to find the corresponding GCP region for your AWS Region. For example, AWS us-east-1 maps to GCP us-east4.

    Retrieve the BigLake service account ID

    After catalog creation, Google provisions a dedicated service account for your federated catalog. Retrieve its numeric ID:

    BIGLAKE_SA_ID=$(gcloud alpha biglake iceberg catalogs describe <FEDERATED_CATALOG_NAME> \
        --project="<GCP_PROJECT_ID>" \
        --format="value(biglake-service-account-id)")
    echo $BIGLAKE_SA_ID

    Update the AWS trust policy

    Back on AWS, replace the placeholder in the IAM role’s trust policy with the actual service account ID:

    aws iam update-assume-role-policy \
        --role-name bigquery-cross-cloud-role \
        --policy-document '{
          "Version": "2012-10-17",
          "Statement": [{
            "Effect": "Allow",
            "Principal": {
              "Federated": "arn:aws:iam::<AWS_ACCOUNT_ID>:oidc-provider/accounts.google.com"
            },
            "Action": "sts:AssumeRoleWithWebIdentity",
            "Condition": {
              "StringEquals": {
                "accounts.google.com:sub": ["<BIGLAKE_SA_ID>"],
                "accounts.google.com:aud": ["<BIGLAKE_SA_ID>"]
              }
            }
          }]
        }'

    Register the service account ID in the OIDC provider’s audience list. Without this step, AWS rejects the token because the aud claim doesn’t match any registered client:

    aws iam add-client-id-to-open-id-connect-provider \
        --open-id-connect-provider-arn "arn:aws:iam::<AWS_ACCOUNT_ID>:oidc-provider/accounts.google.com" \
        --client-id "<BIGLAKE_SA_ID>"

    Set up metadata sync

    Wait 3–5 minutes for IAM changes to propagate globally, then set up background refresh:

    gcloud alpha biglake iceberg catalogs update <FEDERATED_CATALOG_NAME> \
        --project="<GCP_PROJECT_ID>" \
        --refresh-interval=300s

    The --refresh-interval (300 seconds in this example) determines how often BigQuery syncs metadata from the AWS Glue IRC. New tables and schema changes appear in BigQuery within this interval.

    Querying from BigQuery

    After the catalog refresh completes, BigQuery automatically creates external datasets corresponding to the synced namespaces. No manual CREATE SCHEMA is required.

    Verify the sync:

    gcloud alpha biglake iceberg namespaces list \
        --catalog="<FEDERATED_CATALOG_NAME>" \
        --project="<GCP_PROJECT_ID>"

    Run a query in BigQuery:

    SELECT * FROM `<GCP_PROJECT_ID>.<FEDERATED_CATALOG_NAME>.<NAMESPACE>.orders` LIMIT 1000

    Sample Query Output:

    SELECT
        customer_id,
        COUNT(*) as order_count,
        SUM(amount) as total_spend
    FROM `<GCP_PROJECT_ID>.<FEDERATED_CATALOG_NAME>.<NAMESPACE>.orders`
    GROUP BY customer_id
    ORDER BY total_spend DESC
    BigQuery query results showing order count and total spend per customer from the Amazon S3 Tables data

    Figure 5: BigQuery query results returned through Lake Formation credential vending

    BigQuery reads the Iceberg metadata to identify which Parquet data files contain relevant data. It also applies partition pruning where applicable, and fetches only the necessary files from S3 Tables managed storage.

    Schema evolution

    When new columns are added to an Iceberg table on the AWS side (through Spark, Athena, or the AWS Glue IRC), the schema change is captured in Iceberg’s metadata. On the next Lakehouse refresh cycle, BigQuery picks up the new columns automatically. No DDL changes are needed in BigQuery.

    Metadata freshness

    The s3tablescatalog catalog in AWS Glue is a federated catalog that resolves table metadata live from the S3 Tables service on each request. When a streaming job commits new data to an S3 Table, the latest metadata is immediately available through the AWS Glue IRC. BigQuery sees the update on its next refresh cycle (as configured by --refresh-interval).

    OIDC identity federation

    The trust relationship between Google Cloud and AWS uses OpenID Connect. When BigQuery Lakehouse needs to access your data, it presents a signed JWT token containing:

    • iss: accounts.google.com (the issuer)
    • sub: The BigLake service account ID (identifies which catalog is making the request)
    • aud: The same service account ID (the intended audience)

    AWS validates this token against the registered OIDC provider and trust policy conditions before issuing temporary credentials. Each federated catalog receives a unique service account ID, providing per-catalog isolation and auditability through AWS CloudTrail.

    Network path

    By default, traffic between BigQuery and AWS travels over the public internet. For workloads requiring private connectivity, Google Cloud supports Cross-Cloud Interconnect or Partner Interconnect. This helps routing queries over a dedicated network path. Refer to the Google Cloud documentation for private interconnect configuration.

    Clean up

    To avoid ongoing charges, remove the resources created in this walkthrough.

    On AWS:

    # Delete the table (if created for this walkthrough)
    aws s3tables delete-table \
        --table-bucket-arn "arn:aws:s3tables:<AWS_REGION>:<AWS_ACCOUNT_ID>:bucket/<TABLE_BUCKET>" \
        --namespace analytics --name orders --region <AWS_REGION>
    
    # Delete namespace and table bucket
    aws s3tables delete-namespace \
        --table-bucket-arn "arn:aws:s3tables:<AWS_REGION>:<AWS_ACCOUNT_ID>:bucket/<TABLE_BUCKET>" \
        --namespace <NAMESPACE> --region <AWS_REGION>
    
    aws s3tables delete-table-bucket --name <TABLE_BUCKET> --region <AWS_REGION>
    
    # Delete IAM role and OIDC provider (if no longer needed)
    aws iam delete-role --role-name bigquery-cross-cloud-role

    On Google Cloud:

    gcloud alpha biglake iceberg catalogs delete <FEDERATED_CATALOG_NAME> \
        --project="<GCP_PROJECT_ID>" --location=<GCP_REGION>

    Conclusion

    This post demonstrated how to query Amazon S3 Tables from Google BigQuery using AWS Lake Formation credential vending, where Lake Formation manages the permissions and issues temporary, scoped credentials for data access. With the open Iceberg format, you can write data once on AWS and read it from supported engines that speak Iceberg, including BigQuery.

    Together with the IAM approach covered in Part 1, two access control modes provide flexibility: IAM for teams who want a straightforward setup and Lake Formation for organizations with complex governance requirements where multiple engines need centrally managed access to the same data.

    To get started with this pattern in your environment:


    About the authors

    Lakshmi Nair

    Lakshmi Nair

    Lakshmi is a Principal Analytics Specialist Solutions Architect at AWS. She specializes in designing advanced analytics systems across industries. She focuses on crafting cloud-based data platforms, enabling real-time streaming, big data processing, and robust data governance.

    Srividya Parthasarathy

    Srividya Parthasarathy

    Srividya was a Senior Big Data Architect on the AWS Lake Formation team. She works with product team and customer to build robust features and solutions for their analytical data platform. She enjoys building data mesh solutions and sharing them with the community.

    Introducing AWS Glue 6.0 for faster and more cost-effective data integration

    Post Syndicated from Aarthi Srinivasan original https://aws.amazon.com/blogs/big-data/introducing-aws-glue-6-0-for-apache-spark/

    Organizations running large data processing pipelines want lower costs, faster job runtimes, and dependable support for open table formats, without adding operational overhead. AWS Glue, a serverless, scalable data integration service that you can use to discover, prepare, move, and integrate data from multiple sources, has now launched AWS Glue 6.0, the new version of AWS Glue that addresses these needs. This version upgrade lowers AWS Glue pricing by 30% and improves performance with AWS optimized Apache Spark 4.1. It also augments developer experience with new features and adds support for Apache Iceberg V3 specifications that are suitable for enterprise adoption. The newly available AWS Glue 6.0 makes data processing workloads more manageable, faster to run, and easier to operate.

    In this post, we cover the key capabilities of AWS Glue 6.0 and their performance benefits. We share code examples to help you take full advantage of the release, and we show you how to get started.

    AWS Glue 6.0 highlights

    AWS Glue 6.0 brings together four major improvements designed to transform how you build and run data integration workloads.

    First, it upgrades the underlying runtime to Apache Spark 4.1.1, Python 3.13, Scala 2.13, and AWS SDK for Java 2.x, delivering performance improvements that can help with faster job completion times and lower costs.

    Second, this release reduces current AWS Glue usage rate by 30%, and when combined with the performance improvements, you may realize an even lower effective cost.

    Third, AWS Glue 6.0 introduces support for more capabilities of Apache Iceberg V3. This includes the VARIANT data type with automatic shredding, deletion vectors, row lineage tracking, nanosecond timestamps, and geo types. With these capabilities, you can build modern lakehouse architectures on the latest open table format standards.

    Finally, new features like Spark Declarative Pipelines, Real-Time Mode for streaming and Python virtual environments with S3 caching are designed to further improve performance and developer experience. The following sections dive deeper into each of these areas.

    Runtime upgrades

    AWS Glue 6.0 upgrades the core runtime stack across the board, bringing newer versions of Apache Spark, Python, Scala, and the AWS SDK to your serverless data integration workloads.

    • Apache Spark 4.1.1 – AWS Glue 6.0 runs an AWS optimized build of Apache Spark 4.1.1, a major generational leap from Spark 3.5 on AWS Glue 5.1. This release introduces improvements focused on intent-driven data engineering, real-time streaming with sub-second latencies down to single-digit milliseconds for stateless tasks, faster PySpark performance, and expanded SQL features.
    • Python 3.13 – Supports Python 3.13, a stable release that brings interpreter changes, Python data model enhancements, standard library updates, and security updates.
    • Scala 2.13 – Upgrades to Scala 2.13 which includes a collections library overhaul, language and syntax feature changes, standard library additions, and compiler performance updates.

    Reduced Pricing

    AWS Glue 6.0 cuts current AWS Glue pricing by 30%. This means every job you run on AWS Glue 6.0 costs 30% less per DPU-hour compared to AWS Glue 5.1, with no changes required to your workload configuration. When you combine this pricing reduction with the performance improvements delivered by runtime upgrades, your effective cost savings can compound because jobs can complete faster and consume fewer DPU-hours on a lower price point. If you run large-scale Extract, Transform, and Load (ETL) pipelines or recurring batch workloads, this compounding effect can help reduce your monthly spend.

    To quantify the comparison, we ran the industry-standard TPC-DS benchmark at 3 TB scale on Parquet data stored in Amazon Simple Storage Service (Amazon S3), using 30 G.2X workers on AWS Glue. The following table compares the results we obtained in our tests for AWS Glue 6.0 and AWS Glue 5.1. Thus, based on TPC-DS benchmark at 3 TB scale, AWS Glue 6.0 delivers up to 36% better price performance than AWS Glue 5.1.

    . AWS Glue 6.0 AWS Glue 5.1
    Estimated Cost ($) USD 5.61 USD 8.87

    Table 1: 3TB TPC-DS benchmark comparison between AWS Glue 6.0 and AWS Glue 5.1

    Updated Open Table Format (OTF) support

    AWS Glue 6.0 ships with updated versions of all three major open table formats – Iceberg 1.11.0, Hudi 1.1.1, and Delta Lake 4.2.0 – providing better performance, improved merge-on-read capabilities, streamlined concurrency control, and expanded SQL compatibility.

    Besides supporting the latest open table format versions, AWS Glue 6.0 delivers Apache Iceberg V3 specification that is suitable for enterprise use. The highlight is Variant shredding, which AWS Glue uses to automatically decompose semi-structured data into physically optimized, columnar sub-fields, which should result in faster query read performance. Combined with deletion vectors for efficient row-level updates, UNKNOWN column types, default column values, and richer data type support, AWS Glue 6.0 is designed to make your open data lakes faster, more flexible, and more cost-efficient. AWS Glue 6.0 also adds support for geospatial data types (Geometry and Geography) and nanosecond-precision timestamps from the Apache Iceberg V3 specification, neither of which are currently supported in open-source Apache Spark 4.1. Additional features like row lineage tracking round out the Apache Iceberg V3 capabilities available on AWS Glue 6.0.

    In the following sections, we illustrate select capabilities from Apache Iceberg V3 specification on AWS Glue 6.0.

    1. VARIANT column type

    Apache Iceberg V3 introduces the Variant type to store semi-structured data (think JSON, XML, logs, and deeply nested event data) in a compact binary format. Variant shredding is designed to automatically decompose VARIANT columns into physically optimized, columnar sub-fields, facilitating predicate pushdowns and reducing scan overhead. It aims to provide simpler management of semi-structured data, without the need for complex flattening logic. With Variant type, you get the flexibility of embedding a JSON data type in your table columns while shredding is designed to help accelerate read queries and reduce costs.

    1. UNKNOWN column type

    The UNKNOWN type in Apache Iceberg V3 acts as a flexible placeholder for columns where the data type is not yet determined at the time of table creation or data ingestion. Tables can accept all-null data initially, and the column type can be upgraded later without breaking ingestion pipelines or consuming applications. This can simplify schema evolution for rapidly changing data sources. Apache Iceberg V3’s UNKNOWN column type maps to Spark 4.1’s VOID type.

    1. DEFAULT column values

    Apache Iceberg V3’s DEFAULT column values allow specifying a default value for a column in the table metadata. When you add a new column, the query engine is designed to automatically apply this default to older rows, without rewriting data or running manual backfill operations.

    The following code demonstrates creating an Apache Iceberg V3 table that uses VARIANT and UNKNOWN types, and DEFAULT values for a column.

    Prerequisites

    To get started with this code example, make sure you have the following prerequisites.

    1. An AWS account.
    2. An AWS Identity and Access Management (IAM) role with permissions for AWS Glue, the AWS Glue Data Catalog, and Amazon S3. For more information, see Setting up IAM permissions for AWS Glue. This will be the AWS Glue job execution role.
    3. An S3 bucket to store the Iceberg table data.

    Steps

    To create an AWS Glue 6.0 job, use the following steps.

    1. Log in to your AWS account and open the AWS Glue console.
    2. Create a new ETL job, with Script editor option.
      1. Choose engine as Spark in the drop-down menu.
      2. Start fresh, Create script and copy-paste the following code.
      3. Replace the demo S3 bucket name with your bucket name in the code.
    # Example pySpark script for testing few Iceberg v3's new data types
    from pyspark.sql import SparkSession
    
    CATALOG = "glue_catalog"
    DATABASE = "sample_glue6_iceberg_db"
    TABLE_NAME = "sample_glue6_table"
    TABLE = f"{CATALOG}.{DATABASE}.{TABLE_NAME}"
    TABLE_LOCATION = "s3://amzn-s3-demo-table-bucket/glue6blog-newdatatypes/"
    
    # Configure Spark to use Apache Iceberg with the AWS Glue Data Catalog.
    spark = (
        SparkSession.builder
        .appName("Glue6NewDataTypes")
        .config("spark.sql.extensions", "org.apache.iceberg.spark.extensions.IcebergSparkSessionExtensions")
        .config(f"spark.sql.catalog.{CATALOG}", "org.apache.iceberg.spark.SparkCatalog")
        .config(f"spark.sql.catalog.{CATALOG}.catalog-impl", "org.apache.iceberg.aws.glue.GlueCatalog")
        .config(f"spark.sql.catalog.{CATALOG}.io-impl", "org.apache.iceberg.aws.s3.S3FileIO")
        .config(f"spark.sql.catalog.{CATALOG}.warehouse", "s3://amzn-s3-demo-table-bucket/glue6blog-newdatatypes")
        .config("spark.sql.defaultColumn.enabled", "true")
        .getOrCreate()
    )
    
    spark.sql(f"CREATE DATABASE IF NOT EXISTS {CATALOG}.{DATABASE}")
    
    # Create an Iceberg v3 table with VARIANT, unknown, and a default value.
    # Spark's VOID type is stored as the Iceberg v3 unknown type.
    spark.sql(
        f"""
        CREATE TABLE {TABLE} (
            record_id BIGINT,
            payload VARIANT,
            reserved_field VOID,
            status STRING DEFAULT 'active'
        )
        USING ICEBERG
        LOCATION '{TABLE_LOCATION}'
        TBLPROPERTIES ('format-version' = '3')
        """
    )
    
    # Insert two rows. The omitted columns use null and the declared default.
    spark.sql(
        f"""
        INSERT INTO {TABLE} (record_id, payload)
        VALUES
        (1, parse_json('{{"event_type":"created","score":98.5}}')),
        (2, parse_json('{{"event_type":"processed","score":87.2}}'))
        """
    )
    
    # Query the row and extract values from the VARIANT column.
    spark.sql(
        f"""
        SELECT
            record_id,
            variant_get(payload, '$.event_type', 'string') AS event_type,
            variant_get(payload, '$.score', 'double') AS score,
            reserved_field,
            status
        FROM {TABLE}
        """
    ).show(truncate=False)
    
    spark.stop()
    1. Provide the following details in the Job details tab.
      1. A Name for the job.
      2. The IAM role you have from Prerequisites (2) for the IAM role of the job.
      3. Choose Glue 6.0 for the Glue version.
      4. Leave the rest as defaults.The following screenshot shows the Job details tab with illustrated values in the AWS Glue console.

        AWS Glue Job details tab with the Glue version set to Glue 6.0 and other settings left as defaults

        Figure 1: Job details tab with the Glue version set to Glue 6.0

      5. Scroll down. Under Advanced properties, for Job parameters, add the following additional Job parameter key-value pair:--datalake-formats=icebergThe following screenshot shows the Job parameters with the illustrated key-value pair in the AWS Glue console.

        Advanced properties section showing the Job parameters key –datalake-formats set to the value iceberg

        Figure 2: Job parameters with the datalake-formats key set to iceberg

    2. Save the job and choose Run.
    3. After the job is completed successfully, from the Runs tab – Run details, you can inspect the Output logs that take you to the logs in the Amazon CloudWatch console. The following shows the sample output for the SELECT query in the script.
    +---------+----------+-----+--------------+------+
    |record_id|event_type|score|reserved_field|status|
    +---------+----------+-----+--------------+------+
    |1        |created   |98.5 |NULL          |active|
    |2        |processed |87.2 |NULL          |active|
    +---------+----------+-----+--------------+------+

    Notice that we inserted two rows with values only in the record_id and the variant column. Variant column inserts were done using parse_json(). The reserved_field is of VOID type, hence returns NULL values. The status column is declared with a default active value and returns active, since the column was omitted during the insert operation.

    1. Deletion Vectors
      Apache Iceberg V3 replaces the traditional positional delete files used in Apache Iceberg V2 to deletion vectors. This change can help improve Merge-on-Read (MoR) performance. This shift replaces heavy, multi-file Parquet reads with highly compressed, direct binary bitmaps that can provide lower storage overhead and faster reads on delete-heavy tables. In scenarios with heavy table updates, such as streaming change data capture (CDC) from operational databases, Apache Iceberg V3 can offer read performance advantage over Apache Iceberg V2.

      To validate the performance of deletion vectors, we created two identical AWS Glue streaming jobs and ingested the events into two different Iceberg tables, one in Apache Iceberg V2 and another in Apache Iceberg V3 format. The streaming CDC events were approximately 150,000 events per second, merge-on-read, update-heavy. Every micro-batch writes row-level deletes. We froze both tables at the same delete-heavy state and disabled compaction, leaving the tables with roughly 1.7 million rows in valid state out of the 26.4 million physical rows. The following table summarizes the read performance latency of the two Iceberg tables. We observed in this testing that reading from the delete-heavy Apache Iceberg V3 is at least 1.5 times faster than the reading from a similar Apache Iceberg V2 table. For larger enterprise scale Apache Iceberg V3 tables, the read performance could improve further.

    Read latency comparison showing Apache Iceberg V3 deletion vectors reading at least 1.5 times faster than Apache Iceberg V2 delete files

    Table 2 – Read latency comparison between Apache Iceberg V2 delete files and Apache Iceberg V3 deletion vectors

    New ETL features

    AWS Glue 6.0 introduces several additional capabilities designed to simplify how you build and manage data pipelines, some of which are discussed in the following list.

    • Spark Declarative Pipelines (SDP) where you define the outcomes you want for your entire data pipelines in a declarative fashion with SQL statements or Python decorators while AWS Glue handles execution flow, dependency resolution, parallelism, checkpointing, CDC, and recovery automatically. This helps you focus on business logic rather than orchestration plumbing.
    • Real-Time Mode (RTM) for streaming delivers continuous execution for Structured Streaming with sub-second latencies, down to single-digit milliseconds for stateless tasks. This can help support real-time use cases like fraud detection, live dashboards, and event-driven architectures without managing dedicated streaming infrastructure.
    • Arrow-Native UDFs/UDTFs execute Python functions directly on PyArrow batches without Pandas conversion overhead, which can result in faster performance for custom transformation logic at scale.
    • Recursive Common Table Expressions (CTE) adds WITH RECURSIVE queries natively, allowing graph traversals and hierarchical queries without workarounds or external libraries.
    • Python data source filter pushdown evaluates filters at the data source designed to minimize data movement, reduce the volume of data scanned, and improve job performance.
    • With Python virtual environments and S3 caching, you can provide pre-built Python dependencies, which should result in reduced startup latency for AWS Glue jobs by eliminating runtime dependency resolution. For existing jobs that use --additional-python-modules, no action is required. AWS Glue automatically handles the conversion to virtual environments when your job runs on AWS Glue 6.0.

    Dependent library upgrades

    The following table summarizes the key runtime and library version upgrades on AWS Glue 6.0.

    Feature Glue 6.0 Glue 5.1
    Spark 4.1.1-amzn-0 3.5.6-amzn-1
    Python 3.13.14 3.11.15
    Scala 2.13.17 2.12.18
    AWS SDK for Java 2.44.6
    (Version 1.x removed)
    2.35.5
    Boto3 1.42.84 1.40.61
    Java 17.0.20 17.0.19
    Iceberg 1.11.0 1.10.0
    Hudi 1.1.1 .0.2
    Delta Lake 4.2.0 3.3.2
    AWS Glue Data Catalog client 4.11.0 4.9.0
    EMR DynamoDB connector 6.1.0 5.7.0
    Arrow 18.3.0 2.0.1
    Hive 2.3.10-amzn-1 2.3.9-amzn-4

    Table 3: Runtime and library version comparison across AWS Glue 6.0 and AWS Glue 5.1

    Getting started

    To get started with AWS Glue 6.0, you can use one of the following methods.  

    Clean up

    To avoid incurring costs, clean up the resources you created for this post.

    1. Delete the Data Catalog database and the Iceberg table.
    2. Delete the data and metadata folders of the Iceberg table from your S3 bucket.
    3. Delete the AWS Glue job and the AWS Glue job execution IAM role.

    Conclusion

    AWS Glue 6.0 is designed to be faster, more cost-effective, and easier to use for building your open data lakehouse architectures and orchestrating your data pipelines. In this post, we discussed the key highlights of AWS Glue 6.0 and illustrated usage of Apache Iceberg V3 features with code samples. You can create new AWS Glue jobs on AWS Glue 6.0 or migrate your existing AWS Glue jobs to benefit from these improvements.

    With Apache Spark 4.1.1, Apache Iceberg V3, Python 3.13, upgraded open table format libraries, and new streaming capabilities, AWS Glue 6.0 aims to help you build new data applications or to operate your existing data pipelines more efficiently and with less maintenance overhead.

    We encourage you to test AWS Glue 6.0 in your development environment today. Check out this blog that talks about upgrading your AWS Glue jobs to AWS Glue 6.0. Also, in the coming days and weeks, look out for blogs on individual topics illustrating various features of Spark 4.1.1 and Apache Iceberg V3 on AWS Glue 6.0.

    Acknowledgements: We thank the numerous engineers and leaders who helped build AWS Glue 6.0 to support customers with a highly performant Spark runtime and other value-added capabilities.


    About the authors

    Aarthi Srinivasan

    Aarthi Srinivasan

    Aarthi is a Senior Big Data Architect working on data, analytics and GenAI topics with the worldwide specialist org at AWS. She works with AWS customers and partners to architect open data lake solutions, enhance product features, and establish best practices for data governance and analytics services adoption.

    Shrey Malpani

    Shrey Malpani

    Shrey is a Senior Product Manager Technical at Amazon Web Services (AWS), where he works at the intersection of distributed data processing and data integration. He is focused on building and scaling data integration and data management capabilities across services like AWS Glue, Amazon EMR, and Amazon Redshift that help customers build AI-ready data platforms for their analytics and machine learning workflows.

    Angel Conde Manjon

    Angel Conde Manjon

    Angel is a Senior Solutions Architect at AWS where he helps partners develop businesses centered on Data and AI. He has previously worked on research related to Data Analytics and Artificial Intelligence in diverse European research projects. Angel is also an Apache Iceberg contributor.

    Peter Tsai

    Peter Tsai

    Peter is a Software Development Engineer at AWS, where he enjoys solving challenges in the design and performance of the AWS Glue runtime. In his leisure time, he enjoys hiking and cycling.

    Danylo Prozorov

    Danylo Prozorov

    Danylo is a Software Development Engineer at AWS Glue, where he works on building data integration and generative AI solutions for analytics customers. Outside of work, he enjoys sports, hiking, riding motorcycles, and building his overland rig.

    Bo Li

    Bo Li

    Bo is a Senior Software Development Engineer on the AWS Glue team. He is devoted to designing and building end-to-end solutions to address customers’ data analytic and processing needs with cloud-based, data-intensive and GenAI technologies.

    Kartik Panjabi

    Kartik Panjabi

    Kartik is a Software Development Manager on the AWS Glue team. His team builds generative AI features for the Data Integration and distributed system for data integration.

    Mohit Saxena

    Mohit Saxena

    Mohit leads AWS Glue and AWS Data Analytics agentic AI initiatives that help customers build and operate big data applications on Apache Spark, Amazon S3, and cloud data lakes and warehouses, spanning across AWS Glue, Amazon EMR, and Amazon Athena.

    Upgrade AWS Glue jobs to Glue 6.0 with AI-powered Spark upgrades

    Post Syndicated from Prasad Nadig original https://aws.amazon.com/blogs/big-data/upgrade-aws-glue-jobs-to-glue-6-0-with-ai-powered-spark-upgrades/

    Upgrading PySpark jobs to a new Apache Spark major version can introduce breaking changes. Removed configuration keys, stricter type casting, and Python library incompatibilities can cause runtime failures or silent behavior differences. With AWS Glue 6.0 now running Apache Spark 4.1 and Python 3.13, you need a reliable way to migrate your existing jobs while validating correctness.

    In this post, we walk through upgrading a PySpark ETL job from AWS Glue 5.1 to AWS Glue 6.0. We use the generative AI upgrades for Apache Spark in the AWS Glue console. The upgrade analysis automatically identifies incompatibilities, iteratively resolves them, validates the result with data quality checks, and presents recommended changes for your review. AWS Glue 6.0 also delivers up to 36% better price performance* along with Iceberg v3, Spark Declarative Pipelines, Real-Time Mode, and Arrow-native Python UDFs.

    What changes with AWS Glue 6.0

    AWS Glue 6.0 runs Apache Spark 4.1, which introduces several behavioral changes from the Spark 3.5 runtime used in AWS Glue 5.1:

    Behavior Spark 3.5 (AWS Glue 5.1) Spark 4.1 (AWS Glue 6.0)
    ANSI SQL mode Disabled by default Enabled by default
    Legacy Parquet datetime configs Supported Removed (renamed)
    Python runtime 3.11 3.13

    Beyond version compatibility, AWS Glue 6.0 also introduces:

    • Apache Iceberg v3 with VARIANT Shredding for efficient semi-structured data handling.
    • Spark Declarative Pipelines — agent-authorable ETL.
    • Real-Time Mode — single-digit millisecond streaming latency.
    • Arrow-native Python UDFs (PyArrow) for improved performance.
    • Built-in observability with structured metrics and enhanced Spark UI.
    • Up to 36% better price performance compared to AWS Glue 5.1*.

    These runtime changes mean your existing AWS Glue jobs might encounter removed configuration keys, stricter type casting behavior, or Python package version incompatibilities when running on AWS Glue 6.0. Fixing these manually is time-consuming and error-prone. The following sections show how the generative upgrade analysis handles this automatically.

    The sample job

    Our example is a daily ecommerce order analytics pipeline running on AWS Glue 5.1:

    What the job does:

    • Ingests 10,000 orders from Parquet files with INT96 timestamps (including pre-1900 historical dates from a legacy system migration).
    • Computes revenue metrics by casting string prices to numeric values and calculating line totals with discounts and tax.
    • Segments customers using recency, frequency, and monetary (RFM) scoring through mapInPandas with pandas and scikit-learn.
    • Writes enriched results back to Amazon Simple Storage Service (Amazon S3).

    Job configuration (AWS Glue 5.1):

    Glue version: 5.1
    Worker type: G.1X
    Workers: 10
    Python modules: pandas==2.2.2, scikit-learn==1.5.0, numpy==1.26.4
    Spark configs:
      spark.sql.legacy.parquet.datetimeRebaseModeInWrite=LEGACY
      spark.sql.legacy.parquet.int96RebaseModeInWrite=LEGACY
      spark.sql.parquet.datetimeRebaseModeInRead=LEGACY
      spark.sql.parquet.int96RebaseModeInRead=LEGACY

    This job runs successfully on AWS Glue 5.1. The following sections walk through how the upgrade analysis identifies and resolves incompatibilities when upgrading this job to AWS Glue 6.0. Before starting, confirm you have the prerequisites in place.

    Prerequisites

    • An AWS account with access to the AWS Glue console.
    • An existing AWS Glue job on version 5.1 or earlier with at least one successful run.
    • An Amazon S3 path for storing the upgrade analysis results.

    Running the upgrade analysis from the console

    The following steps walk through the upgrade analysis workflow using the AWS Glue console.

    Step 1: Select your job

    Navigate to your job in the AWS Glue Studio console. Confirm the job has a successful run history on AWS Glue 5.1 before starting the upgrade analysis.

    AWS Glue Studio job run history showing a successful run on AWS Glue 5.1

    Figure 1: Job run status for the job on AWS Glue 5.1

    Step 2: Start the upgrade analysis

    From the job’s Actions menu, select Upgrade with generative AI. Configure the following:

    • Target AWS Glue version: 6.0.
    • Results S3 path: An S3 location where the analysis stores its artifacts and recommendations.
    Actions menu in AWS Glue Studio with the Upgrade with generative AI option

    Figure 2: The Upgrade with generative AI option in the Actions menu

    Configure the target AWS Glue version and the S3 results path, then choose Run.

    Upgrade window with the target AWS Glue version set to 6.0 and an Amazon S3 results path

    Figure 3: The Upgrade with generative AI window for setting the target AWS Glue version and results path

    Choose Run. The analysis begins by running your job on AWS Glue 5.1 to establish a baseline. It then iteratively tests the job on AWS Glue 6.0, identifies failures, applies recommended fixes, and validates the job. If the upgrade analysis cannot resolve an incompatibility within its attempt budget, the analysis stops and reports the unresolved issue for manual review. Your original job remains unchanged.

    Note: The upgrade analysis executes your job multiple times (one baseline run plus one or more validation attempts), and each run consumes Data Processing Units (DPUs). For large or long-running jobs, consider using the run configuration option to specify fewer workers or a smaller dataset to optimize analysis cost.

    Step 3: Monitor progress

    The console displays the analysis progressing through multiple validation attempts. Each attempt either succeeds or fails with a specific error, and the upgrade analysis uses that error signal to determine and apply the appropriate fix for the next attempt.

    Upgrade analysis progress showing multiple validation attempts with success and failure states

    Figure 4: Upgrade analysis progress across multiple validation attempts

    What the upgrade analysis found and fixed

    The analysis completed in four validation attempts, identifying and resolving three distinct incompatibilities. The upgrade uses deterministic migration rules for known config changes, and automated diagnosis for runtime or code errors.

    Iteration 1: Removed Parquet legacy configuration

    The analysis first sanitizes any Spark configurations that were removed in Spark 4.1. Our job used spark.sql.legacy.parquet.datetimeRebaseModeInWrite and spark.sql.legacy.parquet.int96RebaseModeInWrite, which no longer exist.

    Migration rule applied: The SQL configs with the spark.sql.legacy prefix were removed in Spark 4.1. They have been renamed to their non-legacy equivalents, preserving the original values.

    Recommended change:

    Before:
    spark.sql.legacy.parquet.datetimeRebaseModeInWrite=LEGACY
    spark.sql.legacy.parquet.int96RebaseModeInWrite=LEGACY
    
    After:
    spark.sql.parquet.datetimeRebaseModeInWrite=LEGACY
    spark.sql.parquet.int96RebaseModeInWrite=LEGACY

    The read-side configs (datetimeRebaseModeInRead, int96RebaseModeInRead) already used the correct non-legacy names and required no changes.

    However, with this fix applied, the validation run still failed because the Python module installation encountered an error on the AWS Glue 6.0 image.

    Iteration 2: Python module version incompatibility

    The pinned module versions (pandas==2.2.2, scikit-learn==1.5.0, numpy==1.26.4) could not be installed in the AWS Glue 6.0 Python 3.13 environment.

    Error:

    LAUNCH ERROR | Installation of Additional Python Modules failed

    Recommended change: The upgrade analysis updated the version specifications from exact pins to minimum version constraints, allowing pip to resolve compatible versions for Python 3.13:

    Before: pandas==2.2.2, scikit-learn==1.5.0, numpy==1.26.4
    After:  pandas>=2.1.0, scikit-learn>=1.3.0, numpy>=1.24.0

    With modules installing successfully, the job launched on AWS Glue 6.0 but encountered a runtime error.

    Iteration 3: ANSI mode strict type casting

    Spark 4.1 enables ANSI SQL mode by default (spark.sql.ansi.enabled=true). Our revenue calculation casts string prices to double, but approximately 1.8% of records contain non-numeric placeholder values such as “N/A”, “pending”, or “null” from the upstream system. From a business perspective, this meant 1.8% of revenue orders were silently excluded from revenue metrics. This data quality issue was invisible to the original pipeline.

    On AWS Glue 5.1 (ANSI mode off), cast("N/A" as double) silently returns null. On AWS Glue 6.0 (ANSI mode on), this throws an exception:

    Error:

    NumberFormatException: [CAST_INVALID_INPUT] The value 'null' of the type
    "STRING" cannot be cast to "DOUBLE" because it is malformed. Correct the
    value as per the syntax, or change its target type. Use try_cast to
    tolerate malformed input and return NULL instead. SQLSTATE: 22018

    Migration rule applied: As of Spark 4.1, spark.sql.ansi.enabled is on by default. Casting a malformed value now raises CAST_INVALID_INPUT instead of returning NULL. The upgrade analysis resolved this by updating the script to use try_cast(), which safely returns NULL for malformed input while preserving ANSI mode protections for the rest of the job.

    Recommended change:

    Before (AWS Glue 5.1):

    F.col("unit_price").cast("double")

    After (AWS Glue 6.0, fixed by the upgrade analysis):

    F.expr("try_cast(unit_price as double)")

    This is a targeted fix that handles the known dirty data without disabling ANSI mode globally, keeping overflow detection and type safety active throughout the job.

    Final validation and data quality check

    After applying all three fixes, the analysis ran the job on AWS Glue 6.0 one final time and performed a data quality comparison between the AWS Glue 5.1 baseline output and the AWS Glue 6.0 output.

    Result: The job completed successfully and all data validations passed with no mismatches detected between the source and target outputs.

    Completed upgrade analysis status with links to the results output path in Amazon S3

    Figure 5: Final analysis status with links to the results output path in Amazon S3

    Reviewing the upgrade summary

    The analysis produces a detailed summary stored in your S3 results path. This summary documents each validation attempt, the errors encountered, the migration rules applied, and the recommended configuration changes:

    s3://amzn-s3-demo-bucket/scripts/auto-upgrade/ja-{analysis-id}/
        summary/
            summary.md                       # Full iteration-by-iteration report
            data_validation_summary.md       # Data quality comparison results
        artifact/
            attempt_N/
                script/main.py               # Recommended script (if modified)
                job_config_modifications.json  # Recommended parameter changes
                requirements.txt             # Updated dependency versions

    The following is a snippet from the upgrade summary (summary.md) showing the recommended changes and validation attempt details:

    The summary documents each validation attempt, the changes applied, and the data quality results.

    Upgrade summary showing validation attempts, applied changes, and data quality comparison results

    Figure 6: Upgrade summary snippet showing validation attempt details, data quality, and analysis results

    After reviewing the recommendations, accept the changes to upgrade your job to AWS Glue 6.0. This updates your job definition with the recommended configuration, including the renamed Spark configs, updated module versions, and any script modifications. Because the analysis has already validated the job on AWS Glue 6.0 and confirmed data quality parity with the original, your job is ready for production.

    After reviewing the recommendations, you can apply the upgraded script to your job.

    AWS Glue Studio prompt to apply the upgraded script to the job

    Figure 7: The option to apply the upgraded script to the job

    Choose Apply to confirm the upgrade.

    Confirmation dialog with the Apply button to upgrade the job to AWS Glue 6.0

    Figure 8: The Apply button that confirms upgrading the job to AWS Glue 6.0

    After applying, the job definition reflects the new AWS Glue version.

    AWS Glue job details showing version 6.0 after applying the upgrade

    Figure 9: The AWS Glue version for the job after applying the upgrade

    Python virtual environments in AWS Glue 6.0

    AWS Glue 6.0 introduces --python-virtual-env-storage-prefix, a service-managed virtual environment with S3 caching that simplifies Python dependency management.

    For existing jobs that use --additional-python-modules, no action is required. AWS Glue automatically handles the conversion to virtual environments when your job runs on AWS Glue 6.0. Your jobs continue to work without any changes.

    For new jobs on AWS Glue 6.0, we recommend using the virtual environment approach:

    {
        "DefaultArguments": {
            "--python-virtual-env-storage-prefix": "s3://amzn-s3-demo-bucket/glue-venv-cache/",
            "--additional-python-modules": "pandas>=2.1.0,scikit-learn>=1.3.0,numpy>=1.24.0"
        }
    }

    How it works:

    • On the first run, AWS Glue installs your modules into a virtual environment, packages it, and caches the result to your specified S3 path (approximately 15–30 seconds of additional startup time).
    • On subsequent runs, AWS Glue downloads and extracts the cached virtual environment instead of running pip install.
    • The cache is automatically invalidated when your module list, versions, or AWS Glue version changes.

    This approach provides faster cold starts after the first run, requires no Docker image management (unlike --python-virtual-env), and is entirely service-managed with no maintenance burden.

    Conclusion

    The generative upgrade analysis identified and resolved three distinct compatibility issues in our AWS Glue 5.1 job, so the job now runs successfully on AWS Glue 6.0 with Apache Spark 4.1:

    • The upgrade analysis renamed legacy Parquet datetime configuration keys (removed in Spark 4.1) to their current equivalents.
    • The upgrade analysis updated Python module version specifications that were incompatible with Python 3.13 to use flexible minimum version constraints.
    • The upgrade analysis addressed the new ANSI SQL mode default (which causes runtime failures on malformed data) with a targeted fix using try_cast() to safely handle non-numeric values while preserving ANSI mode protections.

    The analysis validated that the upgraded job produces output consistent with the original, and presented all changes as recommendations for review before applying them to your job.

    Next steps

    After you have reviewed and accepted the upgrade changes, you can delete the analysis results stored in your S3 results path.

    *Based on 3TB TPC-DS benchmark comparing AWS Glue 6.0 to AWS Glue 5.1.


    About the authors

    Prasad Nadig

    Prasad Nadig

    Prasad is a Senior Analytics Specialist Solutions Architect at Amazon Web Services (AWS), specializing in large-scale data analytics and AI. Prasad partners with customers to design, migrate, and modernize their analytics platforms on AWS into scalable, cost-effective solutions, with deep expertise in data lakes, data warehousing, distributed processing, and performance tuning at petabyte scale.

    Shrey Malpani

    Shrey Malpani

    Shrey is a Senior Product Manager Technical at Amazon Web Services (AWS), where he works at the intersection of distributed data processing and data integration. He is focused on building and scaling data integration and data management capabilities across services like AWS Glue, Amazon EMR, and Amazon Redshift that help customers build AI-ready data platforms for their analytics and machine learning workflows.

    Rishabh Nair

    Rishabh Nair

    Rishabh is a Software Development Engineer in the AWS analytics organization, where he combines generative AI with distributed systems to build agentic workflows that modernize large-scale data processing. He is passionate about the infrastructure that makes these workflows reliable and scalable for customers.

    Keerthi Chadalavada

    Keerthi Chadalavada

    Keerthi is a Senior Software Development Engineer in the AWS analytics organization. She focuses on combining generative AI and data integration technologies to design and build comprehensive solutions for analytics and data engineering workloads.

    Build a unified AI agent architecture with DynamoDB and Bedrock

    Post Syndicated from Dhananjay Karanjkar original https://aws.amazon.com/blogs/architecture/build-a-unified-ai-agent-architecture-with-dynamodb-and-bedrock/

    Teams building AI agents on AWS often face a fragmented data architecture: operational data lives in Amazon DynamoDB while vector embeddings for semantic search sit in a separate, purpose-built vector store. This duplication increases infrastructure cost, adds synchronization complexity, and widens the window for stale retrieval results. With the general availability of native vector search in Amazon DynamoDB (launched August 5, 2026), you can now store embeddings alongside your operational data in the same table. You query them using the SearchVectors API operation.

    In this post, I show you how to build a unified AI agent architecture where an Amazon Bedrock agent uses a single DynamoDB table for both structured lookups and semantic similarity search. The agent calls AWS Lambda action groups that invoke SearchVectors for natural language retrieval and standard DynamoDB APIs for create, read, update, and delete (CRUD) operations. An Amazon DynamoDB Streams pipeline automatically generates embeddings using Amazon Titan Text Embeddings V2 whenever content changes. This keeps the vector index synchronized without manual intervention.

    Use case

    Consider a technical knowledge management platform where a team maintains hundreds of internal documents: runbooks, architecture decision records, and troubleshooting guides. Team members interact with a conversational agent to find relevant content (“What’s our retry strategy for payment failures?”), retrieve specific documents by ID, or update existing entries.

    Without native vector search, this architecture requires a DynamoDB table for document storage plus a separate vector database (or Amazon OpenSearch Service cluster) for semantic retrieval. The Amazon DynamoDB Streams pipeline must write to both stores, and the agent must route requests to the correct backend. With DynamoDB vector search, you collapse this into a single table and reduce operational overhead.

    Solution overview

    This solution uses a single-table design in DynamoDB that serves two access patterns: key-value lookups for operational data and approximate nearest neighbor (ANN) search for semantic queries. A Bedrock agent orchestrates user interactions and routes requests to the appropriate action group function.

    The following list summarizes the core components:

    • DynamoDB table with vector index stores documents, metadata, and 1,024-dimension embeddings in one place.
    • Bedrock agent handles conversation orchestration, tool selection, and response synthesis.
    • Action group Lambda executes semantic search (using SearchVectors) and CRUD operations against the same table.
    • Embedding pipeline Lambda (triggered by DynamoDB Streams) generates embeddings for new or modified content using Amazon Titan Text Embeddings V2.

    Architecture

    The following diagram illustrates the data flow through the unified architecture.

    Architecture diagram showing a user query flowing to an Amazon Bedrock agent, which invokes action group Lambda functions that call the DynamoDB SearchVectors API and standard CRUD APIs, with DynamoDB Streams triggering an embedding pipeline Lambda that generates vectors with Amazon Titan Text Embeddings V2

    Figure 1: Unified AI agent architecture using DynamoDB vector search and Amazon Bedrock

    The numbered steps describe the data and request flow:

    1. A user sends a natural language query to the Bedrock agent.
    2. The agent analyzes the request and invokes the appropriate action group Lambda function.
    3. For semantic search, the action group Lambda generates a query embedding using Amazon Titan Text Embeddings V2.
    4. The Lambda function calls the DynamoDB SearchVectors API (or standard CRUD APIs for operational lookups) against the single table with vector index.
    5. When new content is written to the table, DynamoDB Streams captures the change.
    6. DynamoDB Streams triggers the embedding pipeline Lambda.
    7. The embedding pipeline Lambda calls Amazon Titan Text Embeddings V2 to generate a vector for the new content and writes it back to the same DynamoDB item, where the vector index automatically indexes it.

    Prerequisites

    To implement this architecture in your account, you need the following:

    • An AWS account with permissions to create DynamoDB tables, Lambda functions, Bedrock agents, and IAM roles.
    • DynamoDB Streams enabled on the table with StreamViewType set to NEW_AND_OLD_IMAGES (the embedding pipeline compares old and new content to prevent a write loop).
    • Access to the Amazon Titan Text Embeddings V2 model (amazon.titan-embed-text-v2:0) enabled in Amazon Bedrock model access.
    • Access to an Anthropic Claude or Amazon Nova model for the Bedrock agent foundation model (check model support by Region).
    • Python 3.12 or later (for Lambda function code).

    Implementation

    This section walks through the key components of the architecture.

    Designing the single-table schema

    The table uses a composite primary key (entity_id as partition key, sk as sort key) and stores embeddings as a list of numbers:

    # Table schema overview
    # PK: entity_id (S) - unique document identifier
    # SK: sk (S) - sort key for item versioning
    # Attributes: title, content, category, metadata, embedding (L of N)

    The vector index partitions search results by the category attribute. Choose a partition key with moderate cardinality that matches your query patterns. A very low-cardinality key (a handful of values) concentrates data in few partitions and limits throughput scaling, while a unique-per-item key leaves no neighbors to compare. For multi-tenant workloads, tenant_id is usually the right partition key. For more information, refer to the DynamoDB vector search best practices.

    The following AWS Command Line Interface (AWS CLI) command creates the vector index on an existing table:

    aws dynamodb update-table \
        --table-name unified-agent-data \
        --stream-specification StreamEnabled=true,StreamViewType=NEW_AND_OLD_IMAGES \
        --attribute-definitions \
            AttributeName=category,AttributeType=S \
        --vector-index-updates \
        '[{"Create": {
            "IndexName": "content-embedding-index",
            "VectorAttribute": {"AttributeName": "embedding"},
            "Dimensions": 1024,
            "DistanceFunction": "COSINE",
            "SearchSchema": [
                {"AttributeName": "category", "SearchSchemaElementType": "HASH"}
            ],
            "Projection": {"ProjectionType": "INCLUDE", "NonKeyAttributes": ["title", "category"]}
        }}]'

    After creating the index, wait for it to become searchable. Poll DescribeTable until IndexStatus is ACTIVE and Backfilling is no longer true. The first few searches after the index reports ACTIVE can still return ValidationException because SearchVectors is served by a dedicated search endpoint. Treat these as retryable rather than as a failure.

    aws dynamodb describe-table --table-name unified-agent-data \
        --query 'Table.VectorIndexes[?IndexName==`content-embedding-index`].[IndexStatus,Backfilling]'

    Key constraints to keep in mind:

    • DynamoDB vector indexes require on-demand capacity mode (provisioned mode isn’t supported).
    • Maximum five vector indexes per table, with up to 4,096 dimensions each.
    • The SearchSchema HASH attribute is mandatory in every SearchConditionExpression.
    • Only equality operators are supported in search conditions.
    • SearchVectors responses are limited to 16 MB and don’t support pagination. Project only the attributes you need and keep TopK modest to stay within this limit.
    • Items missing the SearchSchema HASH attribute (category in this example) are silently excluded from the vector index while remaining in the base table.

    Building the action group Lambda

    The action group Lambda handles both semantic search and operational lookups. The agent invokes it with a function name and parameters based on the tool definition.

    The semantic search function generates a query embedding and calls SearchVectors. This index uses COSINE distance, where lower scores indicate greater similarity. Name the field accordingly so the agent doesn’t invert the ranking:

    def semantic_search(query: str, category: str, max_results: int = 5):
        embedding = generate_embedding(query)
        results = dynamodb.search_vectors(
            TableName=TABLE_NAME,
            IndexName=INDEX_NAME,
            SearchVector=[{"N": str(v)} for v in embedding],
            TopK=min(max_results, 100),
            SearchConditionExpression="category = :cat",
            ExpressionAttributeValues={":cat": {"S": category}},
        )
        return [
            {"entity_id": r["Item"]["entity_id"]["S"],
             "title": r["Item"].get("title", {}).get("S", ""),
             "distance": r["Score"]}  # COSINE: lower = more similar
            for r in results.get("SearchResults", [])
        ]

    The generate_embedding helper calls Amazon Titan Text Embeddings V2:

    def generate_embedding(text: str) -> list[float]:
        response = bedrock_runtime.invoke_model(
            modelId="amazon.titan-embed-text-v2:0",
            body=json.dumps({
                "inputText": text,
                "dimensions": 1024,
                "normalize": True
            }),
        )
        return json.loads(response["body"].read())["embedding"]

    The Lambda handler routes requests based on the function name passed by the Bedrock agent:

    def handler(event, context):
        function = event.get("function")
        parameters = {p["name"]: p["value"] for p in event.get("parameters", [])}
        if function == "semantic_search":
            result = semantic_search(parameters["query"], parameters["category"])
            body = json.dumps({"results": result})
        elif function == "get_item_details":
            body = json.dumps(get_item_details(parameters["entity_id"]))
        else:
            body = json.dumps({"error": f"Unknown function: {function}"})
        return {
            "messageVersion": "1.0",
            "response": {
                "actionGroup": event["actionGroup"],
                "function": function,
                "functionResponse": {"responseBody": {"TEXT": {"body": body}}}
            }
        }

    Automating embeddings with DynamoDB Streams

    The embedding pipeline Lambda triggers on INSERT and MODIFY events. It generates an embedding for new or changed content and writes it back to the same item:

    def handler(event, context):
        for record in event["Records"]:
            if record["eventName"] not in ("INSERT", "MODIFY"):
                continue
            new_image = record["dynamodb"]["NewImage"]
            old_image = record["dynamodb"].get("OldImage", {})
            content = new_image.get("content", {}).get("S")
            if not content:
                continue
            # Prevent infinite loop: skip if content hasn't changed
            if "embedding" in new_image and old_image.get("content") == new_image.get("content"):
                continue
            embedding = generate_embedding(content)
            dynamodb.update_item(
                TableName=TABLE_NAME,
                Key={"entity_id": new_image["entity_id"], "sk": new_image["sk"]},
                UpdateExpression="SET embedding = :emb",
                ExpressionAttributeValues={
                    ":emb": {"L": [{"N": str(v)} for v in embedding]}
                },
            )

    The infinite-loop guard is critical. Without it, the Lambda writes back an embedding, which triggers another Streams event, which triggers another embedding generation, and so on. The check compares the content field between old and new images, skipping processing when only the embedding attribute changed. This guard requires StreamViewType = NEW_AND_OLD_IMAGES. Without it, OldImage is empty and the guard never fires.

    For production use, configure the event source mapping with ReportBatchItemFailures so that only failed records are retried. Add an Amazon Simple Queue Service (Amazon SQS) dead-letter queue (or on-failure destination) for records that repeatedly fail. Retry Amazon Bedrock InvokeModel calls with exponential backoff to handle throttling.

    Defining the agent tool schema

    The Bedrock agent needs a function schema that describes the available tools. This tells the agent when and how to call each function:

    {
        "functions": [
            {
                "name": "semantic_search",
                "description": "Search documents by meaning using natural language. Returns results ranked by COSINE distance (lower = more similar).",
                "parameters": {
                    "query": {"type": "string", "required": true,
                              "description": "Natural language search query"},
                    "category": {"type": "string", "required": true,
                                 "description": "Document category to search within"}
                }
            },
            {
                "name": "get_item_details",
                "description": "Retrieve a specific document by its unique ID.",
                "parameters": {
                    "entity_id": {"type": "string", "required": true,
                                  "description": "Unique document identifier"}
                }
            }
        ]
    }

    When to use this pattern

    This unified architecture works best when your application already uses DynamoDB as its primary operational store and you want to add semantic search without managing a separate service. Consider the following decision points:

    • Use this pattern when your application meets these conditions:
      • Documents update frequently and must be immediately searchable.
      • Your dataset fits within the DynamoDB vector index constraints.
      • You want to minimize infrastructure components.
    • Use Amazon Bedrock Knowledge Bases when your source data lives in Amazon Simple Storage Service (Amazon S3), you need managed chunking and ingestion, or you don’t need real-time index updates tied to operational writes.
    • Use Amazon OpenSearch Service when you need advanced search features (range filters, aggregations, faceted search), your queries require more than equality-based filtering, or you need results beyond the 100-item TopK limit.

    Security considerations

    The following list highlights the key security aspects of this architecture:

    • Least-privilege IAM policies: Scope dynamodb:SearchVectors to the specific index ARN (arn:aws:dynamodb:{region}:{account}:table/{table}/index/{index}). The embedding Lambda needs only dynamodb:UpdateItem, not search permissions.
    • No fine-grained access control for SearchVectors: DynamoDB condition keys like dynamodb:LeadingKeys don’t apply to the SearchVectors API. For multi-tenant workloads, use the SearchSchema HASH partition key to scope queries by tenant, or use separate tables for strict isolation.
    • Encryption at rest: DynamoDB encrypts data including vector embeddings using your choice of AWS owned keys, AWS managed keys, or customer managed keys through AWS Key Management Service (AWS KMS).
    • Transport encryption: All SearchVectors traffic uses TLS. The API routes to a dedicated search endpoint that the AWS SDKs handle automatically.
    • Bedrock model access: Restrict bedrock:InvokeModel permissions to the specific embedding and agent foundation model ARNs required by the solution.
    • Agent-to-Lambda invocation: Grant lambda:InvokeFunction to bedrock.amazonaws.com on the action group Lambda, scoped with an aws:SourceArn condition matching the agent ARN. Without this resource-based policy, the agent can’t invoke the action group.

    Clean up

    To avoid ongoing charges, delete the resources in the following order:

    1. Delete the Bedrock agent and its action group.
    2. Delete the embedding pipeline Lambda function and its event source mapping.
    3. Delete the DynamoDB table (this also removes the vector index). If you want to keep the table but remove the vector index, run the following command first:
      aws dynamodb update-table \
          --table-name unified-agent-data \
          --vector-index-updates '[{"Delete": {"IndexName": "content-embedding-index"}}]'

    4. Delete the action group Lambda function and associated IAM roles.

    Conclusion

    With this pattern, you can build a unified AI agent architecture that uses a single DynamoDB table for both operational data and vector-based semantic search. The native vector search of DynamoDB combined with Bedrock agent action groups eliminates the need for a separate vector database. DynamoDB Streams-driven embedding generation keeps the index synchronized in real time.

    This pattern reduces infrastructure complexity for applications that already rely on DynamoDB and need to add conversational AI capabilities. The automatic embedding pipeline keeps your vector index synchronized with operational writes, and the action group design gives the agent access to both semantic and structured query paths.

    Adapt the table schema, embedding dimensions, and agent instructions to your domain. Clone the sample-dynamodb-vector-search-architecture repository to deploy the complete working implementation. For more information about DynamoDB vector search capabilities and limits, refer to the Amazon DynamoDB vector search documentation.

    References

    About the author

    How AgentFlo built AI sales agents with Amazon Bedrock AgentCore – Part 2

    Post Syndicated from Muhammad Musab Iqbal original https://aws.amazon.com/blogs/architecture/how-agentflo-built-ai-sales-agents-with-amazon-bedrock-agentcore-part-2/

    If you’re building AI agents for commerce at scale, you face two critical challenges: handling unpredictable traffic spikes and ensuring your agents can be trusted with real customer transactions.

    This post shows how AgentFlo solved these challenges using Amazon Bedrock AgentCore and AWS serverless architecture. You learn the architectural patterns behind their reliability and trust frameworks, see the measurable business results (including +12% net revenue uplift based on early deployment data), and explore their roadmap for voice agents and server-side tool execution.

    This is Part 2 of a two-part series. Part 1 covers velocity, standardization, and scalability.

    Pillar 4: Trust: guardrails for autonomous commercial action and real-time visibility into agent operations

    AgentFlo enforces trust at every layer of the stack, from pre-request filtering to post-response privacy controls, so merchants can deploy autonomous agents with confidence.

    The challenge

    Enterprise customers won’t deploy autonomous agents unless they can trust them. An agent in production can’t expose sensitive data, offer unauthorized discounts, or access another customer’s information. The system also prevents price hallucination, unauthorized tool calls, opt-out violations, and credential exposure.

    Merchants also need fine-grained control over who can interact with their AI agents and what data each segment can access. Enterprise customers require restricted access; B2C businesses need open access for broader reach. Without identity-based controls, deploying customer-facing AI is a non-starter.

    Defense in depth

    In AgentFlo, trust isn’t only about safe responses. It’s about safe action. Agents can create carts, place orders, apply discounts, access customer data, and interact with backend systems, so policy enforcement must sit outside the model’s reasoning loop. The model proposes. Deterministic policy decides.

    AgentFlo applies trust controls across the full agent lifecycle: before the model sees the request, during tool execution, and after the model generates a response.

    Three-layer guardrails

    When users deploy an agent from the AgentFlo Portal, security enforcement happens at three stages.

    First, the AWS Fargate layer detects prompt injection and handles opt-outs before requests reach the agent. WhatsApp messages are authenticated using phone numbers as unique identifiers. Enterprise customers like EBM restrict access to authorized users, while restaurant deployments stay open for broader reach.

    Next, the AgentCore layer verifies identity and enforces order locks during tool execution. AgentCore Gateway, a capability of Amazon Bedrock AgentCore, enforces policies that prevent sales agents from accessing customer support tools. Cedar policies enforce business rules like maximum discount percentages independently of the model’s reasoning. Cedar is an open-source policy language developed by AWS for fine-grained, verifiable authorization decisions. Additionally, Policy in Amazon Bedrock AgentCore integrates with Amazon Bedrock Guardrails, so Cedar policies can invoke configurable safeguards for prompt attack detection, content filtering, and sensitive information blocking directly at the gateway boundary.

    Finally, post-turn privacy filters screen outputs to block inadvertent token disclosure and unverified price claims before customers see responses. Secrets are managed through AWS Secrets Manager with OIDC (OpenID Connect)-authenticated continuous integration and continuous delivery (CI/CD) pipelines. No credentials are stored in agent code.

    Infrastructure security

    Trust at the application layer requires sound underlying infrastructure. AgentFlo combines the built-in isolation of AgentCore with application-level controls:

    • Session isolation: Session isolation through AgentCore runtime, a capability of Amazon Bedrock AgentCore, which provides complete separation between merchants’ agent sessions through dedicated microVMs.
    • AgentCore Gateway policies: Fine-grained Cedar policies control which agents can access which tools and data, enforced deterministically regardless of model reasoning.
    • AWS Identity and Access Management (IAM)-based access control: Fine-grained permissions for agent-to-service communication.
    • Amazon Virtual Private Cloud (Amazon VPC) integration: Agent sessions operate within AgentFlo’s VPC with domain-level network restrictions, so agents only communicate with approved endpoints.
    • Compliance: Data residency controls and audit trails for regulatory requirements across multiple jurisdictions.

    Observability

    Trust requires visibility. Merchants need to see what their agents are doing in real time, not only after something goes wrong. AgentFlo uses AgentCore Observability, a capability of Amazon Bedrock AgentCore, to provide end-to-end tracing of every agent interaction, from initial request through tool execution to final response.

    AgentCore Observability captures structured traces for each agent turn, including model latency, tool invocation sequences, token usage, and error rates. These traces flow into Amazon CloudWatch, where AgentFlo builds dashboards showing active sessions, response times, and tool call patterns. Full request-to-response traces enable trace-level debugging. The system tracks P50/P95 latencies and throughput across agent types, alerting merchants when behavior deviates from baselines. Cost attribution provides per-merchant, per-agent breakdowns tied to specific conversations.

    Results

    Together, observability and trust give enterprises confidence to deploy autonomous agents at scale. Merchants benefit from safer execution, stronger compliance across jurisdictions, and controlled access to tools and data at the session level.

    Pillar 5: Reliability: a data foundation that keeps agents grounded in reliable data

    Reliable agents need reliable data. AgentFlo grounds every agent action in verified, current information through stateful sessions, merchant knowledge bases, and semantic product discovery.

    The challenge

    Enterprise customers won’t trust AI agents that forget context, hallucinate product details, or operate on stale data. An agent that quotes the wrong price, forgets a customer’s earlier request, or recommends discontinued products destroys confidence instantly. The system must make sure every agent action is grounded in verified, current information, from product catalogs and pricing to conversation history and business rules.

    Merchants also need their agents to maintain continuity across long customer journeys, access up-to-date business-specific knowledge, and surface products through natural language, all without manual intervention or prompt engineering.

    Data architecture overview

    In AgentFlo, reliability isn’t only about accurate responses. It’s about accurate action grounded in verified data. Agents retrieve product information, manage carts, and complete transactions, so every data source must be authoritative and current. The model reasons. Structured data decides.

    AgentFlo applies data reliability controls across three layers: stateful conversation management through Amazon DynamoDB, merchant-specific knowledge through Amazon Bedrock Knowledge Bases, and semantic product discovery through vector embeddings in Amazon S3 Vector.

    State management architecture

    A real sales journey can span 8 hours or 3 days. A customer might ask about a product in the morning, compare options at lunch, and complete the purchase that evening. The agent must remember context across all turns and maintain state, so customers don’t need to start over.

    AgentCore runtime and Amazon DynamoDB manage this context storage. The agent replays relevant history, loads context based on intent, and continues transactions safely.

    Each agent needs to be stateful (remembering earlier interactions), autonomous (deciding next steps without human intervention), and safe (operating within business rules without exposing sensitive data).

    The two-table DynamoDB design covers all three requirements: session continuity through conversation replay, autonomous context loading based on detected intent, and data integrity through structured ground-truth storage that the model can’t hallucinate over.

    Diagram of the per-message conversation flow between AgentCore runtime and the DynamoDB session and cart tables

    Figure 1: Per-message conversation flow. AgentCore runtime loads the last 15 messages from the DynamoDB Session Table at the start of each turn. The Cart Table is loaded on demand only when intent detection flags the request as cart-related, preventing the model from generating incorrect prices and quantities.

    Knowledge base system

    Merchants upload business-specific data (restaurant menus, clinic policies, product specifications, promotion calendars) into Amazon Bedrock Knowledge Bases backed by Amazon Simple Storage Service (Amazon S3). Agents automatically retrieve and reason over this merchant-specific content. Responses stay grounded in accurate, up-to-date business information without merchants writing a single prompt.

    Semantic search and vector retrieval

    AgentFlo improves product discovery by giving every product in its Amazon Aurora database a lightweight vector embedding. Customers can find products by name or description.

    AgentFlo also generates extra searchable tags for each product automatically, and merchants can add their own. The result: phrases like “the pink one,” “the smallest one,” “the new one,” or “the chocolate with the golden wrapper” all map to the right product. Customers ask for things naturally, and the platform finds what they’re looking for.

    Observability and billing

    The system captures all message interactions through Amazon Data Firehose to Amazon S3, so merchants can track cost per conversation and compare those costs against sales revenue. This pipeline shows merchants the return on investment (ROI) of their agent deployments and provides the data foundation for continuous agent improvement.

    Results

    The data architecture helps minimize context loss in conversations across multi-day customer journeys, with grounded responses that eliminate price and product hallucination. Merchants benefit from natural language product discovery without keyword dependency and merchant-specific knowledge retrieval without prompt engineering. Full cost visibility and ROI attribution per agent deployment give merchants clear measurement of platform value.

    Business impact: measurable results across the customer lifecycle

    Salesflo’s solution, powered by Strands Agents SDK and Amazon Bedrock AgentCore, delivered measurable improvements across the customer lifecycle:

    Metric Improvement
    Net revenue uplift +12%
    Customer engagement +40%
    Conversion rate +15%
    Average order value +8%
    Customer reactivation +20%

    AgentFlo generated these results by comparing agent-assisted customer journeys against a control group over a 90-day early deployment period.

    Note: The foundation models referenced in this post are available in select AWS Regions. For the latest information on model availability, see Supported Regions and models for Amazon Bedrock.

    The compounding effect at scale

    At AgentFlo’s scale, the impact is significant. With $300 billion in annual transacted value flowing through the Salesflo solution (based on platform transaction data), even single-digit percentage improvements translate to billions in incremental revenue for merchants.

    Operational improvements

    Beyond the metrics, merchants see operational improvements:

    • 24/7 coverage — AI agents engage customers at any hour, in any time zone, across any channel.
    • Consistent quality — Every customer interaction follows best-practice selling methodologies without the variability of human agents.
    • Scalable personalization — Thousands of concurrent agent sessions, each maintaining unique context per customer.
    • Rapid merchant onboarding — New merchants go live with customized AI agents in days, not months, through the self-service configuration platform.

    What’s next: voice, server-side execution, and integration expansion

    AgentFlo is actively extending the platform along three directions, each at a different stage of maturity.

    Real-time voice agents (in pilot)

    AgentFlo already supports voice within WhatsApp. Incoming voice notes go through a two-pass transcription process: a raw initial pass, followed by domain-aware correction that fuzzy-matches text against the live product catalog. The second pass catches brand names and SKUs even when partially misheard, across more than 90 supported languages. For outbound audio, merchants pick from multiple Text-to-Speech (TTS) providers per deployment.

    Because Speech-to-Text (STT), reasoning on AgentCore runtime, and TTS are fully independent components, any one can be swapped without disrupting the rest of the pipeline.

    The next step: BidiAgent. The next evolution is real-time voice agents built on the Strands SDK BidiAgent and Amazon Bedrock AgentCore WebRTC support. BidiAgent supports bidirectional audio streaming, natural interruptions, and concurrent tool execution. The agent can check inventory or apply a discount while continuing to listen and respond to the customer in the same call.

    The AgentCore WebRTC protocol and Amazon Kinesis Video Streams handle peer-to-peer transport for mobile and browser interactions without requiring relay infrastructure. This pushes AgentFlo beyond text messaging into proactive outbound calls and high-value B2B sales, where real-time conversation is essential for building trust.

    Server-side tool execution (under development)

    AgentFlo is experimenting with server-side tool execution in Amazon Bedrock, which removes client-side orchestration entirely.

    Traditional orchestration loops between model and tools repeatedly (model → execute → send result → repeat). With server-side execution, the agent makes a single API call to the Amazon Bedrock Responses API with an AgentCore Gateway Amazon Resource Name (ARN). The model then autonomously discovers, invokes, and processes tools through the Gateway Model Context Protocol (MCP) interface, all inside AWS infrastructure with no roundtrips back to the client.

    Here’s what that one API call looks like:

    from openai import OpenAI
    
    # OPENAI_BASE_URL = https://bedrock-mantle.us-west-2.api.aws/v1
    # OPENAI_API_KEY = <Amazon Bedrock API key>
    client = OpenAI()
    
    response = client.responses.create(
        model="openai.gpt-oss-120b",
        stream=True,
        background=False,
        store=False,
        input=[
            {
                "type": "message",
                "role": "user",
                "content": [{"type": "input_text", "text": user_message}],
            }
        ],
        tools=[
            {
                "type": "mcp",
                "server_label": "agentflo_gateway",
                "connector_id": GATEWAY_ARN,  # arn:aws:bedrock-agentcore:...:gateway/...
                "server_description": "AgentFlo commerce tools (cart, catalog, knowledge base)",
                "require_approval": "never",
            },
        ],
    )

    Note: Model availability varies by AWS Region. The model and endpoint shown in this example may not be available in all Regions. See Supported Regions and models for Amazon Bedrock for current availability.

    One request handles the whole loop. The Gateway ARN goes in as an MCP connector, and Bedrock takes it from there; pulling the tool list, picking the right one, invoking it, and feeding the result back to the model without anything leaving AWS. The client never sees credentials, tool schemas, or the intermediate turns. See ShopAssist: E-Commerce Agent Demo for more details.

    Early results: For specialist agents with short, focused tool loops, early measurements show approximately 30% lower latency. A sales agent calling three tools in sequence (check inventory, apply discount, update cart) collapses 50+ lines of orchestration into a single API call. All credentials stay server-side, and the simplified architecture makes onboarding new agent developers faster.

    Integration ecosystem expansion (ongoing)

    AgentFlo adds integrations based on merchant demand. Each new platform (payment processors, shipping providers, loyalty systems, or vertical-specific ERPs) becomes another MCP server connector in AgentCore Gateway. This pattern keeps expansion modular and quick.

    Key takeaways

    1. Pick your pillars first. The right AWS stack follows. AgentFlo first defined what velocity, standardization, scalability, and trust meant for the production system. With clear requirements, the AWS stack choices became obvious: Strands for the agent layer, AgentCore runtime for stateful sessions, AgentCore Gateway for tool routing and policy, and AWS Fargate for message ingestion.
    2. Specialized agent recipes beat multi-agent complexity. Deploying a single, well-configured agent with domain-specific tools and knowledge outperforms multi-agent orchestration for most customer interactions. Multi-agent handoffs are reserved for cross-domain transitions where context boundaries are clearly defined.
    3. Commerce is stateful. Plan for that on day one. A real sales journey can span 8 hours or 3 days. Stateless chatbots can’t maintain context that long. AgentCore runtime stateful sessions and DynamoDB-backed context were chosen on day one for exactly this reason. Retrofitting state onto a stateless agent later is much more painful than designing for it up front.
    4. Three-layer security builds trust. Pre-turn guards on Fargate, per-tool guards through AgentCore Gateway policies with Cedar, and post-turn output filters work together to support safe deployment of autonomous agents handling commercial transactions.
    5. System design supports scale. By building agent customization as a software as a service (SaaS) layer on top of AgentCore infrastructure, AgentFlo serves hundreds of merchants on shared infrastructure while still delivering personalized agent behavior for each one.
    6. Serverless + AgentCore = elastic commerce. The combination of Fargate for message handling and AgentCore for agent execution means AgentFlo scales from normal traffic to 50x flash-sale spikes without pre-provisioning or capacity planning.
    7. The feedback loop is the product. Real customer conversations teach the agents how to close. Where customers hesitate, what language converts, when they want a human handoff — all of it feeds back into recipes, prompts, and tool definitions. A new merchant deployment benefits from every conversation that ran on the platform before it. That compounding loop is harder to copy than any single piece of the architecture.

    Conclusion

    Building production-scale AI agents for commerce requires scalability and trust from day one. By combining Amazon Bedrock AgentCore stateful sessions and microVM isolation with AWS serverless infrastructure, AgentFlo delivers autonomous agents that handle unpredictable traffic while maintaining the security controls enterprises require.

    Next steps

    For questions about implementing similar architectures, visit the AWS Architecture Center or contact your AWS account team. To start building, open the Amazon Bedrock console or explore the Amazon Bedrock service detail page.

    We’d love to hear how you’re building agentic AI systems. Share your experiences in the comments.


    About the authors

    Amazon Linux default SSM parameter will now track the latest kernel

    Post Syndicated from Gokul Govindaraju original https://aws.amazon.com/blogs/compute/amazon-linux-default-ssm-parameter-will-now-track-the-latest-kernel/

    Today we are announcing that the Amazon Linux kernel-default AWS Systems Manager (SSM) parameter will now update to point to the latest Amazon Linux kernel version as new kernel versions get released. On August 17, 2026, for Amazon Linux 2023 (AL2023), the SSM parameter was updated from kernel 6.1 to kernel 6.18. As new kernel versions get released (expected annually), the parameter will continue to update to the latest kernel version after a validation period.

    This post explains the default kernel behavior, what it means for your workloads, and how to manage the transition.

    What’s changing?

    Amazon Linux ships multiple kernel versions and has tracked a default kernel for each OS version. For example,
    the AL2023 parameter:

    ssm:/aws/service/ami-amazon-linux-latest/al2023-ami-{minimal}-kernel-default-{x86_64 arm64}
    

    has remained on kernel 6.1 since launch. Going forward, the kernel-default SSM parameter will update to the latest kernel as new versions are released. Each new kernel will go through a 3- to 6-month validation period after GA before we update the default. This window gives you time to test the new kernel before the change. We will announce the kernel-default upgrade date before it takes effect.

    SSM Parameter Resolved to (Before) Resolves to (Now)
    al2023-ami-{minimal}-kernel-default-{x86_64, arm64} Kernel 6.1 AMI Kernel 6.18 AMI (what’s changed)
    al2023-ami-{minimal}-kernel-6.18-{x86_64, arm64} Kernel 6.18 AMI Kernel 6.18 AMI (unchanged)
    al2023-ami-{minimal}-kernel-6.1-{x86_64, arm64} Kernel 6.1 AMI Kernel 6.1 AMI (unchanged)

    Note: Already-running instances will keep the kernel they booted with and are not affected by this change. Only new instances launched from the kernel-default parameter will boot kernel 6.18. If you already use a version-specific SSM parameter, nothing changes for you.

    Why are we making this change?

    The Linux kernel is the foundation of workloads you run on Amazon Elastic Compute Cloud (Amazon EC2) and other services. Each new kernel brings meaningful improvements. For example, kernel 6.18 includes the Earliest Eligible Virtual Deadline First (EEVDF) CPU scheduler for fairer CPU time distribution and improved latency in mixed workloads. The kernel also increases Transmission Control Protocol (TCP) receive buffer for better network throughput on high-bandwidth instances.

    Previously, customers who wanted to run the latest Amazon Linux kernel had to manually update their SSM parameter references and redeploy each time a new kernel became available. With this change, you can receive these improvements without needing to manually upgrade.

    Evaluating the default kernel upgrade

    Staying on the default kernel is the recommended approach as it allows your new instances to always run the latest validated kernel with no manual intervention. However, because the default will now advance annually, you should build processes to validate that the new kernel works for your workload before each upgrade takes effect. If your workload has specific requirements that mandate a fixed kernel version, evaluate whether the new default is compatible or revert to a kernel version that suits your use case.

    If you haven’t validated kernel 6.18 yet, we recommend launching test instances on kernel 6.18 using the version-specific SSM parameter al2023-ami-{minimal}-kernel-6.18-{x86_64, arm64}. For instructions on referencing SSM parameters in your launch configuration, see the AL2023 User Guide.

    Staying on or reverting to a specific kernel version

    If you experience issues with the new default, or if your workload requires a specific kernel version for additional validation time or any other reason, revert to the version-specific SSM parameter. Change your references from al2023-ami-{minimal}-kernel-default-x86_64 to al2023-ami-{minimal}-kernel-{kernel_version}-x86_64 (for example, al2023-ami-kernel-6.1-x86_64). This applies anywhere you resolve an AL2023 AMI, including AWS CloudFormation templates, launch templates, Amazon EC2 Auto Scaling groups, CI/CD pipelines, or CLI scripts. For examples, refer to the AL2023 User Guide.

    Each of the supported kernels (6.1, 6.12, and 6.18) continue to receive updates as defined in AL2023 kernel lifecycle. When staying on a specific version, we recommend tracking the kernel lifecycle and planning upgrades before the kernel reaches end of support.

    Note: For Federal Information Processing Standards (FIPS) workloads, the default kernel may not always be the FIPS-validated kernel. If you require FIPS mode, see AL2023 FIPS FAQ.

    Conclusion

    In this post, we announced that the Amazon Linux default SSM parameter will now upgrade to the latest kernel as new kernel versions are released. The AL2023 kernel-default parameter was updated from kernel 6.1 to kernel 6.18 on August 17, 2026. We explained how the new cadence works, how already-running instances are unaffected, and how to stay on a specific kernel version if your workload requires it.

    To learn more, see the AL2023 Kernel documentation and the AL2023 release notes. For questions or issues, contact AWS Support.

    Propagate user authorization context in AI agents with Amazon Bedrock AgentCore

    Post Syndicated from Anshu Bathla original https://aws.amazon.com/blogs/security/propagate-user-authorization-context-in-ai-agents-with-amazon-bedrock-agentcore/

    Many teams now deploy AI agents that pull from Amazon DynamoDB tables, document repositories, software as a service (SaaS) platforms, and internal knowledge bases to answer questions and automate workflows. A key risk in these deployments is that the agent has no awareness of who’s asking, so it might return data the user shouldn’t see.

    If you’re using Amazon Bedrock AgentCore to build AI agents that access multiple data sources, you need each user to see only the data they’re authorized to access. In this post, you learn patterns for propagating user authorization context through your agents so access control is enforced by infrastructure and downstream services, not by agent code. In this post, we show you how to deploy agents that enforce least privilege access without writing authorization logic in the agent itself. This approach follows AGENTSEC03 best practice in the AWS Well-Architected Agentic AI Lens.

    Use case

    Consider an example of a customer relationship management (CRM) chat application where employees from Sales and Finance departments interact with an AI agent to access customer information. Employees use the same chat interface and the same agent, but each department needs isolated access to their respective data:

    • Sales needs access to customer contracts, pricing strategies, and sales pipeline data
    • Finance needs access to customer invoices, payment records, and financial reports

    The AI agent accesses three types of data sources on behalf of users:

    When a Sales employee asks, “Show me customer contracts,” the agent must retrieve only Sales department contracts, not Finance invoices. This enforcement must happen outside the agent so that even if the agent is compromised through prompt injection or application bugs, it can’t access unauthorized data.

    Note: Although we use department-based scoping in this example, the pattern generalizes to any custom claim you define, whether it represents a role, business unit, geographic region, or project assignment.

    Architecture overview

    The following diagram shows the architecture used in this demonstration.

    Figure 1: Target architecture

    Figure 1: Target architecture

    The data flow shown in Figure 1 includes:

    1. A user opens the chat application and authenticates with Amazon Cognito user pool , which acts as the identity provider (IdP).
    2. A pre token generation Lambda trigger (V2) enriches the JSON Web Tokens (JWTs) with a custom claim and AWS session tag metadata before returning them to the user.
    3. The web app routes the user’s request along with the access token to the agent deployed on Amazon Bedrock AgentCore Runtime.
    4. Bedrock AgentCore Runtime validates the inbound JWT and, through Bedrock AgentCore Identity, issues a workload access token that binds the user and agent identities, and then invokes the agent.
    5. For queries requiring internal documents, the agent uses its AWS Identity and Access Management (IAM) role to query Amazon Bedrock Knowledge Bases (backed by an Amazon S3 vector store) with metadata filtering, and DynamoDB with user-scoped session-tagged credentials.
    6. For queries requiring external data, Bedrock AgentCore Identity retrieves credentials from AWS Secrets Manager and performs an on-behalf-of token exchange (RFC 8693) with Salesforce, returning a user-scoped access token.
    7. The agent calls the Salesforce REST API using the user-scoped token. Salesforce applies sharing rules and returns only records the user is authorized to access.

    This architecture follows two key principles.

    • The agent acts as an orchestrator, not a gatekeeper; it coordinates tool calls and reasoning but doesn’t control access to data. Authorization is enforced by downstream services.
    • The agent doesn’t store credentials to data stores; instead, each request gets temporary, user-bound access tokens.

    In the following sections, we dive deep into each data source to show how these principles are achieved in practice.

    Initial user authentication with IdP

    When an employee opens the chat application, they authenticate using their corporate credentials. For this example, you use Amazon Cognito user pools as the IdP. You can also achieve this with other IdPs such as Entra ID or Okta.

    The pre token generation Lambda trigger (V2) captures the user’s custom department context and adds it to the tokens to both the identity (ID) token and access token that Bedrock AgentCore Runtime uses for authorization decisions each serving a distinct purpose. The access token is used by the Bedrock AgentCore Runtime custom JWT authorizer for inbound authorization. The ID token also receive the https://aws.amazon.com/tags claim (used by AWS Security Token Service (AWS STS)) for session tags). The https://aws.amazon.com/tags claim is the specific format required by AWS STS to extract session tags during AssumeRoleWithWebIdentity. For more information and step-by-step guidance see How to customize access tokens in Amazon Cognito user pools.

    The following example shows the key logic within a pre token generation Lambda handler function configured as a trigger on your Amazon Cognito user pool. This code runs automatically when a user authenticates, extracting their department attribute and adding it as a custom claim to both ID Token and access token.

    import json
    
    def lambda_handler(event, context):
        department = event['request']['userAttributes'].get('custom:department', '')
    
        event['response']['claimsAndScopeOverrideDetails'] = {
            'idTokenGeneration': {
                'claimsToAddOrOverride': {
                    'department': department,
                    'https://aws.amazon.com/tags': {
                        "principal_tags": {"department": [department]},
                        "transitive_tag_keys": ["department"]
                    }
                }
            },
            'accessTokenGeneration': {
                'claimsToAddOrOverride': {
                    'department': department
                }
            }
        }
        return event
    

    Inbound authorization by AgentCore Runtime

    When the user request reaches AgentCore Runtime, the Inbound JWT authorizer performs two checks as shown in Figure 2. It validates the JWT token with Amazon Cognito (the configured IdP) by cryptographically verifying the token’s signature, confirming it is non-expired, and checking it was issued by the trusted IdP. It then extracts the department claim from the validated token and compares it against the expected value configured in the authorizer, any token without a matching claim is rejected before the agent code is invoked.

    Figure 2: Inbound JWT authorization

    Figure 2: Inbound JWT authorization

    The following example shows the inbound JWT authorizer configuration that you pass when deploying your agent to AgentCore Runtime. This configuration tells AgentCore which IdP to validate against and which custom claim value to enforce for this agent. In this example, inboundTokenClaimName is department, inboundTokenClaimValueType declares the claim type as STRING_ARRAY, and authorizingClaimMatchValue specifies the allowed values ([“Sales”, “Finance”]) with the CONTAINS_ANY operator. The authorizer validates that the department claim is present in the token and matches one of these values, ensuring only authenticated users from the Sales or Finance department can invoke the agent.

    authorizer_config = {
            "customJWTAuthorizer": {
                "discoveryUrl": discovery_url,
                "allowedClients": [client_id],
                "customClaims": [
                    {
                        "inboundTokenClaimName": "department",
                        "inboundTokenClaimValueType": "STRING_ARRAY",
                        "authorizingClaimMatchValue": {
                            "claimMatchValue": ["Sales", "Finance"]
                            "claimMatchOperator": "CONTAINS_ANY"
                        }
                    }
                ]
            }
        }

    Note: AgentCore Runtime automatically creates a workload identity for each deployed agent. A workload identity represents the digital identity of your agents within the AWS environment. It allows agents to maintain consistent identity whether they’re using IAM roles for AWS resource access, OAuth 2.0 tokens for external service integration, or API keys for third-party tool access.

    Passing the user context for agent outbound authorization

    After the inbound JWT token is validated and the user’s authorization context is confirmed, the agent must propagate this context to downstream resources. The fundamental security challenge here is how to design a system so that an agent acting on behalf of a user can only access data that user is authorized to see, even if the agent itself is compromised.

    The traditional approach of granting the agent broad credentials and relying on application-level filtering (such as adding WHERE clauses to queries) creates a single point of failure. If an attacker manipulates the agent through prompt injection or exploits a bug in the filtering logic, the full dataset becomes accessible. A more resilient design moves authorization enforcement out of the agent’s application code and into the infrastructure layer wherever possible. Instead of trusting the agent to filter results correctly, you configure the underlying services—IAM policies, database access controls, SaaS sharing rules—to reject unauthorized requests regardless of what the agent asks for. This way, the agent’s credentials are inherently limited to the requesting user’s permissions, and no amount of prompt manipulation can bypass those boundaries. Where infrastructure-level enforcement isn’t yet available, such as metadata filtering in Amazon Bedrock Knowledge Bases, the agent applies application-layer controls as a complementary measure. The following sections demonstrate how this principle applies to each data source in our architecture.

    Pattern 1: Scoping DynamoDB access to the requesting user

    For DynamoDB access, you can use AssumeRoleWithWebIdentity with session tags to create per-request, user-scoped credentials rather than granting the agent a static IAM role with direct table access. The agent passes the user’s signed ID token to AWS STS, which extracts the department tag from the token’s https://aws.amazon.com/tags claim and returns temporary credentials constrained to that department’s data partition. This moves access control from agent code to IAM policy evaluation. STS additionally validates the token’s audience (aud) claim against the IAM OIDC provider configuration, preventing tokens issued for other app clients from being used to assume the role. The following diagram shows this flow (Figure 3).

    Prerequisites (one-time setup):

    Before this runtime flow can execute, complete the following configuration:

    • Register Amazon Cognito as an IAM OIDC provider. Although the user authenticates using the Cognito API (USER_PASSWORD_AUTH), STS requires Cognito to be registered as an OIDC provider so it can discover and validate ID tokens. Configure the allowed client IDs (audiences) on the provider to match your application’s app client ID.
    CognitoOIDCProvider:
      Type: AWS::IAM::OIDCProvider
      Properties:
        Url: !Sub 'https://cognito-idp.${AWS::Region}.amazonaws.com/${CognitoUserPoolId}'
        ClientIdList:
          - !Ref CognitoAppClientId
        ThumbprintList:
          - '<thumbprint>'

    • Configure the UserScopedDynamoDBRole trust policy to include both sts:AssumeRoleWithWebIdentity and sts:TagSession permissions, with the Amazon Cognito OIDC provider as the federated principal.
    {
      "Version": "2012-10-17",
      "Statement": [{
        "Effect": "Allow",
        "Principal": {
          "Federated": "arn:aws:iam::111122223333:oidc-provider/cognito-idp.us-east-1.amazonaws.com/us-east-1_EXAMPLE"
        },
        "Action": [
          "sts:AssumeRoleWithWebIdentity",
          "sts:TagSession"
        ],
        "Condition": {
          "StringEquals": {
            "cognito-idp.us-east-1.amazonaws.com/us-east-1_EXAMPLE:aud": "<app-client-id>"
          }
        }
      }]
    }

    • By default, AgentCore Runtime drops custom headers as a security measure. To allow the X-Id-Token header through to the agent container, configure it in the agent runtime’s requestHeaderAllowlist so the ID token is forwarded to agent code. The following configuration tells AgentCore Runtime to forward only the X-Id-Token header to agent code, dropping other non-standard headers:
    request_header_config = {
        'requestHeaderAllowlist': ['X-Id-Token']
    }

    How it works:

    1. The user navigates the web application.
    2. The user authenticates with Amazon Cognito using USER_PASSWORD_AUTH.
    3. The JWT is issued with a custom department claim and the https://aws.amazon.com/tags claim for STS session tagging (covered in the preceding Initial user authentication with IdP section).
    4. Amazon Cognito returns the enriched tokens to the frontend. The access token carries the department claim for inbound authorization. The ID token carries both the department claim and the https://aws.amazon.com/tags claim for downstream STS calls.
    5. The user asks the agent a question (for example, “Show Q4 sales pipeline”).
    6. The frontend calls AgentCore Runtime, passing two tokens: the Amazon Cognito access token in the Authorization header (for inbound authorization), and the user’s ID token as a custom X-Id-Token header (for downstream STS calls).
    7. AgentCore Runtime validates the JWT and verifies the department claim matches the allowed values configured in the inbound authorizer. If validation fails, the request is rejected with HTTP 401 before agent code executes. After validation, AgentCore forwards the request to the agent container along with the allowed X-Id-Token header.
    8. The agent calls sts:AssumeRoleWithWebIdentity with the ID token. This call targets a single shared UserScopedDynamoDBRole. The following is the agent code for this step:
      def _scoped_dynamodb_resource(id_token: str):
          """Assume user-scoped role and return DynamoDB resource."""
          sts = boto3.client('sts')
          response = sts.assume_role_with_web_identity(
              RoleArn=USER_SCOPED_DYNAMODB_ROLE_ARN,
              RoleSessionName="agent-user-session",
              WebIdentityToken=id_token,
              DurationSeconds=900
          )
          creds = response['Credentials']
          session = boto3.Session(
              aws_access_key_id=creds['AccessKeyId'],
              aws_secret_access_key=creds['SecretAccessKey'],
              aws_session_token=creds['SessionToken']
          )
          return session.resource('dynamodb')

    9. AWS STS validates the token against the Amazon Cognito OIDC provider registered in IAM. STS verifies the token’s cryptographic signature, expiration, issuer, and audience (aud). The aud claim in the ID token must match one of the client IDs configured on the IAM OIDC provider resource. This prevents a valid token issued by the same Cognito user pool but for a different app client from being accepted. Note that the agent’s own execution role has no DynamoDB access and only permits sts:AssumeRoleWithWebIdentity, so even a compromised agent can’t bypass this flow.

      Note: Amazon Cognito user pools expose a standard OpenID Connect discovery endpoint, which is what you register as the trusted OIDC provider in IAM, even though the user signs in through the Cognito authentication APIs. When STS validates the token, it checks that the aud claim matches the client ID configured in the IAM OIDC provider. Tokens whose audience doesn’t match are rejected, adding a second control alongside signature and issuer validation.

    10. AWS STS extracts the https://aws.amazon.com/tags claim and creates a session with aws:PrincipalTag/department set. The trust policy’s sts:TagSession permission (configured in the prerequisites) enables this. Without it, STS silently drops the session tags and subsequent access is denied.
    11. AWS STS returns temporary credentials. These credentials are user-scoped and tamper-proof because the session tags are derived from the cryptographically signed JWT, not from agent code.
    12. The agent queries DynamoDB using these credentials.
    13. IAM evaluates the dynamodb:LeadingKeys condition against ${aws:PrincipalTag/department}. Only the user’s department partition is accessible. Because IAM evaluates this condition at the policy level, even if agent code is manipulated using prompt injection, cross-department access is denied. The following is an example of the permission policy on the role:
      {
        "Version": "2012-10-17",
        "Statement": [{
          "Effect": "Allow",
          "Action": ["dynamodb:GetItem", "dynamodb:Query"],
          "Resource": "arn:aws:dynamodb:us-east-1:111122223333:table/CustomerRecords",
          "Condition": {
            "ForAllValues:StringEquals": {
              "dynamodb:LeadingKeys": ["${aws:PrincipalTag/department}"]
            }
          }
        }]
      }

    14. DynamoDB returns only the records from the user’s authorized department partition. Cross-department data is never returned because the IAM policy blocks the API call itself. It doesn’t rely on post-query filtering.
    15. The agent receives the authorized results and passes them to the LLM for natural language response composition.
    16. The composed response is returned to the frontend application and displayed to the user.

    Pattern 2: User-scoped authorization to Amazon Bedrock Knowledge Bases

    For documents stored in Amazon Bedrock Knowledge Bases, the agent applies metadata filtering at query time. Each document is tagged with a Department metadata attribute during ingestion. Amazon Bedrock Knowledge Bases using metadata filtering to implement the data authorization. You need to provide metadata files alongside the source data files with the same name as the source data file and .metadata.json suffix while uploading data in Amazon S3. Amazon Bedrock Knowledge Bases ingests these documents along with corresponding metadata file. The metadata attributes are stored alongside the vectors as filterable fields in the index.

    Each metadata file contains a simple JSON structure with the department attribute. The following example shows the complete content of a metadata file for Sales department documents:

    {"metadataAttributes": {"Department": “Sales"}}

    When the agent queries Amazon Bedrock Knowledge Bases, it calls the bedrock:Retrieve action and appends the retrievalConfiguration filter scoped to the user’s department. The department value is extracted from the JWT access token that the agent received during inbound authorization.

    response = client.retrieve(
        knowledgeBaseId=KNOWLEDGE_BASE_ID,
        retrievalQuery={"text": user_query},
        retrievalConfiguration={
            "vectorSearchConfiguration": {
                "filter": {"equals": {"key": "Department", "value": department}}
            }
        }
    )

    Note: Metadata filtering is application-layer enforcement. The bedrock:Retrieve API doesn’t expose metadata filter content as an IAM condition key. For stricter isolation, consider separate knowledge bases per department with IAM resource-level policies.

    Pattern 3: User-scoped access to external services using on-behalf-of token exchange

    We use Salesforce as an example of an external service integration. The same on-behalf-of (OBO) token exchange pattern applies to external service that supports RFC 8693 or a compatible token exchange mechanism. External services like Salesforce don’t support IAM-based access control, so you need a different mechanism to propagate user identity. The AgentCore Identity OBO token exchange (RFC 8693) provides this by exchanging the user’s authenticated identity for a user-scoped token that the external service will recognize and enforce natively.

    AgentCore Identity supports three OAuth patterns for external service access. With client credentials—Two-Legged OAuth (2LO) or machine-to-machine (M2M)—the agent authenticates as a service account and receives a token with broad access. The agent is then responsible for filtering data in queries, which makes this pattern suitable when accessing organization-wide data that isn’t scoped to an individual user. A variation of this pattern embeds user context as custom claims within the agent’s M2M token itself, see Empower AI agents with user context using Amazon Cognito. With Authorization Code (3LO), the user explicitly consents through a browser redirect and the external service enforces per-user access. This works when per-service consent is required, but it demands user interaction during the flow, making it impractical for background agent operations. Learn more about this in Secure AI agents with Amazon Bedrock AgentCore Identity on Amazon ECS. With OBO token exchange, the user’s already-authenticated identity is exchanged for a service-scoped token without any additional user interaction, and the external service enforces access.

    For this use case, OBO is the most appropriate pattern. The user has already authenticated at the entry point (through the IdP), and the agent needs to act on their behalf across multiple services without prompting for additional consent. OBO propagates user identity end-to-end without the agent holding credentials, scales automatically with no per-user token storage, and allows downstream services to enforce their own authorization (sharing rules, role-based access control (RBAC)). Because no browser redirect is needed, OBO works seamlessly for background tool calls where the user isn’t present in a browser session. Figure 4 demonstrates the complete flow when using OBO token exchange.

    How it works:

    1. The user navigates to the web application.
    2. The user authenticates with Amazon Cognito using USER_PASSWORD_AUTH.
    3. A pre token generation Lambda function injects the custom department claim into the token (covered in the preceding Initial user authentication with IdP section).
    4. Amazon Cognito returns the tokens to the frontend. The access token is issued with the department claim.
    5. The user asks the agent a question (for example, “Show me Sales opportunities”).
    6. The frontend calls AgentCore Runtime with a single agent Amazon Resource Name (ARN), passing the Amazon Cognito access token: POST /invocations, Authorization: Bearer {access_token}.
    7. AgentCore Runtime validates the inbound JWT (signature, expiration, issuer, and custom claims including the department claim). After successful validation, AgentCore Runtime extracts the user identity from the JWT and calls the GetWorkloadAccessTokenForJWT API to exchange it for a workload access token. The agent code receives the workload access token through the invocation payload header. Workload access tokens are exclusively for accessing Amazon Bedrock AgentCore services and can’t be used directly for external services.
    8. The agent calls AgentCore Identity (GetResourceOauth2Token) with the workload access token, requesting a Salesforce token through the configured OBO (on-behalf-of) credential provider. AgentCore Identity validates the caller identity and agent identity, then accesses the stored client credentials from Secrets Manager. If a previously stored OAuth access token has expired, AgentCore Identity automatically obtains a new one using the client credentials, reducing the need for manual token lifecycle management in agent code. The agent code uses the @requires_access_token decorator to invoke this flow:
      @requires_access_token(
          provider_name="salesforce-token-exchange",
          scopes=[],
          auth_flow="ON_BEHALF_OF_TOKEN_EXCHANGE",
      )
      def _get_salesforce_token_sync(*, access_token: str) -> str:
          return access_token

      On the AWS side, this requires an AgentCore Identity OAuth Client configured with Grant type: Token Exchange, Actor token: None, pointing to the Salesforce token endpoint. The Salesforce Connected App consumer secret is stored in Secrets Manager (the agent doesn’t access it directly).

    9. AgentCore Identity performs RFC 8693 token exchange with the Salesforce token endpoint, sending the user identity as the subject_token. AgentCore Identity performs this secure token exchange for user-delegated access based on the configured OAuth 2.0 credential provider. The agent can’t request tokens for arbitrary users because the workload access token cryptographically binds the request to the authenticated user.
    10. Salesforce validates the token against the registered Amazon Cognito auth provider configured in Salesforce Setup.
    11. Salesforce resolves the user using FederationIdentifier. On the Salesforce side, this requires:
      • Amazon Cognito registered as an OpenID Connect auth provider
      • A token exchange handler (Apex class extending Auth.Oauth2TokenExchangeHandler) that resolves users by FederationIdentifier
      • Token exchange flow enabled on the connect app or external client app
      • Each user’s FederationIdentifier set to their Amazon Cognito subject’s (sub) unique user identifier (UUID).
      • Sharing rules configured to enforce department-scoped record access

      The federation ID (sub) is immutable and can’t be spoofed by the agent, because it originates from the cryptographically signed identity token.

    12. Salesforce returns a user-scoped access token to AgentCore Identity, which passes it back to the agent.
    13. Agent calls the Salesforce REST API using the user-scoped token. No department filtering is needed in the Salesforce Object Query Language (SOQL) query because Salesforce enforces access through sharing rules:
      @tool
      def query_salesforce_opportunities(query_text: str) -> str:
          access_token = _get_salesforce_token_sync()
      
          # No department filter needed. Salesforce sharing rules enforce access.
          soql = "SELECT Id, Name, Amount, StageName, CloseDate FROM Opportunity ORDER BY CloseDate DESC LIMIT 10"
      
          response = requests.get(
              f"{SALESFORCE_URL}/services/data/v59.0/query?q={urllib.parse.quote(soql)}",
              headers={"Authorization": f"Bearer {access_token}"},
              timeout=30,
          )
          return json.dumps(response.json().get("records", []))

    14. Salesforce applies sharing rules and returns only records the user is authorized to access. The agent doesn’t hold Salesforce credentials (refresh tokens, client secrets), these remain with AgentCore Identity.
    15. The agent’s LLM composes a response from the returned records.
    16. The frontend displays the results to the user.

    Conclusion

    In this post, you learned how to enforce consistent, end-to-end authorization in agentic AI applications by propagating user context from Amazon Cognito through Amazon Bedrock AgentCore to downstream resources. We showed you three patterns:

    • Per-request user-scoped credentials using AssumeRoleWithWebIdentity with session tags, evaluated by IAM attribute-based access control (ABAC) policies to access Amazon DynamoDB
    • Department-scoped metadata filtering at the application layer to access Amazon Bedrock Knowledge Bases.
    • On-behalf-of token exchange (RFC 8693) using AgentCore Identity, with Salesforce-native sharing rules governing access to external CRM data.

    The key takeaway is that the agent coordinates work but doesn’t decide who can access what. Access decisions are made by infrastructure-level controls and the downstream service’s authorization model. This layered approach means that even if the agent behaves unexpectedly, unauthorized data access is still blocked.

    You can use this as a reference implementation and adapt it to your requirements by choosing authorization attributes relevant to your organization (such as department, role, business unit, or region), integrating additional data sources, or extending the token exchange patterns to other external services.

    Next steps

    If you have feedback about this post, submit comments in the Comments section below.


    Anshu Bathla

    Anshu Bathla

    Anshu is a Sr. Lead Consultant – Security at AWS, based in Gurugram, India. He works with customers across diverse verticals to help strengthen their security infrastructure and achieve their security goals. Outside of work, Anshu enjoys reading books and gardening at his home garden. Connect with him on LinkedIn.

    Prafful Gupta

    Prafful Gupta

    Prafful is a DevOps Engineer at AWS, based in Gurugram, India. Having started his professional journey with Amazon, he specializes in DevOps and generative AI solutions, helping customers navigate their cloud transformation journeys. Beyond work, he enjoys networking with fellow professionals and spending quality time with family. Connect with him on LinkedIn.

    Rohit Verma

    Rohit Verma

    Rohit is a Delivery Consultant – Security, Risk and Compliance at AWS, based in Gurugram, India. He partners with customers across multiple industries to strengthen their security posture, leading risk consulting engagements, and security deliverable reviews. Outside of work, Rohit is a fitness enthusiast who enjoys music and reading non-fiction books. Connect with him on LinkedIn.

    AI-powered clinical trial eligibility and safety using Amazon Bedrock AgentCore

    Post Syndicated from Sachin Jain original https://aws.amazon.com/blogs/architecture/ai-agents-for-clinical-trial-screening/

    AI agents built on Amazon Bedrock AgentCore let clinical trial teams make fast, accurate enrollment decisions while keeping clinicians in control through human-in-the-loop oversight. According to the Tufts Center for the Study of Drug Development, 80 percent of clinical trials miss their enrollment timelines, and each day of delay costs an estimated $500,000.

    Today, eligibility decisions rely on manual chart review across fragmented sources — EHR notes, lab results, imaging reports, and medication histories. Study teams spend hours reconstructing each candidate’s history and mapping it to protocol criteria. As protocols grow more complex, this doesn’t scale: screen failure rates stay high and enrollment targets slip.

    We show how to architect a Clinical Trial Eligibility and Safety Agent on AWS that assembles patient evidence, evaluates it against protocol criteria, and presents screening recommendations with citations, while clinicians retain final authority and full audit trails. It combines AWS HealthLake for FHIR-native data access, Amazon Bedrock AgentCore for multi-step reasoning, and Amazon Bedrock AgentCore Evaluations for scoring each decision via LLM-as-a-judge and human-in-the-loop. This post is for solution architects, engineering teams, and technology leaders applying AI to clinical trial operations on AWS.

    AI agents for clinical trial screening

    AI agents with Human-in-the-Loop (HIL) are well-suited for clinical trial eligibility and safety decisions because they address information fragmentation while preserving human clinical judgment. The core problem isn’t a lack of data, but that eligibility and safety signals are scattered across EHR notes, lab portals, imaging reports, and medication histories, forcing study teams to reconstruct each participant’s clinical picture. A knowledge graph addresses this by storing clinical data as entities and the relationships between them, representing each patient, molecule, endpoint, and market as a node with relationships stored as edges. To answer an eligibility or safety question, the agent traverses these edges, going from a diagnosis to its associated labs or a medication to its known interactions, rather than re-querying and joining disconnected sources each time. This structure supports the agent’s preparatory work:

    • Organizing evidence from fragmented sources into a knowledge graph, linking patients, molecules, endpoints, and markets as interconnected nodes.
    • Mapping patient information against protocol criteria.
    • Surfacing relevant passages with citations for clinician review.
    • Highlighting uncertainties that require human judgment.

    Critically, the clinician remains the decision-maker. The agent organizes the supporting information. These systems augment rather than replace clinical reasoning — proposing preliminary assessments, flagging edge cases, providing confidence scores, and learning from feedback.

    As protocols grow more complex with precision oncology and biomarker-driven eligibility, agents manage multi-step logic and maintain consistency across sites, while deferring final judgment to clinical staff.

    Architecture overview

    This proposed architecture illustrates how core AWS services can be combined to create an end-to-end clinical trial screening pipeline. AWS HealthLake serves as the FHIR-native clinical data foundation, ingesting and normalizing patient records from disparate EHR systems, lab portals, and imaging archives into a unified, queryable data store. Amazon Bedrock AgentCore orchestrates the multi-step workflow assembling patient profiles, matching them against trial protocols, detecting safety signals, and generating evidence-backed screening recommendations. An Amazon Bedrock Knowledge Bases stores trial protocols, inclusion/exclusion criteria, and safety guidelines. The entire pipeline feeds into a clinician review dashboard where investigators examine agent reasoning, verify citations, and render final decisions. Actions are captured in an immutable audit trail for regulatory compliance.

    Architecture diagram showing the clinical trial screening pipeline with AWS HealthLake, Amazon Bedrock AgentCore, and Amazon CloudWatch

    Architecture workflow

    The screening pipeline operates in the following steps. Each step maps to a distinct phase of the eligibility and safety assessment, from data ingestion through clinician review and continuous monitoring.

    Step 1: Clinical data ingestion

    AWS HealthLake ingests patient records from EHR systems, lab portals, imaging reports, and medication histories, then normalizes them into FHIR R4 resources for standardized, queryable access.

    Step 2: Agent orchestration

    Amazon Bedrock AgentCore orchestrates three specialized agents, each scoped to a distinct phase of the screening pipeline. They operate within the Amazon Bedrock AgentCore Runtime, which connects to tools through MCP Gateway, maintains session memory so agents reference earlier findings without re-querying, and enforces identity-based access control for least-privilege data access. A built-in code interpreter handles dynamic calculations such as eGFR or BMI derivation.

    Pre-screening agent: The first gate. It resolves three threshold questions: Is the patient’s informed consent valid and current? Does their high-level profile (age, diagnosis category, geography) align with basic enrollment parameters? Have they completed any required washout period? Patients who clear all three advance. Those who don’t receive a documented rejection citing the failing criterion.

    Detailed screening agent: The core clinical reasoning engine. It walks through all inclusion and exclusion criteria, retrieving the relevant FHIR resources — Observation for labs, Condition for diagnoses, MedicationStatement for medications — and evaluating each against the protocol threshold. It also reviews organ function, adverse drug reactions, and contraindicated conditions, cross-references medications against the investigational product for interactions, and assesses the overall comorbidity profile for risk combinations no single criterion would catch. The output is a structured determination (Eligible, Ineligible, or Requires Review) with a per-criterion evidence matrix, confidence scores, and a reasoning summary citing source records.

    Site & enrollment agent: Once a patient clears screening, it handles operational logistics — matching the patient to the most appropriate site by proximity, capabilities, and investigator availability, then confirming open enrollment capacity. If the preferred site is full, it identifies alternatives and flags the study coordinator.

    All three agents operate behind Amazon Bedrock Guardrails, which enforce:

    1. PII/PHI filtering to protect patient health information.
    2. Content safety controls to help prevent clinically inappropriate outputs.
    3. Grounding checks to keep responses anchored in retrieved evidence rather than model parametric knowledge.
    4. Denied topic boundaries to keep agents within their screening scope.

    Step 3: LLM-as-judge evaluation

    Amazon Bedrock AgentCore Evaluations scores every screening decision using a combination of built-in and custom evaluators across three dimensions:

    1. Clinical accuracy: Correctness of the eligibility determination against patient data, faithfulness to source evidence (not hallucinated justifications), logical coherence across reasoning steps, and context relevance confirming the right protocol and patient records were retrieved.
    2. Operational effectiveness: Response completeness and clarity for coordinators reviewing dozens of patients daily, appropriate use of FHIR queries and knowledge base tools, and end-to-end goal success (did the agent complete the full screening workflow?).
    3. Safety compliance: Custom evaluators verify that safety-critical criteria (lab thresholds, restricted medications, contraindicated conditions) were never skipped, that uncertainties are explicitly acknowledged rather than resolved with false confidence, and that all safety flags route to the appropriate review tier.

    Decisions that pass evaluation with high confidence proceed to the clinician dashboard. The system flags those that fall below quality thresholds and routes them to human review with the specific evaluation concern highlighted.

    Step 4: Human-in-the-loop review and enrollment

    Flagged cases and agent recommendations flow into a tiered clinical review structure:

    1. PI review queue: Principal Investigators review flagged decisions from the LLM Judge, examining the agent’s reasoning chain, verifying citations against source records, and rendering a final determination.
    2. Study coordinator dashboard: Coordinators manage trial logistics, scheduling, and the day-to-day enrollment pipeline, using the agent’s structured outputs to accelerate their workflow.
    3. Patient communication: Outreach and consent updates are coordinated through the dashboard, keeping patients informed of their screening status.
    4. Escalation to medical director: Complex or high-risk cases that exceed the PI’s comfort level are escalated to the Medical Director for final adjudication.

    Clinicians retain complete override capability at every stage. When a clinician overrides an agent recommendation, approving a patient the agent flagged or rejecting one it cleared, the system captures the corrected decision and the clinician’s reasoning. These corrections expand the ground truth dataset used by Amazon Bedrock AgentCore Evaluations and surface patterns that inform prompt and retrieval tuning, creating a continuous learning loop where human judgment directly improves agent performance over time.

    Step 5: Observability and continuous monitoring

    Amazon CloudWatch provides end-to-end observability across all agents, surfacing agent traces (step-by-step execution logs), latency metrics, error rates (failed tool calls, guardrail blocks), judge scores (pass/flag rates per agent), HITL metrics (override rates, review latency), and alarm-based escalation when safety thresholds are breached.

    Although the current implementation focuses on screening and enrollment, the same agent orchestration framework, evaluation pipeline, and compliance infrastructure support future post-enrollment monitoring agents such as adverse event detection from lab results and clinical notes, protocol deviation tracking, retention risk prediction, and re-screening triggers when clinical changes affect ongoing eligibility. Each inherits the existing scoring, logging, and auditability without requiring a separate governance framework.

    Evaluating agent performance in clinical trial screening with human oversight

    The screening pipeline’s credibility rests on two layers: an automated evaluation layer that scores every decision, and a human-in-the-loop (HITL) layer that gives clinicians final authority. LLM-as-Judge (Step 3) decides which cases clinicians see and how they’re prioritized. The HITL workflow (Step 4) decides how clinicians act. Together they form a continuous loop where human judgment both safeguards and improves agent performance. Using Amazon Bedrock AgentCore Evaluations, you build a framework spanning three dimensions: clinical accuracy, operational effectiveness, and safety compliance with built-in and custom evaluators that run continuously.

    Clinical accuracy and reasoning

    Built-in evaluators check whether the agent gets the determination right and whether its reasoning holds up: Correctness (accurate against the patient’s labs, diagnoses, and medications), Faithfulness (reasoning stays grounded in patient data and protocol, not plausible-sounding invention), Coherence (no logical contradictions across steps), Context relevance (the right protocol and records were retrieved), and Goal success rate (the full workflow ran end to end). Custom LLM-as-Judge evaluators add clinical specifics: Eligibility accuracy (each inclusion/exclusion criterion evaluated correctly) and Criteria coverage (no criteria skipped, especially safety-critical lab thresholds and restricted medications).

    Operational effectiveness

    Accuracy alone is insufficient, output must fit workflows where coordinators review dozens of patients daily. Helpfulness, conciseness, and relevance confirm a clear, scannable, on-topic determination. Instruction following verifies the expected structured format (patient summary, criteria checklist, determination, justification, safety flags, next steps). Tool selection and parameter accuracy check the agent invoked the right tools with correct inputs.

    Safety and responsible behavior

    Safety carries the strictest thresholds. Harmfulness detection flags clinically dangerous content; Stereotyping detection makes sure decisions aren’t influenced by demographics beyond protocol requirements. Both trigger immediate review. Custom evaluators target the highest-risk failures: Safety flag detection confirms every significant concern surfaced (contraindicated medications, out-of-range labs, disqualifying conditions, drug interactions), with a single miss treated as critical; Uncertainty acknowledgment makes sure the agent recommends human review on missing or ambiguous data rather than making an overconfident call.

    The human-in-the-loop safeguard

    When a wrong eligibility call can affect patient safety, human judgment is the final safeguard. A score below threshold routes the case to the HITL workflow.

    The three agents together produce an eligibility determination with a confidence score. At trial onset, the clinician sets a confidence threshold. Cases below it or flagged by evaluation reach the clinician dashboard with the specific concern highlighted. Clinicians review the full reasoning and approve, reject, or request more information from the same interface. Their corrections are stored alongside machine-approved records, feeding back into future determinations and continuously improving accuracy.

    Review and approval workflow

    Review is tiered by complexity: automated pre-screening filters clearly ineligible candidates. Low-complexity cases get expedited review, medium-complexity follow standard protocols, and high-complexity edge cases escalate to senior clinicians. Cases unreviewed beyond set timeframes escalate automatically. Final enrollment decisions, low-confidence cases, experimental therapies, and complex histories require human approval. Routine high-confidence checks proceed automatically.

    Audit trails

    The system generates immutable audit records in Amazon DynamoDB for every decision, capturing clinician ID, timestamp, patient and trial IDs, outcomes, AI recommendations, and complete workflow execution history. These records are designed to support FDA 21 CFR Part 11 requirements for electronic records and signatures, providing documentation for regulatory inspections and quality assurance. Readers should consult their compliance team and conduct their own assessment. See the AWS compliance resources for further guidance.

    Security and compliance

    Clinical trial data is among the most sensitive in healthcare. HIPAA, FDA 21 CFR Part 11, GxP, and GDPR require strict controls over how patient data is stored, accessed, and processed, and AI agents reasoning over that data introduce new security considerations. This solution protects data at every layer while maintaining the audit trails and privacy standards regulators require.

    AWS HealthLake is HIPAA-eligible with encryption at rest and in transit, access controls, and SMART on FHIR authorization. Amazon Bedrock is HIPAA-eligible, SOC 2 attested, ISO and CSA STAR Level 2 certified, and never shares customer data with model providers. AWS PrivateLink keeps traffic off the public internet.

    Amazon Bedrock AgentCore enforces agent boundaries at runtime through declarative authorization policies — readable, deterministic rules, outside application code, defining what the agent can access, invoke, and retrieve. AgentCore runs within your Amazon Virtual Private Cloud (Amazon VPC) for network isolation, and AWS CloudTrail records API calls for an immutable audit trail that can support FDA compliance requirements.

    Amazon Bedrock AgentCore Evaluations scores each decision using built-in and custom evaluators with an LLM-as-a-Judge approach. Continuous sampling detects drift, and Amazon CloudWatch alerts teams when quality drops below thresholds — ongoing evidence the agent performs within validated parameters, supporting GxP with minimal manual testing.

    Conclusion

    In this post, we showed how combining the FHIR-native data foundation of AWS HealthLake
    with the multi-step reasoning capabilities of Amazon Bedrock AgentCore turns manual,
    fragmented clinical trial screening into an AI-assisted workflow that reduces patient matching
    time from days to minutes. Clinical trial enrollment remains one of drug development’s most
    resource-intensive bottlenecks, and delayed starts carry heavy financial consequences from lost
    patent-protected sell time and operational burn. Clinicians receive organized evidence,
    transparent reasoning, and actionable recommendations while retaining full decision authority
    and audit traceability.

    The impact extends beyond speed: more consistent criteria interpretation across sites, earlier
    detection of safety contraindications, and lower screen failure rates. As oncology trial eligibility
    criteria grow in complexity — with fewer than 5% of cancer patients enrolling under strict
    requirements — this human-in-the-loop approach offers a scalable, compliance-aligned path to
    faster, higher-quality recruitment.

    Call to action

    Ready to accelerate your clinical trial operations? Take the next step: