If you’re building large scale enterprise applications, you’ve likely faced the complexities of processing large volumes of data files. Whether you’re analyzing your application logs, processing customer data files, or transforming machine learning datasets, you know the complexity involved in orchestrating workflows. You’ve probably written nested workflows and additional custom code to process objects from Amazon Simple Storage Service (Amazon S3) buckets.
With AWS Step Functions Distributed Map, you can process large scale datasets by running concurrent iterations of workflow steps across data entries in parallel, achieving massive scale with simplified management.
With the new prefix-based iteration feature and LOAD_AND_FLATTEN transformation parameter for Distributed Map, your workflows can now iterate over S3 objects under a specified prefix using S3ListObjectsV2 to process their contents in a single Map state, avoiding nested workflows and reducing operational complexity.
In this post, you’ll learn how to process Amazon S3 objects at scale with the new AWS Step Functions Distributed Map S3 prefix and transformation capabilities.
Use case: Application log processing and summarization
You’ll build a sample Step Functions state machine that demonstrates processing of all the log files from the given S3 prefix using a Distributed Map. You’ll analyze all the log files to build a summary INFO, WARNING and ERROR messages in the log file on hourly basis. The following diagram presents the AWS Step Functions state machine:
Log files processing workflow
The state machine iterates over all the log files from the specified S3 prefix using S3 ListObjectsV2 and process them using AWS Step Functions Distributed Map.
For each log file entry, the state machine puts hourly ErrorCount metric into Amazon CloudWatch.
The state machine then stores hourly metrics count in a Amazon DynamoDB table.
The state machine then invokes an AWS Lambda function to perform metrics aggregation.
The following is an example of the parameters in an ItemReader configured to iterate over the content of S3 objects using S3 ListObjectsV2.
{
"QueryLanguage": "JSONata",
"States": {
...
"Map": {
...
"ItemReader": {
"Resource": "arn:aws:states:::s3:listObjectsV2",
"ReaderConfig": {
// InputType is required if Transformation is LOAD_AND_FLATTEN. Use one of the given values
"InputType": "CSV | JSON | JSONL | PARQUET",
// Transformation is OPTIONAL and defaults to NONE if not present
"Transformation": "NONE | LOAD_AND_FLATTEN"
},
"Arguments": {
"Bucket": "amzn-s3-demo-bucket1",
"Prefix": "{% $states.input.PrefixKey %}"
}
},
...
}
}
With the LOAD_AND_FLATTEN option, your state machine will do the following:
Read the actual content of each object listed by the Amazon S3 ListObjectsV2 call.
Parse the content based on InputType (CSV, JSON, JSONL, Parquet).
Create items from the file contents (rows/records) rather than metadata.
We recommend including a trailing slash on your prefix. For example, if you select data with a prefix of folder1, your state machine will process both folder1/myData.csv and folder10/myData.csv. Using folder1/ will strictly process only one folder. All of the objects listed by prefix need to be in the same data format. For example, if you are selecting InputType as JSONL, your S3 prefix should contain only JSONL files and not a mix of other types.
The context object is an internal JSON structure that is available during an execution. The context object contains information about your state machine and execution. Your workflows can reference the context object in a JSONata expression with $states.context.
Within a Map state, the context object includes the following data:
For each Map iteration, the Index contains the index number for the array item that is being currently processed.
A Key is only available when iterating over JSON objects. Value contains the array item being processed. For example, for the following input JSON object, Names will be assigned to Key and {"Bob", "Cat"} will be assigned to Value.
{
"Names": {"Bob", "Cat"}
}
Source contains one of the following:
For state input: STATE_DATA
For Amazon S3 LIST_OBJECTS_V2 with Transformation=NONE, the value will show the S3 URI for the bucket. For example: S3://amzn-s3-demo-bucket1
For all the other input types, the value will be the Amazon S3 URI. For example: S3://amzn-s3-demo-bucket1/object-key
Using LOAD_AND_FLATTEN and the Source field, you can connect child executions to their sources.
Run the following steps to deploy and test the Step Functions state machine.
Clone the GitHub repository in a new folder and navigate to the project folder.
git clone https://github.com/aws-samples/sample-stepfunctions-s3-prefix-processor.git
cd sample-stepfunctions-s3-prefix-processor
Run the following commands to deploy the application.
sam deploy --guided
Enter the following details:
Stack name: Stack name for CloudFormation (for example, stepfunctions-s3-prefix-processor)
AWS Region: A supported AWS Region (for example, us-east-1)
Accept all other default values.
The outputs from the AWS SAM deploy will be used in the subsequent steps.
Run the following command to generate sample log files.
python3 scripts/generate_logs.py
Run the following to upload the log files to the S3 bucket with the /logs/daily prefix. Replace amzn-s3-demo-bucket1 with the value from the sam deploy output.
The Step Function state machine iterates over all the log files with the S3 prefix /logs/daily and processes them in parallel. The workflow updates the metrics in CloudWatch, stores hourly metrics count in DynamoDB, then invokes an AWS Lambda function to aggregate the metrics.
Monitor and verify results
Run the following steps to monitor and verify the test results.
Run the following command to get the details of the execution. Replace executionArn with your state machine ARN.
When the status shows SUCCEEDED, run the following commands to check the processed output from the LogAnalyticsSummaryTableName DynamoDB table. Replace the value LogAnalyticsSummaryTableName with the value from the sam deploy output.
The output of the Step Functions state machine shows the daily summary insights of the log files created by the Lambda function.
Clean up
To avoid costs, remove all resources created for this post once you’re done. Run the following command after replacing amzn-s3-demo-bucket1 with your own bucket name to delete the resources you deployed for this post’s solution:
aws s3 rm s3://amzn-s3-demo-bucket1 --recursive
sam delete
rm -rf logs/
Conclusion
In this post, you learned how AWS Step Functions Distributed Map can use prefix-based iteration with LOAD_AND_FLATTEN transformation to read and process multiple data objects from Amazon S3 buckets directly. You no longer need one step to process object metadata and another to load the data objects. Loading and flatting in one step is particularly valuable for data processing pipelines, batch operations, and event-driven architectures where objects are continually added to S3 locations. By eliminating the need to maintain object manifests, you can build more resilient, dynamic data processing workflows with less code and fewer moving parts.
New input sources for Distributed Map are available in all commercial AWS Regions where AWS Step Functions is available. To get started, you can use the Distributed Map mode today in the AWS Step Functions console. To learn more, visit the Step Functions developer guide.
For more serverless learning resources, visit Serverless Land.
Amazon SageMaker provides a single data and AI development environment to discover and build with your data. This unified platform integrates functionality from existing AWS Analytics and Artificial Intelligence and Machine Learning (AI/ML) services, including Amazon EMR, AWS Glue, Amazon Athena, Amazon Redshift, and Amazon Bedrock.
Organizations need to efficiently manage data assets while maintaining governance controls in their data marketplaces. Although manual approval workflows remain important for sensitive datasets and production systems, there’s an increasing need for automated approval processes with less sensitive datasets. In this post, we show you how to automate subscription request approvals within SageMaker, accelerating data access for data consumers.
Prerequisites
For this walkthrough, you must have the following prerequisites:
An AWS account – If you don’t have an account, you can create one. The account should have permission to do the following:
A demo project – Create a demo project in your SageMaker domain. For instructions, see Create a project. For this example, we choose All capabilities in the project profile section.
SageMaker domain ID, project ID, and project role ARN – These will be used in later steps to provide permissions for existing datasets and resources, and automatic subscription approval code. To retrieve this information, go to the Project details tab on the project details page on the SageMaker console.
Python installed – You must have Python version 3.8 or later.
IAM permissions – Sign in as the user with administrative access
Lambda permissions – Configure the appropriate IAM permissions for the Lambda execution role. The following code is a sample role used for testing this solution. Before implementing this IAM policy in your environment, provide the values for your specific AWS Region and account ID. Adjust them based on the principle of least privilege. To learn more about creating Lambda execution roles, refer to Defining Lambda function permissions with an execution role.
Understanding the subscription and approval workflow in Amazon SageMaker is important before diving deep into custom workflow solution. After an asset is published to the SageMaker catalog, data consumers can discover assets. When a data consumer discovers assets in SageMaker catalog, they request access to the asset, by submitting a subscription request with business justification and intended use case. The request enters a pending state and notifies the data producer or asset owner for review. The data producer evaluates the request based on governance policies, consumer credentials, and business context. The data producer can accept, reject, or request additional information from the data consumer. Upon acceptance, SageMaker triggers the AcceptSubscriptionRequest event and begins automated access provisioning. After a subscription is accepted, a subscription fulfilment process gets kicked off to facilitate access to the asset, for the data producer. SageMaker integrates deeply with AWS Lake Formation to manage fine-grained permissions. When a subscription is approved, SageMaker automatically calls Lake Formation APIs to grant specific database, table, and column-level permissions to the subscriber’s IAM role. Lake Formation acts as the central permission engine, translating subscription approvals into actual data access rights without manual intervention. The system provisions and updates resource-based policies on data sources. Once the provisioning completes, the data consumer can immediately access subscribed data through query engines like Athena, Redshift, or EMR, with Lake Formation enforcing permissions at query time.
By default, subscription requests to a published asset require manual approval by a data owner. However, Amazon SageMaker supports automatic approval of subscription requests at asset level: when publishing a data asset, you can choose to not require subscription approval. In this case, all incoming subscription requests to that asset are automatically approved. Let’s first outline the step-by-step process for disabling automatic approval at the asset level.
Configure automatic approval at asset level:
To configure automatic approval, data producers can follow the steps below.
Log in to SageMaker Unified Studio portal as data producer. Navigate to Assets and select the target asset
Choose Assets → Pick the asset, which you would like to configure for automatic approval.
On the asset details page, locate Edit Subscription settings in the right pane.
Choose Edit next to Subscription Required
Select Not Required in the dialogue box
Confirm your selection
Customize SageMaker’s subscription workflow:
While manual approval workflow remains essential for production environments and sensitive data handling, organizations seek to streamline and automate approvals for lower-risk environments and non-sensitive datasets. To achieve this project-level automation, we can enhance SageMaker’s native approval workflow through a custom event-driven solution. This solution leverages AWS’s serverless architecture, combining using AWS Lambda, Amazon EventBridge rules, and Amazon Simple Notification Service (Amazon SNS) to create an automated approval workflow. This customization allows organizations to maintain governance while reducing administrative overhead and accelerating the development cycle in non-critical environments. The event-driven approach ensures real-time processing of approval requests, maintains audit trails, and can be configured to apply different approval rules based on project characteristics and data sensitivity levels.
The custom workflow consists of the following steps:
The data consumer submits a subscription request for a published data asset.
SageMaker detects the request and generates a subscription event, which is automatically sent to EventBridge.
EventBridge triggers the designated Lambda function.
The Lambda function sends an AcceptSubscriptionRequest API call to SageMaker.
The function also sends a notification through Amazon SNS.
AWS Lake Formation processes the approved subscription and updates the relevant access control lists (ACLs) and permission sets.
The data consumer now has authorized access to the requested data asset and can begin working with the subscribed data.
The following diagram illustrates the high-level architecture of the solution.
Key benefits
This solution uses AWS Lambda and Amazon EventBridge to automate SageMaker subscription requests approvals, delivering the following benefits for organizations and end-users:
Scalability – Automatically handles high volumes of subscription requests
Cost-efficiency – Pay-as-you-go approach with no idle resource costs
Minimal maintenance – Serverless components require no infrastructure management
Flexible triggering – Supports event-driven, scheduled, and manual invocation modes
Audit compliance – Comprehensive logging and traceability through AWS CloudTrail
Step-by-step procedure
This section outlines the detailed process for implementing a custom subscription request approval workflow in Amazon SageMaker
Create Lambda function
Complete the following steps to create your Lambda function:
On the Lambda console, choose Functions in the navigation pane.
Choose Create function.
Select Author from scratch.
For Function name, enter a name for the function.
For Runtime, choose your runtime (for this post, we use Python version 3.9 or later).
Choose Create function.
On the Lambda function page, choose the Configuration tab and then choose Permissions.
Note the execution role to use when configuring the SageMaker project.
Create SNS topic
For this solution, we create SNS topic. Complete the following steps to create the SNS topic for automatic approvals:
On the Amazon SNS console, choose Topics in the navigation pane.
Choose Create topic.
For Type, select Standard.
For Name, enter a name for the topic.
Choose Create topic.
On the SNS topic details page, note the SNS topic Amazon Resource Name (ARN) to use later in the Lambda function.
On Subscription tab, choose Create Subscription.
For Protocol, choose Email.
For Endpoint, enter email address of Data consumers.
Create EventBridge rule
Complete the following steps to create an EventBridge rule to capture subscription request events:
On the EventBridge console, choose Rules in the navigation pane.
Choose Create rule.
For Name, enter a name for the rule.
For Rule type, select Rule with event pattern. This option enables the automatic subscription approval workflow to be triggered when a subscription request is initiated. Alternatively, you can select Schedule to schedule the rule to trigger on a regular basis. Refer to Creating a rule that runs on a schedule in Amazon EventBridge to learn more.
Choose Next.
For Event source, select AWS events or EventBridge partner events.
For Creation method, select Use pattern form
For Event source, select AWS services
For AWS service, select DataZone.
For Event type, select Subscription Request Created.
Configure your target to route events to both the Lambda function and SNS topic.
Choose Next.
For this post, skip configuring tags and choose Next.
Review the settings and choose Create rule.
Configure automation workflow
Complete the following steps to configure the automation workflow:
On the Lambda console, go to the function you created.
Configure the EventBridge rule to trigger the Lambda function
Configure the destination as SNS topic for event notification.
Configure code in Lambda function
Complete the following steps to configure your Lambda function:
On the Lambda console, go to the function you created.
Add the following code to your function. Provide the domain ID, project ID, and SNS topic ARN that you noted earlier.
import boto3
import json
import logging
import os
from botocore.exceptions import ClientError
# Configure logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def lambda_handler(event, context):
"""Lambda function to auto-approve subscription requests in Amazon SageMaker"""
try:
# Initialize clients
datazone_client = boto3.client('datazone')
sns_client = boto3.client('sns')
# Get configuration from environment variables or use hardcoded values
domain_id = os.environ.get('DOMAIN_ID', '<domain_id>')
project_id = os.environ.get('PROJECT_ID', '<project_id>')
sns_topic_arn = os.environ.get('SNS_TOPIC_ARN', '<sns_topic_arn>')
# Get pending subscription requests
pending_requests = get_pending_requests(datazone_client, domain_id, project_id)
if not pending_requests:
logger.info("No pending subscription requests found")
return
# Process requests
for request in pending_requests:
approve_request(datazone_client, sns_client, domain_id, request, sns_topic_arn)
except Exception as e:
logger.error(f"Error: {str(e)}")
def get_pending_requests(client, domain_id, project_id):
"""Get all pending subscription requests"""
requests = []
next_token = None
try:
while True:
params = {
'domainIdentifier': domain_id,
'status': 'PENDING',
'approverProjectId': project_id
}
if next_token:
params['nextToken'] = next_token
response = client.list_subscription_requests(**params)
if 'items' in response:
requests.extend(response['items'])
next_token = response.get('nextToken')
if not next_token:
break
logger.info(f"Found {len(requests)} pending requests")
return requests
except ClientError as e:
logger.error(f"Error listing requests: {e}")
return []
def approve_request(datazone_client, sns_client, domain_id, request, sns_topic_arn):
"""Approve a subscription request and send notification"""
request_id = request.get('id')
if not request_id:
return
try:
# Approve the request
datazone_client.accept_subscription_request(
domainIdentifier=domain_id,
identifier=request_id,
decisionComment="Subscription request is auto-approved by Lambda"
)
# Send notification
asset_name = request.get('assetName', 'Unknown asset')
message = f"Your subscription request has been auto-approved by Lambda. You can now access this asset."
sns_client.publish(
TopicArn=sns_topic_arn,
Subject=f"Subscription Request is auto-approved by Lambda",
Message=message
)
logger.info(f"Approved request {request_id} for {asset_name}")
except Exception as e:
logger.error(f"Error processing request {request_id}: {e}")
Configure Lambda and project execution roles in SageMaker
Complete the following steps:
In SageMaker Unified Studio, go to your publishing project.
Choose Members in the navigation pane.
Choose Add members.
Add the Lambda execution role and project execution roles as Contributor.
Test the solution
Complete the following steps to test the solution:
In SageMaker Unified Studio, navigate to the data catalog and choose Subscribe on the configured asset to initiate a subscription request.
Choose Subscription requests in the navigation pane to view the outgoing requests and choose the Approved tab to verify automatic approval.
Choose View subscription to confirm the approver appears as the Lambda execution role with “Auto-approved by Lambda” as the reason.
On the CloudTrail console, choose Event history to view the event you created and review the automated approval audit trail.
Clean up
To avoid incurring future charges, clean up the resources you created during this walkthrough. The following steps use the AWS Management Console, but you can also use the AWS CLI.
aws lambda delete-function --function-name <Lambda function name>
Conclusion
Combining an event-driven architecture with SageMaker creates an automated, cost-effective solution for data governance challenges. This serverless approach automatically handles data access requests while maintaining compliance, so organizations can scale efficiently as their data grows. The solution discussed in this post can help data teams access insights faster with minimal operational costs, making it an excellent choice for businesses that need quick, compliant data access while keeping their systems lean and efficient.
The rise of distributed data processing frameworks such as Apache Spark has revolutionized the way organizations manage and analyze large-scale data. However, as the volume and complexity of data continue to grow, the need for fine-grained access control (FGAC) has become increasingly important. This is particularly true in scenarios where sensitive or proprietary data must be shared across multiple teams or organizations, such as in the case of open data initiatives. Implementing robust access control mechanisms is crucial to maintain secure and controlled access to data stored in Open Table Format (OTF) within a modern data lake.
One approach to addressing this challenge is by using Amazon EMR on Amazon Elastic Kubernetes Service (Amazon EKS) and incorporating FGAC mechanisms. With Amazon EMR on EKS, you can run open source big data frameworks such as Spark on Amazon EKS. This integration provides the scalability and flexibility of Kubernetes, while also using the data processing capabilities of Amazon EMR.
On February 6th 2025, AWS introduced fine-grained access control based on AWS Lake Formation for EMR on EKS from Amazon EMR 7.7 and higher version. You can now significantly enhance your data governance and security frameworks using this feature.
In this post, we demonstrate how to implement FGAC on Apache Iceberg tables using EMR on EKS with Lake Formation.
Data mesh use case
With FGAC in a data mesh architecture, domain owners can manage access to their data products at a granular level. This decentralized approach allows for greater agility and control, making sure data is accessible only to authorized users and services within or across domains. Policies can be tailored to specific data products, considering factors like data sensitivity, user roles, and intended use. This localized control enhances security and compliance while supporting the self-service nature of the data mesh.
FGAC is especially useful in business domains that deal with sensitive data, such as healthcare, finance, legal, human resources, and others. In this post, we focus on examples from the healthcare domain, showcasing how we can achieve the following:
Share patient data securely – Data mesh enables different departments within a hospital to manage their own patient data as independent domains. FGAC makes sure only authorized personnel can access specific patient records or data elements based on their roles and need-to-know basis.
Facilitate research and collaboration – Researchers can access de-identified patient data from various hospital domains through the data mesh architecture, enabling collaboration between multidisciplinary teams across different healthcare institutions, fostering knowledge sharing, and accelerating research and discovery. FGAC supports compliance with privacy regulations (such as HIPAA) by restricting access to sensitive data elements or allowing access only to aggregated, anonymized datasets.
Improve operational efficiency – Data mesh can streamline data sharing between hospitals and insurance companies, simplifying billing and claims processing. FGAC makes sure only authorized personnel within each organization can access the necessary data, protecting sensitive financial information.
Producers: Create and serve domain-specific data products
Consumers: Access and integrate data products
Enables self-service data consumption
To demonstrate how you can use Lake Formation to implement cross-account FGAC within an EMR on EKS environment, we create tables in the AWS Glue Data Catalog in a central AWS account acting as producer and provision different user personas to reflect various roles and access levels in a separate AWS account acting as multiple consumers. Consumers can be spread across multiple accounts in real-world scenarios.
The following diagram illustrates the high-level solution architecture.
Figure 1: High Level Solution Architecture
To demonstrate the cross-account data sharing and data filtering with Lake Formation FGAC, the solution deploys two different Iceberg tables with varied access for different consumers. The permission mapping for consumers are with cross-account table shares and data cell filters.
It has two different teams with different levels of Lake Formation permissions to access Patients and Claims Iceberg tables. The following table summarizes the solution’s user personas.
Persona/Table Name
Patients
Claims
Patients Care Team
(team1 job execution role)
Exclude a column ssn
Include rows only from Texas and New York states
Full table access
Claims Care Team
(team2 job execution role)
No access
Full table access
Prerequisites
This solution requires an AWS account with an AWS Identity and Access Management (IAM) power user role that can create and interact with AWS services, including Amazon EMR, Amazon EKS, AWS Glue, Lake Formation, and Amazon Simple Storage Service (Amazon S3). Additional specific requirements for each account are detailed in the relevant sections.
Clone the project
To get started, download the project either to your computer or the AWS CloudShell console:
git clone https://github.com/aws-samples/sample-emr-on-eks-fgac-iceberg
cd sample-emr-on-eks-fgac-iceberg
Set up infrastructure in producer account
To set up the infrastructure in the producer account, you must have the following additional resources:
The setup script deploys the following infrastructure:
An S3 bucket to store sample data in Iceberg table format, registered as a data location in Lake Formation
An AWS Glue database named healthcare_db
Two AWS Glue tables: Patients and Claims Iceberg tables
A Lake Formation data access IAM role
Cross-account permissions enabled for the consumer account:
Allow the consumer to describe the database healthcare_db in the producer account
Allow to access the Patients table using a data cell filter, based on row-level selected state, and exclude column ssn
Allow full table access to the Claims table
Run the following producer_iceberg_datalake_setup.sh script to create a development environment in the producer account. Update its parameters according to your requirements:
export AWS_REGION=us-west-2
export PRODUCER_AWS_ACCOUNT=<YOUR_PRODUCER_AWS_ACCOUNT_ID>
export CONSUMER_AWS_ACCOUNT=<YOUR_CONSUMER_AWS_ACCOUNT_ID>
./producer_iceberg_datalake_setup.sh
# run the clean-up script before re-run the setup if needed
./producer_clean_up.sh
Enable cross-account Lake Formation access in producer account
A consumer account ID and an EMR on EKS Engine session tag must set in the producer’s environment. It allows the consumer to access the producer’s AWS Glue tables governed by Lake Formation. Complete the following steps to enable cross-account access:
Open the Lake Formation console in the producer account.
Choose Application integration settings under Administration in the navigation pane.
Select Allow external engines to filter data in Amazon S3 locations registered with Lake Formation.
For Session tag values, enter EMR on EKS Engine.
For AWS account IDs, enter your consumer account ID.
Choose Save.
Figure 2: Producer Account – Lake Formation third-party engine configuration screen with session tags, account IDs, and data access permissions.
Validate FGAC setup in producer environment
To validate the FGAC setup in the producer account, check the Iceberg tables, data filter, and FGAC permission settings.
Iceberg tables
Two AWS Glue tables in Iceberg format were created by producer_iceberg_datalake_setup.sh. On the Lake Formation console, choose Tables under Data Catalog in the navigation pane to see the tables listed.
Figure 3: Lake Formation interface displaying claims and patients tables from healthcare_db with Apache Iceberg format.
The following screenshot shows an example of the patients table data.
Figure 4: Patients table data
The following screenshot shows an example of the claims table data.
Figure 5: Claims table data
Data cell filter against patients table
After successfully running the producer_iceberg_datalake_setup.sh script, a new data cell filter named patients_column_row_filter was created in Lake Formation. This filter performs two functions:
Exclude the ssn column from the patients table data
Include rows where the state is Texas or New York
To view the data cell filter, choose Data filters under Data Catalog in the navigation pane of the Lake Formation console, and open the filter. Choose View permission to view the permission details.
Figure 6: Column and Row level filter configuration for patients table
FGAC permissions allowing cross-account access
To view all the FGAC permissions, choose Data permissions under Permissions in the navigation pane of the Lake Formation console, and filter by the database name healthcare_db.
Make sure to revoke data permissions with the IAMAllowedPrincipals principal associated to the healthcare_db tables, because it will cause cross-account data sharing to fail, particularly with AWS Resource Access Manager (AWS RAM).
Figure 7: Lake Formation data permissions interface displaying filtered healthcare database resources with granular access controls
The following table summarizes the overall FGAC setup.
Resource Type
Resource
Permissions
Grant Permissions
Database
healthcare_db
Describe
Describe
Data Cell Filter
patients_column_row_filter
Select
Select
Table
Claims
Select, Describe
Select, Describe
Set up infrastructure in consumer account
To set up the infrastructure in the consumer account, you must have the following additional resources:
An IAM role in the consumer account must be a Lake Formation administrator to run consumer_emr_on_eks_setup.sh script
The Lake Formation admin must accept the AWS RAM resource share invites using the AWS RAM console, if the consumer account is outside of the producer’s organizational unit
Figure 8: Consumer account – Cross-account RAM share for Lake Formation resource
The setup script deploys the following infrastructure:
An EKS cluster called fgac-blog with two namespaces:
User namespace: lf-fgac-user
System namespace:lf-fgac-secure
An EMR on EKS virtual cluster emr-on-eks-fgac-blog:
Set up with a security configuration emr-on-eks-fgac-sec-conifg
Two EMR on EKS job execution IAM roles:
Role for the Patients Care Team (team1): emr_on_eks_fgac_job_team1_execution_role
Role for Claims Care Team (team2): emr_on_eks_fgac_job_team2_execution_role
A query engine IAM role used by FGAC secure space: emr_on_eks_fgac_query_execution_role
An S3 bucket to store PySpark job scripts and logs
An AWS Glue local database named consumer_healthcare_db
Two resource links to cross-account shared AWS Glue tables: rl_patients and rl_claims
Lake Formation permission on Amazon EMR IAM roles
Run the following consumer_emr_on_eks_setup.sh script to set up a development environment in the consumer account. Update the parameters according to your use case:
export AWS_REGION=us-west-2
export PRODUCER_AWS_ACCOUNT=<YOUR_PRODUCER_AWS_ACCOUNT_ID>
export EKSCLUSTER_NAME=fgac-blog
./consumer_emr_on_eks_setup.sh
# run the clean-up script before re-run the setup if needed
./consumer_clean_up.sh
Enable cross-account Lake Formation access in consumer account
The consumer account must add the consumer account ID with an EMR on EKS Engine session tag in Lake Formation. This session tag will be used by EMR on EKS job execution IAM roles to access Lake Formation tables. Complete the following steps:
Open the Lake Formation console in the consumer account.
Choose Application integration settings under Administration in the navigation pane.
Select Allow external engines to filter data in Amazon S3 locations registered with Lake Formation.
For Session tag values, enter EMR on EKS Engine.
For AWS account IDs, enter your consumer account ID.
Choose Save.
Figure 9: Consumer Account – Lake Formation third-party engine configuration screen with session tags, account IDs, and data access permissions
Validate FGAC setup in consumer environment
To validate the FGAC setup in the producer account, check the EKS cluster, namespaces, and Spark job scripts to test data permissions.
EKS cluster
On the Amazon EKS console, choose Clusters in the navigation pane and confirm the EKS cluster fgac-blog is listed.
Kubernetes uses namespaces as logical partitioning system for organizing objects such as Pods and Deployments. Namespaces also operate as a privilege boundary in the Kubernetes role-based access control (RBAC) system. Multi-tenant workloads in Amazon EKS can be secured using namespaces.
This solution creates two namespaces:
lf-fgac-user
lf-fgac-secure
The StartJobRun API uses the backend workflows to submit a Spark job’s UserComponents (JobRunner, Driver, Executors) in the user namespace, and the corresponding system components in the system namespace to accomplish the desired FGAC behaviors.
You can verify the namespaces with the following command:kubectl get namespaceThe following screenshot shows an example of the expected output.
Figure 11: EKS Cluster namespaces
Spark job script to test Patients Care Team’s data permissions
The following script is a snippet of the PySpark job that retrieves filtered data for the Claims and Patient tables:
print("Patient Care Team PySpark job running on EMR on EKS! to query Patients and Claims tables!")
print("This job queries Patients and Claims tables!")
df1 = spark.sql('SELECT * FROM dev.${CONSUMER_DATABASE}.${rl_patients}')
print("Patients tables data:")
print("Note: Patients table is filtered on SSN column and it shows records only for Texas and New York states")
df1.show(20)
df2 = spark.sql('SELECT p.state,
c.claim_id,
c.claim_date,
p.patient_name,
c.diagnosis_code,
c.procedure_code,
c.amount,
c.status,
c.provider_id
FROM dev.${CONSUMER_DATABASE}.${rl_claims} c
JOIN dev.${CONSUMER_DATABASE}.${rl_patients} p
ON c.patient_id = p.patient_id
ORDER BY p.state, c.claim_date')
print("Show only relevant Claims data for Patients selected from Texas and New York state:")
df2.show(20)
print("Job Complete")
....
Spark job script to test Claims Care Team’s data permissions
The following script is a snippet of the PySpark job that retrieves data from the Claims table:
print("Claims Team PySpark job running on EMR on EKS to query Claims table!")
print("Note: Claims Team has full access to Claims table!")
df = spark.sql('SELECT * FROM dev.${CONSUMER_DATABASE}.${rl_claims}')
df.show(20)
....
Validate job execution roles for EMR on EKS
The Patients Care Team uses the emr_on_eks_fgac_job_team1_execution_role IAM role to execute a PySpark job on EMR on EKS. The job execution role has permission to query both the Patients and Claims tables.
The Claims Care Team uses the emr_on_eks_fgac_job_team2_execution_role IAM role to execute jobs on EMR on EKS. The job execution role only has permission to access Claims data.
Both IAM job execution roles have the following permissions:
For more details about how to work with Iceberg tables in EMR on EKS jobs, refer to Using Apache Iceberg with Amazon EMR on EKS. Complete the following steps to run the PySpark jobs on EMR on EKS with FGAC:
Run the following commands to run the patients and claims jobs:
Alternatively, you can navigate to the Amazon EMR console, open your virtual cluster, and choose the open icon next to the job to open the Spark UI and monitor the job progress.
Figure 12: EMR on EKS job runs
View PySpark jobs output on EMR on EKS with FGAC
In Amazon S3, navigate to the Spark output logs folder:
Figure 13: EMR on EKS job’s stdout.gz location on S3 Bucket
The Patients Care Team PySpark job has query access to the Patients and Claims tables. The Patients table has filtered out the SSN column and only shows records for Texas and New York claim records, as specified in our FGAC setup.
The following screenshot shows the Claims table for only Texas and New York.
Figure 14: EMR on EKS Spark job output
The following screenshot shows the Patients table without the SSN column.
Figure 15: EMR on EKS Spark job output
Similarly, navigate to the Spark output log folder for the Claims Care Team job:
As shown in the following screenshot, the Claims Care Team only has access to the Claims table, so when the job tried to access the Patients table, it received an access denied error.
Figure 16: EMR on EKS Spark job output
Considerations and limitations
Although the approach discussed in this post provides valuable insights and practical implementation strategies, it’s important to recognize the key considerations and limitations before you start using this feature. To learn more about using EMR on EKS with Lake Formation, refer to How Amazon EMR on EKS works with AWS Lake Formation.
Clean up
To avoid incurring future charges, delete the resources generated if you don’t need the solution anymore. Run the following cleanup scripts (change the AWS Region if necessary).Run the following script in the consumer account:
In this post, we demonstrated how to integrate Lake Formation with EMR on EKS to implement fine-grained access control on Iceberg tables. This integration offers organizations a modern approach to enforcing detailed data permissions within a multi-account open data lake environment. By centralizing data management in a primary account and carefully regulating user access in secondary accounts, this strategy can simplify governance and enhance security.
Amazon Redshift is a fully managed, petabyte-scale, cloud data warehouse service. You can use Amazon Redshift to run complex queries against petabytes of structured and semi-structured data quickly and efficiently, integrating seamlessly with other AWS services.
Amazon Redshift Serverless helps you run and scale analytics in seconds without having to set up, manage, or scale data warehouse infrastructure. It automatically provisions data warehouse capacity and intelligently scales the underlying resources to deliver fast performance for demanding workloads and you pay only for the compute capacity you use. Additionally, with Amazon Redshift managed storage, you can further optimize your data warehouse by scaling storage and compute independently and you pay only for the storage you use.
Upgrading your data warehouse from Amazon Redshift dense compute (DC2) instances to Amazon Redshift Serverless unlocks these advantages and provides an enhanced user experience and simplified operations, offering a more efficient, scalable solution for data analytics.
In this post, we show you the upgrade process from DC2 instances to Amazon Redshift Serverless. We’ll cover:
Assessing your current setup and determining if an upgrade is right for you
Planning and preparing for the upgrade
Step-by-step instructions for the upgrade process
Post-upgrade optimization and best practices
Why upgrade to Amazon Redshift Serverless
By using Amazon Redshift Serverless, you can run and scale analytics without managing data warehouse infrastructure. When you upgrade from DC2 instances to Amazon Redshift Serverless, you get the following benefits:
Simplified operations: Access and analyze data without needing to set up, tune, and manage compute clusters.
Pay-as-you-go pricing: The flexible pricing structure charges you only during active usage; you pay only for what you use.
Online maintenance: Amazon Redshift Serverless automatically manages system updates and patches without requiring maintenance windows, helping to facilitate seamless operation of your data warehouse.
Decoupled storage and compute: Control costs by scaling and paying for compute and storage separately with Amazon Redshift managed storage.
To upgrade from DC2 to Amazon Redshift Serverless, you need to understand the size equivalency. The following table shows suggested sizing configurations when upgrading from the DC2 node type.
Note that availability of Redshift Processing Unit (RPU) configurations varies by AWS Region.
Existing node type
Existing number of nodes
Amazon Redshift Serverless upgrade
DC2.large
1–4
Start with 4 RPUs
DC2.large
5–7
Start with 8 RPUs
DC2.large
8–32
Add 8 RPUs per 8 nodes of DC2.large
DC2.8xlarge
2–32
Add 16 RPUs per node (up to a maximum of 1,024 RPUs)
These sizing estimates provide a flexible starting point tailored to help you make the most of Amazon Redshift Serverless. The ideal configuration for your needs will depend on factors such as your desired balance of cost and performance and the specific latency and throughput requirements of your workload. To further optimize the sizing based on your specific requirements, you can use one or more of following approaches:
Test your workload beforehand: Before migrating to Amazon Redshift Serverless, evaluate your workload’s performance requirements in a non-production environment. The Amazon Redshift Test Drive utility simplifies this process by simulating your production workloads across different serverless configurations. You can use the results to help identify the optimal balance between performance and cost and make informed decisions about your configuration. For step-by-step guidance on using the Test Drive utility for DC2 to Serverless upgrades, see the Amazon Redshift Migration Workshop. Running these performance tests before migration helps you to identify any necessary adjustments to your configuration before deploying to production
Monitor in production: After you’ve deployed your workload, closely monitor the performance and resource utilization for over a period of time that represents your typical workloads. Based on the observed metrics, you can then scale the resources up or down as needed to achieve the best balance of performance and cost.
AI-driven scaling and optimization: Consider using Amazon Redshift Serverless with AI-driven scaling and optimization to automatically size Amazon Redshift Serverless for your workload needs.
A methodical approach to sizing validation, combining both pre-production testing and ongoing production monitoring, helps ensure your Amazon Redshift Serverless configuration aligns with your workload.
Upgrade to Amazon Redshift Serverless
To upgrade to Amazon Redshift Serverless, you can use a snapshot restore to move directly from Amazon Redshift to Amazon Redshift Serverless, as shown in the following figure. A snapshot restore restores data and objects in addition to users and their associated permissions, configurations, and schema structures. By using snapshot restore for migration, you can validate the target Amazon Redshift Serverless warehouses without impacting your production Amazon Redshift DC2 cluster. You can also use snapshot restore to migrate your Amazon Redshift DC2 workloads to different Regions or Availability Zones.
Amazon Redshift Serverless is encrypted by default. Amazon Redshift Serverless also supports changing the AWS KMS key for the namespace so you can adhere to your organization’s security policies.
Verify that the Amazon Redshift Serverless namespace you’re trying to restore to is attached to an Amazon Redshift Serverless workgroup.
To restore from a provisioned Amazon Redshift cluster to Amazon Redshift Serverless, the AWS Identity and Access Management (IAM) user or role must have the following permissions: redshift-serverless:RestoreFromSnapshot, CreateNamespace, and CreateWorkgroup. For more information, see Amazon Redshift Serverless restore.
Upgrade using the console
Use the following steps in the AWS Management Console for Amazon Redshift to upgrade your DC2 cluster to Amazon Redshift Serverless using the snapshot restore method.
On the Redshift console, choose Clusters in the navigation pane. Select your cluster and then choose Maintenance.
Choose Create snapshot to create a manual snapshot of the existing Amazon Redshift provisioned cluster.
Enter a snapshot identifier, select the snapshot retention period, and then choose Create snapshot.
Select the snapshot you want to restore to Amazon Redshift Serverless from the list and then choose Restore snapshot and select Restore to serverless namespace.
Under Select namespace, select your target serverless namespace from the dropdown list and then choose Restore.
The restoration time will vary based on your data volume.
After the restoration completes, verify your data migration by connecting to your Amazon Redshift Serverless workspace using either the Amazon Redshift Query Editor v2 or your preferred SQL client.
Use the following steps in the AWS Command Line Interface (AWS CLI) to upgrade your DC2 cluster to Amazon Redshift Serverless using the snapshot restore method.
Consider a CNAME. A Canonical Name (CNAME) record is a type of DNS record that you can use to create an alias for the endpoint of your Amazon Redshift cluster.
If you use interleaved sort keys, Amazon Redshift automatically converts them to compound keys when you restore a provisioned cluster snapshot to a serverless namespace. For more information, see Considerations when using Amazon Redshift Serverless.
Some concepts and features are different in Amazon Redshift Serverless than their corresponding feature for an Amazon Redshift provisioned data warehouse. These include differences in system tables and views, audit logging, and endpoint names. For a full list of these differences, see Comparing Amazon Redshift Serverless to an Amazon Redshift provisioned data warehouse.
Update existing connections: When you migrate to Amazon Redshift Serverless, a new endpoint will be created. Update any existing connections to business intelligence and other reporting tools.
Observability and monitoring: If you have any data monitoring tools using systems views, verify that there are no open or empty transactions. It’s important as a best practice to end transactions. If you don’t end or roll back open transactions, Amazon Redshift Serverless will continue to use RPUs for those transactions.
Access: When using IAM authentication with dbUser and dbGroups, your applications can access the database using the GetCredentials API. For more information, see Connecting using IAM.
System views: Review the list of unified system views available in Amazon Redshift Serverless.
In this section, we provide information to help you understand and manage your Amazon Redshift Serverless costs.
You can reduce your serverless computing costs by reserving capacity in advance when you have predictable usage patterns.
Amazon Redshift Serverless automatically adjusts capacity based on workload. By setting a maximum RPU limit, you can control costs by capping how much the system can scale up.
Amazon Redshift Serverless uses RPUs as a compute unit. While it starts with a default of 128 RPUs, you can adjust the base RPU anywhere from 4 to 1,024 RPUs to match your specific workload needs and SLA requirement. For more information, see Billing for Amazon Redshift Serverless.
Amazon Redshift Serverless automatically creates recovery points every 30 minutes or whenever 5 GB of data changes per node occur, whichever happens first. The minimum interval between recovery points is 15 minutes. All recovery points are retained for 24 hours by default.
If you need to preserve backups for a longer period, you can create manual backups. Manual backups will incur additional storage costs.
To avoid incurring future charges, delete the Amazon Redshift Serverless instance or provisioned data warehouse cluster created as part of the prerequisite steps. For more information, see Deleting a workgroup and Shutting down and deleting a cluster.
Conclusion
In this post, we discussed the benefits of upgrading Amazon Redshift DC2 instances to Amazon Redshift Serverless, in addition to the various options for upgrading and some best practices. It is essential to determine the target Amazon Redshift Serverless configuration and validate it using Amazon Redshift Test Drive utility in test and development environments before upgrading.
Get started upgrading to Amazon Redshift Serverless today by implementing the guidance in this post. If you have questions or need assistance, contact AWS Support forarchitectural and design guidance, in addition to support for proofs of concept and implementation.
Email’s universal adoption and accessibility make Amazon Simple Email Service (Amazon SES) an ideal platform for delivering critical business communications, such as customer notifications or password resets. However, the ubiquity of email also invites bad actors who seek to actively exploit email’s ubiquity to launch sophisticated attacks. Business email transmissions traverse a complex network with potential vulnerabilities, making email systems prime targets for these malicious actors. Common threats include message interception, email spoofing, unauthorized access to sending services, and service disruption attacks.
Amazon SES handles millions of sensitive communications daily. For example, healthcare providers transmit patient data, financial institutions send transaction alerts, and businesses exchange confidential information. Securing this critical infrastructure requires deep expertise in email systems, threat detection, and advanced security protocols to provide message integrity and confidentiality.
In this post, we discuss and guide you in enhancing your email security by using VPC endpoints with Amazon SES.
Common security challenges customers face sending email with Amazon SES
Consider the challenges faced by a large healthcare provider seeking to send automated appointment reminders and confidential lab results. Although Amazon SES meets their email delivery needs, the IT team must implement strict security measures to satisfy industry, government, and internal requirements. These likely include secure SMTP connections, identity-based access controls, and network isolation to safeguard sensitive patient information.
These common security requirements seek to address two critical concerns. First, they aim to prevent unauthorized access to the organization’s Amazon SES accounts, thereby safeguarding sensitive communications from potential breaches. Second, these measures mitigate the risks of bad actors co-opting their Amazon SES accounts to launch sophisticated email spoofing and phishing attacks.
Either breach could compromise trusted domains, undermining the security of the healthcare provider’s email communications and damaging their reputation.
For organizations with specific network security requirements or compliance mandates, Amazon SES offers VPC endpoint integration to provide additional network-level controls. This approach is particularly valuable for customers who prefer to avoid API calls traversing the public internet or need to ensure email processing workflows remain within private network boundaries.
VPC endpoints create a direct connection between your applications and Amazon SES, offering the following capabilities:
Enhanced network isolation: Keeps email traffic within your private network infrastructure
Compliance alignment: Supports regulatory frameworks like HIPAA and GDPR that may require additional network controls
Network-based access controls: Restricts SES access to authorized IP ranges and subnets
Simplified hybrid connectivity: Leverages existing VPN or Direct Connect infrastructure for seamless integration
Defense-in-depth architecture: Adds an additional layer of network security to your email infrastructure
Amazon SES VPC endpoints are enabled by AWS PrivateLink for SMTP message traffic. With these VPC endpoints, you can route SMTP email traffic privately within the AWS network between your sending applications, optionally with encryption, and Amazon SES. When using a VPC endpoint, traffic to Amazon SES doesn’t transmit over the internet and never leaves the Amazon network to securely connect your VPC to Amazon SES without availability risks or bandwidth constraints on your network traffic.
At the time of writing, Amazon SES VPC endpoints don’t support API-based email sending (such as SendEmail, SendRawEmail, or SDKs). Amazon SES API traffic should be encrypted and routed using a VPC through a NAT gateway or over the public internet.
Solution overview
Our solution can help you secure your SMTP message traffic by using the following components:
Authorized SMTP applications that optionally enforce TLS encryption and transport messages only over approved, private networks
The following diagram illustrates the solution architecture. The architecture assumes you already have connectivity from your on-premises network to your VPC. For instructions to connect your on-premises network to AWS, refer to Hybrid network connections.
For testing purposes, we use connectivity within AWS. The same concept applies if you’re connecting from an on-premises network that is connected to your VPC either through a Virtual Private Network (VPN) or Direct Connect (DX).
The solution workflow consists of the following steps:
Your SMTP sending applications and services are located on premises or in your data center using two subnets:
Subnet A (IP range: 10.10.10.50)
Subnet B (IP range: 10.90.120.50)
Secure connections are transmitted using AWS Direct Connect or VPN connection to a VPC in the same AWS Region as your Amazon SES account.
The SMTP message traffic, optionally encrypted, is sent to the Amazon SES VPC endpoints configured to restrict network connections from the VPC to only specific subnets:
Traffic on approved subnet A (10.10.10.50) is sent to Amazon SES.
Traffic on denied subnet B (10.90.120.50) is dropped (not sent to Amazon SES).
SMTP traffic from only the allowed subnet A is further restricted to an IAM policy with valid SMTP credentials.
Messages that conform to the traffic and authentication policies are passed to Amazon SES for final delivery to recipients.
Prerequisites
To implement this solution, you must have the following prerequisites:
Amazon SES, configured with at least one verified identity, in the same Region as the VPC.
An existing VPC in the same Region as Amazon SES. This can be the default VPC. For more information, see Plan your VPC.
An SMTP sending application (optionally supporting TLS encryption) located in one of the following options:
On premises or in a data center that is connected to the VPC through a private network connection (such as Direct Connect or VPN). For more details about private network connections to AWS, refer to Network-to-Amazon VPC connectivity options.
In the VPC running on a compute resource such as Amazon Elastic Compute Cloud (Amazon EC2) or AWS Lambda. For this post, we use an EC2 instance in the VPC and connect to Amazon SES through the VPC endpoint on port 587 with TLS enabled. Note that AWS blocks outbound SMTP traffic on port 25 across most AWS services. Use an alternative TCP port, such as 465, 587, 2465, or 2587. Request port 25 exemption by submitting a request to AWS Support from your AWS account using the “Request to remove email sending limitations” form. This can take upwards of 7 business days to be reviewed; approval is not guaranteed. Amazon SES uses an opportunistic TLS policy by default for encrypting messages when the receiving host supports it. You should use encryption whenever it is available.
For testing, you can use one of the following options:
Bash or Windows PowerShell script from on-premises server.
The first step is to create a security group with inbound rules that only allow a specific IP range on the appropriate port (host-permitting, 25, 465, 587, 2465, or 2587). In our example, we only allow subnet A (IP range: 10.10.10.50) on port 587. Complete the following steps to create the security group:
In the navigation pane of the Amazon EC2 console, under Network & Security, choose Security groups.
Choose Create security group.
For Security group name, enter a unique name that identifies the security group (we use ses-vpce-sec-group).
For Description, enter the purpose of the security group.
For VPC, choose the VPC in which you will host the application that will use Amazon SES.
Under Inbound rules, choose Add rule.
For Type, choose Custom TCP.
For Port range, enter the port number that you want to use to send email. You can choose from 465, 587, 2465, or 2587. For this post, we use 587.
For Source type, choose Custom.
Enter the private IP CIDR range for subnet A (IP range: 10.10.10.50), which contains the resources that will use the VPC endpoint to communicate with Amazon SES.
Choose Create security group.
Create VPC endpoint to connect the VPC to Amazon SES
Complete the following steps to create your VPC endpoint:
On the Amazon VPC console, in the navigation pane, under PrivateLink and Lattice, choose Endpoints.
Choose Create endpoint.
Optionally, under Endpoint settings, create a tag in the Name tag field.
For Service category, select AWS services.
For Services, filter for and select smtp.
For VPC, choose a VPC (for more details, see Prerequisites).
For Subnets, select Availability Zones and Subnet IDs. Amazon SES doesn’t support VPC endpoints in the following Availability Zones: use1-az2, use1-az3, use1-az5, usw1-az2, usw2-az4, apne2-az4, cac1-az3, and cac1-az4.
For Security groups, choose the security group you created earlier.
Optionally, for Tags, create one or more tags.
Choose Create endpoint. Wait approximately 5 minutes while Amazon VPC creates the endpoint. When the endpoint is ready to use, the value in the Status column changes to Available.
Copy the VPC endpoint ID to your clipboard to use in the next step.
Optionally, you can test the connection to make sure the VPC endpoint is configured properly by using command line tools to send a test email using the Amazon SES SMTP interface from an EC2 instance in the same VPC where you just created the email-smtp VPC endpoint. For more information, see Using the Amazon SES SMTP interface to send email.
Create SMTP credentials in Amazon SES that will be used by sender applications to authenticate
Complete the following steps to create SMTP credentials:
On the Amazon SES console, choose SMTP Settings in the navigation pane.
Choose Create SMTP credentials.
Enter your preferred user name and choose Create user.
Download the user’s SMTP credentials or copy the credentials to AWS Secrets Manager. (we will use these SMTP credentials in the next step).
Return to the SES console.
Limit traffic to the Amazon SES VPC endpoint using IAM
In this step, we limit traffic to the Amazon SES VPC endpoint using an IAM policy. The IAM policy has a condition that restricts access to aws:SourceVpce. Complete the following steps:
On the Amazon SES console, choose SMTP Settings in the navigation pane.
Choose Manage my existing SMTP credentials.
Choose the user you created earlier, then choose Permissions.
Choose the policy name AmazonSesSendingAccess to go to the IAM policy editor.
Replace the policy content in JSON view with the following policy, which adds the conditions for traffic to come from the Amazon SES VPC endpoint:
This screenshot shows the test result using the SMTP VPC Endpoint URL.
This configuration allows Amazon SES to only accept SMTP message traffic from applications from allowed on-premises subnets with connectivity to AWS and in the VPC that originates from the permitted SMTP IAM identity policy. This design follows the AWS least privilege access approach to security. To learn more, refer to Strategies for achieving least privilege at scale.
Clean up
After testing, if you don’t want to keep these configurations you should delete the EC2 instance, the VPC endpoint, the SMTP credential, and the IAM user.
Conclusion
In this post, we demonstrated how to implement a secure Amazon SES environment by combining multiple AWS security controls. By using Amazon SES VPC endpoints, security groups, and IAM policies, you can create a robust security architecture that restricts email sending capabilities to authorized networks only.
This multi-layered approach addresses critical security challenges by avoiding public internet exposure for SMTP traffic, enabling comprehensive traffic monitoring through VPC flow logs, and establishing defined network boundaries that satisfy strict compliance requirements.
The solution provides significant security benefits while maintaining the scalability and reliability that Amazon SES customers expect. Organizations can effectively protect sensitive email communications, prevent unauthorized access, and maintain compliance with industry regulations like HIPAA and GDPR. This becomes increasingly important as email-based threats continue to evolve and regulatory requirements become more stringent.
Start implementing these security controls today:
Deploy this solution in your development environment first, testing each component thoroughly
For additional guidance, consult the Amazon SES documentation, explore the AWS Security Blog for related articles, or engage with AWS Support. Remember to periodically review and update your security configurations as new features and best practices emerge.
Amazon SageMaker Catalog simplifies the discovery, governance, and collaboration for data and AI across Data Lakehouse, AI models, and applications. With Amazon SageMaker Catalog, you can securely discover and access approved data and models using semantic search with generative AI–created metadata or could just ask Amazon Q Developer with natural language to find their data.
Large enterprise customers have multiple lines of businesses who produce and consume data using a central SageMaker Data Catalog. Many customers have a central data governance team that is responsible for creating, publishing, and maintaining data governance standards and best practices across the firm. As the customer’s data platform scales, it becomes challenging for the central governance team to maintain the standards across all data producers and consumers. Because of this, many governance teams need to monitor user activity in Amazon SageMaker Catalog to ensure data assets are published according to established organizational governance standards and best practices. In this scenario, there is a need for automation where the central governance teams can be notified when critical events happen in Amazon SageMaker Catalog.
In this post, we show you how to create custom notifications for events occurring in SageMaker Catalog using Amazon EventBridge, AWS Lambda, and Amazon Simple Notification Service (Amazon SNS). You can expand this solution to automatically integrate SageMaker Catalog with in-house enterprise workflow tools like ServiceNow and Helix.
Solution overview
The following solution architecture shows how SageMaker Catalog integrates with other AWS services like AWS IAM Identity Center, Amazon EventBridge, Amazon SQS, AWS Lambda, and Amazon SNS to generate automated notifications to capture critical events in the enterprise catalog.
A SageMaker Catalog user logs into Amazon SageMaker Unified Studio using IAM Identity center. This could be a data scientist, machine learning engineer, or analyst looking for published data sets in the firm. AWS IAM Identity center ensures that only authorized personnel can access the cataloged assets and ML resources.
User performs an activity within SageMaker Catalog. Example user creates a new project or user searches for a data asset and creates a subscription request to access the asset.
User events from SageMaker Catalog are captured in Amazon EventBridge. Amazon EventBridge is a fully managed, serverless event bus service designed to help you build scalable, event-driven applications across AWS, SaaS, and custom applications. Amazon EventBridge provides the ability to filter events and allow users to take action on specific events.The following example event pattern in EventBridge filters DataZone create project events.
Amazon EventBridge sends the filtered events to Amazon SQS. Routing events to an SQS queue improves reliability and durability. Amazon SQS acts as a buffer between Amazon EventBridge and AWS Lambda, decoupling event producers from consumers. This allows your Lambda functions to process messages at their own pace, preventing overload during traffic spikes or when downstream resources are temporarily slow or unavailable. Amazon SQS provides durable, persistent storage for events. If Lambda service is unavailable or throttled, messages remain in the queue until they can be successfully processed, reducing the risk of data loss. There is a Dead Letter Queue (DLQ) attached to the main SQS queue. Attaching a DLQ to SQS ensures that any messages that can’t be processed after multiple attempts are safely captured for inspection and troubleshooting, preventing them from blocking or endlessly circulating in the main queue.
AWS Lambda function reads the messages from SQS queue. Lambda function formats the notification based on your needs.
AWS Lambda publishes the message to Amazon SNS. End users and Central Governance team can subscribe to the SNS topic to receive email alerts when an event happens in SageMaker catalog.
Amazon CloudWatch integrates with AWS Lambda to monitor performance, logs events, and can trigger alarms if anything goes awry, ensuring your workflows run smoothly.
Prerequisites
You need to setup the following prerequisite resources:
Grant Lambda Access in SageMaker Unified Studio (required for Publishing the assets)
Add the Lambda execution role as an IAM role in SageMaker Unified Studio.
Assign the Lambda execution role to your project within the SageMaker Unified Studio portal.
This configuration ensures that Lambda function has the required authorization to access Data Zone resources and successfully publish assets from your SageMaker Unified Studio projects.
Code Deployment
Review the instructions on our GitHub repository to deploy the framework in your AWS account using AWS CDK. The CDK provisions an event-driven notification architecture for Amazon SageMaker Unified Studio, focusing on project creation and asset publishing events.
Core AWS Resources Deployed – The following are the core AWS resourced deployed:
DataZonePublishAssetRule: Captures DataZone asset publishing events (CreateListingChangeSet with PUBLISH action for ASSET entity type).
SQS Queue
DataZoneEventQueue: Buffers DataZone events from EventBridge before processing.
Queue Policy: Allows EventBridge to send messages to the SQS queue.
Lambda Function
ProjectNotificationLambda: Processes messages from the SQS queue, retrieves event details from DataZone, and sends notifications to an SNS topic.
IAM Role: Grants permissions to access SQS, SNS, CloudWatch Logs, and DataZone services.
Event Source Mapping: Triggers the Lambda function for each SQS message.
SNS Topic
LambdaSNSTopic: Receives notifications from the Lambda function.
Email Subscriptions: Two email endpoints are subscribed to receive notifications.
Add your email ID to the SNS topic. You’ll receive an email to request for subscription, click on ‘Confirm Subscription’
Permissions
Amazon EventBridge sends events to SQS (requiring SQS permissions), Lambda poll reads messages from Amazon SQS (requiring Lambda role in SQS permissions), and Lambda publishes to Amazon SNS (requiring SNS permissions).
IAM Policies: Lambda execution role has necessary permissions for SQS, SNS, logging, and Data Zone operations.
Outputs Provided (CloudFormation Output)
Amazon SNS Topic ARN: For notification publishing.
Amazon SQS Queue ARN: For event buffering.
AWS Lambda Function ARN: For event processing.
Amazon EventBridge Rule ARNs: For both asset publishing and project creation events.
Project Creation Notification
Execute the following steps to login to SageMaker Unified Studio and create a project.
Login to SageMaker Unified Studio Console. This takes you to Amazon SageMaker Unified Studio domain login screen (SSO and IAM sign-in options).
Choose Create Project on SageMaker Unified Studio login page.
Choose a project name of your choice, such as ‘My_Demo_Project’. In Project profile, select ‘All-Capabilities’.
Choose Continue. Keep everything as default.
Choose Continue. On next page, create on ‘Create project’.
Project creation final screen
Email Notification. Once project creation is successful, you should see an email notification sent by the above deployed automation.
Asset Publish Notification
To publish a sample asset in SageMaker Unified Studio.
Lambda Permissions After the CDK Stack creates the Lambda execution role ‘DatazoneStack-LambdaExecutionRole’, use the following procedure to integrate this role into your SageMaker Studio project. This integration enables Lambda functions to interact with DataZone API in SageMaker Unified Studio project.
Login to SageMaker Unified studio using SSO, click on Members, Add members.
Find the role ‘DatazoneStack-LambdaExecutionRole’ and add as a ‘Contributor’
The LambdaExecutionRole (<cf-stack-name>-LambdaExecutionRole) has been added as a member to a project in SageMaker Unified Studio.
Create Asset
In your project ‘My_Demo_Project’, click on Data. Choose the plus sign to add a data set.
Upload your CSV file using the sample ‘Product_v6.csv’ found in the checkout folder of the ‘sample-sagemaker-unified-studio-governance-notifications’ GitHub repository.
Use table type as S3/external table.
Review and confirm that the column/attribute names in the uploaded CSV file.
Check the Glue database(glue_db_<unique_id>) to confirm that the table has been created and properly imported
Publish Asset
Select the asset, choose Actions and Publish to Catalog.
View the published asset below.
In the Project Catalog’s Assets section, locate the highlighted entry and verify the published table’s name
Choose the asset name to display additional details and properties about the table/asset.
Email Alerts
Once the asset is published to SageMaker Unified studio, you’ll receive an email alert sent with details of the published asset. Central governance teams can use this alert to review the published asset to ensure it aligns with the enterprise standards.
Email alerts are sent to notify users when assets have been published
Cleanup
To clean up your resources, complete the following steps:
cdk destroy --profile <PIPELINE-PROFILE>
Conclusion
In this post, you learned how to build an automated notification system for Amazon SageMaker Unified Studio using AWS services. Specifically, we covered:
How to set up event-driven notifications from Amazon SageMaker Unified Studio leveraging Amazon EventBridge, AWS Lambda, and Amazon SNS
The step-by-step process of deploying the solution using AWS CDK
Practical examples of monitoring critical events like project creation and asset publishing
How to integrate AWS Lambda permissions with SageMaker Unified Studio for secure operations
Best practices for implementing governance controls through automated notifications
Amazon SageMaker Catalog helps governance teams stay informed of catalog activities in real-time, enabling them to maintain organizational standards as their Data and ML platforms scale. The architecture is flexible and can be extended to integrate with enterprise workflow tools like ServiceNow or to monitor additional event types based on your organization’s needs.
We look forward to hearing how you adapt this solution for your organization’s governance needs. Fork the CDK code from our repository and share your implementation experience in the comments below
In this post, we show how to implement message feedback for SMS one-time passwords (OTPs) using AWS End User Messaging. OTP verification through SMS is a fundamental component of modern authentication systems. Although sending OTPs follows an established pattern, tracking their delivery and usage presents several challenges. This post shows how to implement the AWS End User Messaging Message Feedback API to monitor OTP delivery and conversion rates effectively. This post highlights the Message Feedback API in an OTP use case; for practical examples and detailed guidance on building a secure OTP architecture, see Build a Secure One-Time Password Architecture with AWS.
Challenges with OTP tracking
Organizations commonly face these key challenges with OTP tracking:
Relying solely on Delivery Receipt (DLR) data for confirming message delivery, which is third-party carrier data that can be subject to interpretation by carriers or message providers, whereas conversion tracking through message feedback provides first-party data that can more accurately reflect actual message delivery and usage
Measuring accurate user authentication success rates
Identifying OTP verification issues across different geographic regions, carriers and delivery paths
To address these challenges, you can use the AWS End User Messaging Message Feedback API to track delivery and conversion rates, providing first-party data for more accurate insights into message delivery and usage patterns. Although OTP use cases are the most common and serve as our example implementation of message feedback, the same tracking logic can also be applied to other types of SMS conversions, such as promotional link clicks, shopping cart additions, account activations, appointment confirmations, and delivery notifications.
Solution overview
The OTP message flow consists of two main phases. Let’s first examine how the system handles the initial OTP request.
Phase 1: OTP request flow
When a customer initiates an OTP request, your system begins a carefully orchestrated process. First, your application receives this request and generates a unique OTP. With the OTP generated, your system prepares to send it through the AWS End User Messaging API, specifically enabling message feedback tracking by setting the MessageFeedbackEnabled parameter to true when calling SendTextMessage.
Upon successful sending, it returns a unique message ID, which your system must store alongside the generated OTP. This message ID serves as a crucial tracking identifier for the entire verification process. The message is then dispatched to the customer’s device, and your system enters a waiting state, ready to process the verification attempt.
The following diagram illustrates the OTP request flow.
Phase 2: OTP verification flow
The verification process begins when the customer receives the OTP through SMS and submits it back to your system. Upon receiving the submission, your system first validates the OTP against the stored value. This verification step is critical, because its outcome determines how you will update the message feedback status.
If the customer successfully verifies the OTP, your system calls the PutMessageFeedback API with the stored message ID and sets the status to "RECEIVED", indicating successful delivery and usage of the OTP. However, if the verification fails or the customer doesn’t respond within the timeout period, your system sets the status to "FAILED".
If your system doesn’t explicitly update the feedback status within 1 hour, AWS automatically sets it to "FAILED".
The following diagram illustrates the OTP verification flow.
Prerequisites
Before you begin implementing OTP message feedback, make sure you have the following components and permissions in place:
AWS account (if you don’t have one, you can sign up for one)
An origination identity (sender ID, short code, long code) for AWS End User Messaging
AWS SDK version greater than or equal to 1.35.84 (make sure it has pinpoint-sms-voice-v2)
Send SMS with message feedback enabled
You can enable message feedback in two ways. The first method is to use the MessageFeedbackEnabled parameter when sending an SMS, the second is to send a message with a configuration set with message feedback already enabled. Using a configuration set is often more convenient for bulk implementations because you don’t need to specify message feedback settings in each API call.
To send an SMS with message feedback enabled directly, you can use the following function:
import boto3
# Initialize the End User Messaging client
client = boto3.client('pinpoint-sms-voice-v2')
def send_otp_with_feedback():
# Generate a unique OTP
otp = generate_otp()
# Send SMS with feedback enabled
response = client.send_text_message(
DestinationPhoneNumber='+15555550123', # Replace with your destination phone number
OriginationIdentity='+14255550120', # Replace with your origination identity
MessageBody=f'Your verification code is: {otp}',
MessageFeedbackEnabled=True
)
# Store OTP details for verification
store_otp_details(response['MessageId'], otp)
return response['MessageId']
The function uses the following details:
store_otp_details() is a placeholder function where you store the OTP details in a database for later retrieval
generate_otp() is a placeholder function where you generate your OTPs to send using SMS
If you prefer to use a configuration set with message feedback enabled, you can use the following alternative function:
def send_otp_with_feedback_using_configuration_set():
# Initialize the End User Messaging client
client = boto3.client('pinpoint-sms-voice-v2')
# Generate OTP
otp = generate_otp()
# Send SMS using configuration set
response = client.send_text_message(
DestinationPhoneNumber='+15555550123', # Replace with your destination phone number
OriginationIdentity='pool-201d59fffd554bdfbaf9ee8aEXAMPLE', # Replace with your origination identity
MessageBody=f'Your verification code is: {otp}',
ConfigurationSetName='example-us-east-configuration-set' # Replace with your configuration set name
)
# Store OTP details for later verification
store_otp_details(response['MessageId'], otp)
return response['MessageId']
Your configuration set must have message feedback enabled to use this option. You can enable it using the AWS Command Line Interface (AWS CLI) with the following command:
Another option is to use the AWS End User Messaging console, where you can enable message feedback under Set Settings for the desired configuration set.
Update feedback
After you send a message, you can update the message status to indicate whether a user has successfully completed an action, such as entering the OTP on your application or webpage:
def update_message_feedback(message_id: str, status: str) -> dict:
try:
# Initialize the End User Messaging client
client = boto3.client('pinpoint-sms-voice-v2')
# Update the message feedback status
response = client.put_message_feedback(
MessageId=message_id,
MessageFeedbackStatus=status
)
return response
except Exception as e:
print(f"Error updating message feedback: {str(e)}")
raise
# Example usage
message_id = "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111" # Replace with your message ID
status = "RECEIVED" # Use "FAILED" for unsuccessful verifications
result = update_message_feedback(message_id, status)
print(f"Feedback status updated: {result}")
Verify feedback metrics
The AWS End User Messaging dashboard provides comprehensive metrics to help you monitor your OTP performance. The following metrics are available for customizable time periods:
Number of messages with feedback completion
Percentage of messages with feedback completion
Number of SMS with feedback completion by country
To review your application’s overall message feedback metrics, choose Dashboard in the AWS End User Messaging console navigation pane, then choose Message Feedback Metrics.
The dashboard presents three key metrics:
Number of messages with feedback completion – The count of SMS and MMS messages where the message feedback record is set to RECEIVED
Percentage of messages with feedback completion – The percentage of SMS and MMS messages where the message feedback record is set to RECEIVED
Number of SMS with feedback completion by country – The count of message feedback received by country
The progression to 100% completion indicates optimal system performance, where all sent OTPs were successfully received and verified by users, and the message feedback record is set to RECEIVED within the expected timeframe. This high completion rate suggests effective message delivery and a smooth user verification experience. Variations in completion rates across countries can help identify potential regional delivery challenges or user behavior patterns.
The 30% conversion starting point shown in this example is used for illustration purposes only, demonstrating messages that were intentionally left unconverted during testing.
Best practices for OTP implementation
For a secure and reliable OTP implementation, follow these best practices to balance security with user experience:
Include rate limiting to prevent abuse
Implement proper timeout mechanisms for OTPs
Make sure error handling provides clear feedback to users
Maintain comprehensive logging for security audits
Conclusion
By implementing the Message Feedback API for OTP tracking, you can gain valuable insights into your authentication system’s effectiveness in real time. This approach helps you monitor successful OTP usage and identify potential delivery issues that might affect user authentication, with granular metrics broken down by geographic regions. The data collected through message feedback offers a more accurate picture of actual user interactions compared to carrier-provided delivery receipts, helping you make data-driven decisions about your authentication system.
To build upon this foundation, consider implementing Amazon CloudWatch alerts for your conversion metrics, and optimizing your message templates based on performance data. The combination of real-time feedback, detailed analytics, and proactive monitoring can help make sure your OTP system remains both secure and efficient.
For additional implementation guidance and best practices, refer to the following resources:
Amazon SageMaker Unified Studio provides a unified experience for using data, analytics, and AI capabilities. SageMaker Unified Studio now supports trusted identity propagation (TIP) for SQL workloads, enabling fine-grained data access control based on individual user identities. Organizations can use this integration to manage data permissions through AWS Lake Formation while using their existing single sign-on (SSO) infrastructure.
Organizations already using Amazon Redshift with TIP can extend their existing Lake Formation permissions to SageMaker Unified Studio. Users simply log in through SSO and access their authorized data using the SQL editor, maintaining consistent security controls across their analytics environment.
This post demonstrates how to configure SageMaker Unified Studio with SSO, set up projects and user onboarding, and access data securely using integrated analytics tools.
Solution overview
For our use case, a retail corporation is planning to implement sales analytics to identify sales patterns and product categories that are doing well. This will help the sales team improve on sales planning with targeted promotions and help the finance team plan budgeting with better inventory management. The corporation stores a customer table in an Amazon Simple Storage Service (Amazon S3) data lake and a store_sales table in a Redshift cluster.
The corporation uses SageMaker Unified Studio as the UI, with users onboarded from their identity provider (IdP) to AWS IAM Identity Center with TIP. Amazon SageMaker Lakehouse centralizes data from Amazon S3 and Amazon Redshift, and Lake Formation provides fine-grained access control based on user identity. For our example use case, we explore two different users. The following table summarizes their roles, the tools they use, and their data access.
User
Group
Tool
Data Access
Ethan (Data Analyst)
Sales
Amazon Athena for interactive SQL analysis
Non-sensitive customer data (id, c_country, birth_year) and store_sales full table access
Frank (BI Analyst)
Finance
Amazon Redshift for reports and visualization
US customer data (c_country='US')
The following diagram illustrates the solution architecture.
SageMaker Unified Studio with IAM Identity Center simplifies the user journey from authentication to data analysis. The workflow consists of the following steps:
Users sign in with organizational SSO credentials through their IdP and are redirected to SageMaker Unified Studio.
Users configure IAM Identity Center authentication for Amazon Redshift, linking identity management with data access.
Users access the query editor for Amazon Redshift or SageMaker Lakehouse, triggering IAM Identity Center federation to generate session and access tokens.
SageMaker Unified Studio retrieves user authorization details and group membership using the session token.
Users are authenticated as IAM Identity Center users, ready to explore and analyze data using Amazon Redshift and Amazon Athena.
To implement our solution, we walk through the following high-level steps:
Set up SageMaker Lakehouse resources.
Create a SageMaker Unified Studio domain with SSO and TIP enabled.
Configure Amazon Redshift for TIP and validate access.
Validate data access using Amazon Athena.
Prerequisites
Before you begin implementing the solution, you must have the following in place:
If you don’t have an AWS account, you can sign up for one.
We provide utility scripts to help set up various sections of the post. To use them:
Right-click this link and save the utility scripts zip file.
Run the scripts only when prompted in the relevant sections.
Note: The utility scripts are configured for us-east-1 region. If you prefer another region, edit the region in the scripts before running them.
To deploy the infrastructure, right-click this link and select ‘Save Link As’ to save it as sagemaker-unified-studio-infrastructure.yaml. Then upload the file when creating a new stack in the AWS CloudFormation console, which will create the following resources:
An S3 bucket to hold the customer data used in this post.
If you don’t have a Lake Formation user, you can create one. For this post, we use an admin user. For instructions, see Create a data lake administrator.
If you need to migrate existing Redshift users and groups, use the IAM Identity Center Redshift migration utility.
For a quick way to test the feature and familiarize yourself with the process, we provide a script to generate mock users and groups. Run the setup-idc.sh script, which is provided in Step 2, to create test users and groups in IAM Identity Center for demonstration purposes.
On the Lake Formation console, choose Data lake locations in the navigation pane.
Choose Register location.
For the role, use LakeFormationRegistrationRole.
Create an IAM Identity Center Redshift application, as detailed in our previous post:
On the Amazon Redshift console, choose IAM Identity Center connections in the navigation pane and choose Create application.
For both the display name and application name, enter redshift-idc-app.
Set the IdP namespace to awsidc.
Choose IAMIDCRedshiftRole as the IAM role.
Choose Next to create the application.
Take note of the application Amazon Resource Name (ARN) to use in subsequent steps. The ARN format is arn:aws:sso::<ACCOUNT_NUMBER>:application/ssoins-<RANDOM_STRING>/apl-<RANDOM_STRING>.
If you don’t have existing Redshift tables to work with, run the script setup-producer-redshift.sh, which is provided in Step 2, to create a producer namespace and workgroup, set up a sample sales database, and generate necessary tables with test data.
The post also uses simulated customer data stored in the AWS Glue Data Catalog. To set up this data and configure the necessary Lake Formation permissions, run the setup-glue-tables-and-access.sh script provided in Step 2.
Set up SageMaker Lakehouse resources
In this section, we configure the foundational lakehouse resources required for SageMaker to access and analyze data across multiple storage systems. We’ll register the Redshift instance to the AWS Glue Data Catalog to make warehouse data discoverable and establish Lake Formation permissions on lakehouse resources for user identities to ensure secure, governed access to both data lake and data warehouse resources from within SageMaker environments.
Register Redshift instance to the Data Catalog
In this step, we use the store_sales data, which we created earlier using the setup-producer-redshift.sh script. You can register entire clusters to the Data Catalog and create catalogs managed by AWS Glue. To register a cluster to the Data Catalog, complete the following steps:
On the Lake Formation console, choose Administrative roles and tasks in the navigation pane.
Under Data lake administrators, choose Add.
Choose Read-only administrator, then choose AWSServiceRoleForRedshift.
On the Amazon Redshift console, open your namespace.
On the Actions dropdown menu, chose Register with AWS Glue Data Catalog, then choose Register.
Sign in to the Lake Formation console as the data lake administrator and choose Catalogs in the navigation pane.
Under Pending catalog invitations, select the namespace and accept the invitation by choosing Approve and create catalog.
Provide the name for the catalog as salescatalog.
Select Access this catalog from Apache Iceberg compatible engines, choose DataTransferRole for the IAM role, then choose Next.
Choose Add permissions and choose the admin IAM role under IAM users and roles.
Select Super user for catalog permissions and choose Add.
Choose Next.
Choose Create catalog.
Set up Lake Formation permission on lakehouse resources for user identities
In this section, we configure Lake Formation permissions to enable secure access to lakehouse resources for federated user identities. Lake Formation provides fine-grained access control that works seamlessly with IAM Identity Center, allowing you to manage permissions centrally while maintaining security boundaries.
We’ll focus on granting database access to IAM Identity Center groups in Lake Formation and setting table-level permissions for federated Redshift catalog tables. These permissions form the security foundation for our federated query architecture, enabling users to seamlessly access both S3 data lake and Redshift data warehouse resources through a unified interface.
Grant database access to IAM Identity Center groups in Lake Formation
After you share your Redshift catalog with the Data Catalog and integrate with Lake Formation, you must grant appropriate database access. Follow these steps to set up permissions on your data lake resources for corporate identities:
On the Lake Formation console, under Permissions in the navigation pane, choose Data permissions.
Choose Grant.
Select Principals for Principal type.
Under Principals, select IAM Identity Center and choose Add.
In the pop-up window, if this is your first time assigning users and groups, choose Get started.
Search for and select the IAM Identity Center groups awssso-sales and awssso-finance.
Choose Assign.
Under LF-Tags or catalog resources, choose Named Data Catalog resources.
Choose <accountid>:salescatalog/dev for Catalogs.
Choose sales_schema for Database.
Under Database permissions, select Describe.
Choose Grant to apply the permissions.
Grant table-level permissions for federated Redshift catalog tables
Complete the following steps to grant table permissions to the IAM Identity Center groups:
On the Lake Formation console, under Permissions in the navigation pane, choose Data permissions.
Choose Grant.
Select Principals for Principal type.
Under Principals, select IAM Identity Center and choose Add.
In the pop-up window, if this is your first time assigning users and groups, choose Get started.
Search for and select the IAM Identity Center group awssso-sales.
Choose Assign.
Under LF-Tags or catalog resources, choose Named Data Catalog resources.
Choose <accountid>:salescatalog/dev for Catalogs.
Choose sales_schema for Database.
Choose store_sales for Table.
Select Select and Describe for Table permissions.
Choose Grant to apply the permissions.
Create a SageMaker Unified Studio domain with SSO and TIP enabled
For instructions to create a SageMaker Unified Studio domain, refer to Create an Amazon SageMaker Unified Studio domain – quick setup. Because your IAM Identity Center integration is already complete, you can specify an IAM Identity Center user in the domain configuration settings.
Enable TIP in SageMaker Unified Studio
Complete the following steps to enable TIP in SageMaker Unified Studio:
On the SageMaker console, use the AWS Region selector in the top navigation bar to choose the appropriate Region.
Choose View domains and choose the domain’s name from the list.
On the domain’s details page, on the Project profiles tab, choose a project profile, for example, SQL analytics.
Select SQL analytics and choose Edit.
In the Blueprint parameters section, select enableTrustedIdentityPropagationPermissions and choose Edit.
Update the value as true.
To enforce authorization-based on TIP, the SageMaker Unified Studio admin can make this parameter non-editable.
Choose Save.
Enable user access for SageMaker Unified Studio domain
Complete the following steps to enable user access for the SageMaker Unified Studio domain:
Open the SageMaker console in the appropriate Region and choose Domains in the navigation pane.
Choose an existing SageMaker Unified Studio domain where you want to add SSO user access.
On the domain’s details page, on the User management tab, in the Users section, choose Add and Add SSO users and groups.
Choose the user (for this post, we add the user Frank) from the dropdown list and choose Add users and groups.
Add project members
SageMaker Unified Studio projects facilitate team collaboration for different business initiatives. As the project owner, Ethan now can add Frank as a team member to enable their collaboration. To add members to an existing project, complete the following steps:
Sign in to the SageMaker Unified Studio console using the SSO credentials of who owns the project (for this post, Ethan).
Choose Select a project.
Choose the project you want to edit.
On the Project overview page, expand Actions and choose Manage members.
Choose Add members.
Enter the name of the user or group you want to add (for this post, we add Frank).
Select Contributor if you want to add the project member as a contributor.
(Optional) Repeat these steps to add more project members. You can add up to eight project members at a time.
Choose Add members.
Create a SQL analytics project in Unified Studio
In this step, we federate into SageMaker Unified Studio and create a project using SQL analytics. Complete the following steps:
Federate into SageMaker Unified Studio using your IAM Identity Center credentials:
On the SageMaker console, choose Domains in the navigation pane.
Copy the SageMaker Unified Studio URL for your domain and enter it into a new browser window.
Choose Sign in with SSO.
A browser pop-up will redirect you to your preferred IdP login page, where you enter your IdP credentials.
If authentication if successful, you will be redirected to SageMaker Unified Studio.
After logging in, choose Create project.
Enter a name for your project. This project name is final and can’t be changed later.
(Optional) Enter a description for your project. You can edit this later.
Choose a project profile. For this demo, we choose the SQL analytics profile from the available templates.
Leave the default values as they are or modify them according to your use case, then choose Continue.
Choose Create project to finalize the project and initialize your SQL analytics workspace.
For more detailed information and advanced configurations, refer to Create a project.
Configure Amazon Redshift for TIP and validate access
Run the setup-consumer-redshift.sh script (provided in the prerequisites). This script will create a new namespace and workgroup and add the required tags, which you will use later to integrate with SageMaker Unified Studio compute.
If you are creating the cluster manually, add one of the following tags to the Redshift cluster or workgroup that you want to add to SageMaker Unified Studio:
Option 1 – Add a tag to allow only a specific SageMaker Unified Studio project to access it: AmazonDataZoneProject=<projectID>
Option 2 – Add a tag to allow all SageMaker Unified Studio projects in this account to access it: for-use-with-all-datazone-projects=true
Create compute using IAM Identity Center authentication
After you set up your project, the next step is to establish a compute resource connection on the SageMaker Unified Studio console. Follow these steps to add either Amazon Redshift Serverless or a provisioned cluster to your project environment:
Go to the Compute section of your project in SageMaker Unified Studio.
On the Data warehouse tab, choose Add compute.
You can create a new compute resource or choose an existing one. For this post, we choose Connect to existing compute resources, then choose Next.
Choose the type of compute resource you want to add, then choose Next. For this post, we choose Redshift Serverless.
Under Connection properties, provide the JDBC URL or the compute you want to add, which is integrated with IAM Identity Center. If the compute resource is in the same account as your SageMaker Unified Studio project, you can select the compute resource from the dropdown menu. In our example, we use the consumer account that was just provisioned.
Under Authentication, select IAM Identity Center.
For Name, enter the name of the Redshift Serverless or provisioned cluster you want to add.
For Description, enter a description of the compute resource.
Choose Add compute.
The SageMaker Unified Studio Project Compute and Data pages will now display information for that resource.
If everything is configured correctly, your compute will be created using IAM Identity Center. Because your IdP credentials are already cached while you’re logged in to SageMaker Unified Studio, it uses the same credentials and creates the compute.
Test data access using Amazon Redshift
When Ethan logs in to SageMaker Unified Studio using IAM Identity Center authentication, he successfully federates and can access customer data from all countries but only for non-sensitive columns. Let’s connect to Amazon Redshift in SageMaker Unified Studio by following these steps:
Choose Actions and choose Open Query editor.
Choose Redshift in the Data explorer pane.
Run the customer sales calculation query to observe that user Ethan (a data analyst) can access customer data from all countries but only non-sensitive columns (id, birth_country, product_id):
select current_user, c.*, sum(s.sales_amount) as total_sales
from "awsdatacatalog"."customerdb"."customer" c
join "dev@salescatalog"."sales_schema"."store_sales" s
on c.id=s.id
group by all;
You have successfully configured Redshift to use IAM Identity Center authentication in SageMaker Unified Studio.
Validate data access using Amazon Athena
When Frank logs in to SageMaker Unified Studio using IAM Identity Center authentication, he successfully federates and can access customer data only for the United States. To query with Athena, complete the following steps:
Choose Actions and choose Open Query editor.
Choose Lakehouse in the Data explorer pane.
Explore AwsDataCatalog, expand the database, choose the respective table, and on the options menu (three dots), choose Preview data.
The following demonstration illustrates how user Frank, a BI analyst, can perform SQL analysis using Athena. Due to row-level filtering implemented through Lake Formation, Frank’s access is restricted to customer data from the United States only. Additionally, you can observe that in the Data explorer pane, Frank can only view the customerdb database. The dev@salescatalog database is not visible to Frank because no access has been granted to his respective group from Lake Formation.
The IAM Identity Center authentication integration is complete; you can use both Amazon Redshift and Athena through SageMaker Unified Studio in a simplified, all-in-one interface.Note that, at the time of writing, Athena doesn’t work with Redshift Managed Storage (RMS).
Clean up
Complete the following steps to clean up the resources you created as part of this post:
Delete the data from the S3 bucket.
Delete the Data Catalog objects.
Delete the Lake Formation resources and Athena account.
Delete the SageMaker Unified Studio project and associated domain.
If you created new Redshift cluster for testing this solution, delete the cluster.
Conclusion
In this post, we provided a comprehensive guide to enabling trusted identity propagation within SageMaker Unified Studio. We covered the setup of a SageMaker Unified Studio domain with SSO, the creation of tailored projects, efficient user onboarding with appropriate permissions, and the management of AWS Glue and Amazon Redshift managed catalog permissions using Lake Formation. Through practical examples, we demonstrated how to use both Amazon Redshift and Athena within SageMaker Unified Studio, showcasing secure data access and analysis capabilities. This approach helps organizations maintain strict identity controls while helping data scientists and analysts derive valuable insights from both data lake and data warehouse environments, supporting both security and productivity in machine learning workflows.
Modern applications require deployment strategies that minimize downtime and reduce risk. Blue/green deployment is a strategy that reduces downtime and risk by running two identical production environments called “blue” and “green”. At any given time, only one environment serves live production traffic while the other remains idle. This strategy provides immediate fallback to the previous stable version if issues arise after the new deployment. Let’s say a company is deploying a new version of its application. The following diagram shows the blue/green deployment strategy they are using.
As shown in the preceding diagram, current production traffic is served by the blue environment. During deployment of the new version of the application, the following sequence of activities happens:
Deploy the new version of the application: Deploy the new version to the green environment.
Test thoroughly: Test the new version in the green environment by invoking the API invoke URL from API Gateway. This does not affect production traffic, which continues to be served by the blue environment.
Switch traffic: After you have thoroughly tested the green environment, redirect all production traffic from the blue to the green environment.
Monitor and take any necessary action: Continue to monitor the green environment as it serves production traffic. Keep the blue environment ready for immediate rollback to the previous stable version, in case any issues arise in the green environment. At this point, one of two possible outcomes happens:
If you identify any issues with the green environment in production, roll back to the previous stable version of the blue environment and fix the green environment before retrying.
If you observe no issues with the green environment, decommission the blue environment. The green environment is now the new blue environment, the environment with stable production version of the application serving live traffic.
In this post, you learn how to implement blue/green deployments by using Amazon API Gateway for your APIs. For this post, we use AWS Lambda functions on the backend. However, you can follow the same strategy for other backend implementations of the APIs. All the required infrastructure is deployed by using AWS Serverless Application Model (AWS SAM).
Solution overview
As you follow along with this post, you will implement the following blue/green deployment architecture by using API Gateway custom domain API mapping. You use API mappings to connect API stages to a custom domain name. After you create a domain name and configure DNS records, you use API mappings to send traffic to your APIs through your custom domain name.
As shown in the preceding diagram, the blue/green deployment architecture includes four primary AWS services – Amazon Route 53, Amazon API Gateway, AWS Lambda functions, and AWS Certificate Manager (ACM). When you send a request to the API, the Route 53 resolves the domain to the API Gateway custom domain. API Gateway handles HTTPS termination by using a configured ACM certificate. API Gateway examines the incoming request path and headers to route the request to the active environment.
You first set up the blue environment along with the Route 53 DNS configuration, API Gateway custom domain mapping, ACM and test it with Route 53 URL. This is your production environment serving live traffic. After that, deploy a new version of the application in the green environment and test it by invoking the API invoke URL from API Gateway while live traffic is still being served from the blue environment. Then, switch the traffic from the blue environment to the green environment by using API Gateway custom domain API mapping. This ensures that there is no change in the external (client-facing) API custom domain URL. Live traffic is now served by the green environment. If you observe any issues during this time, you can quickly roll back to the blue environment and fix the green environment. If the green environment is stable, you can decommission the blue environment.
This post uses two separate regional API endpoints to simulate blue/green environments and traffic routing between them but you can this same architectural pattern using single API endpoint with two stages representing blue and green environments.
Prerequisites
Complete the following prerequisites before you start setting up the solution:
Note that this is a sample project to understand the concept and not for direct usage in production. The sample project contains three APIs.
Health GET API to know the current health of the environment and which environment the request was served from.
Pets GET API to get the list of available pets.
Order POST API to place a pet order.
Follow the steps below to setup blue/green deployment and test it.
Clone the repository and navigate to the directory (all commands run from here) Clone the GitHub repository in a new folder and navigate to the stacks folder.
git clone https://github.com/aws-samples/sample-blue-green-deployment-with-api-gateway.git
cd sample-blue-green-deployment-with-api-gateway/stacks
Deploy the blue environment You will first setup the blue environment. Run the following commands to deploy the blue environment:
sam build -t blue-stack.yaml
sam deploy -g -t blue-stack.yaml
Enter the following details:
Stack name: The CloudFormation stack name (for example, blue-green-api-blue)
AWS Region: A supported AWS Region (for example, us-east-1)
BlueLambdaFunction has no authentication. Is this okay?: y
SAM configuration file: blue-samconfig.toml
Keep everything else set to their default values. You will use the SAM deploy output for the subsequent steps. Going forward, you can run the following command to deploy the blue environment resources:
sam build -t blue-stack.yaml
sam deploy -t blue-stack.yaml --config-file blue-samconfig.toml
Test the blue environment
Run the following commands to test the blue environment after replacing ApiEndpoint with BlueApiEndpoint from the SAM deploy output in each case. First, test Health check API to know the health of the environment. Run the following command.
curl --request GET \
--url https://<ApiEndpoint>/health
Check that the response contains the environment attribute set to blue and the version attribute set to v1.0.0
Deploy API Gateway custom domain pointing to the blue environment
Run the following commands to deploy Amazon API Gateway custom domain with API mapping pointing to the blue environment created in the previous step.
sam build -t custom-domain-stack.yaml
sam deploy -g -t custom-domain-stack.yaml
Enter the following details:
Stack name: (for example, blue-green-api-custom-domain)
AWS Region: A supported AWS Region (for example, us-east-1)
PublicHostedZoneId: The Route 53 public hosted zone ID (for example, ABXXXXXXXXXXXXXXXXXYZ)
CustomDomainName: The Route 53 domain name (for example, api.example.com)
CertificateArn: The ACM certificate ARN (for example, arn:aws:acm:us-east-1:123456789012:certificate/abc123)
ActiveApiId: The value of the BlueApiId output from the blue-stack deployment
ActiveApiStage: The value of the BlueApiStage output from the blue-stack deployment
SAM configuration file: custom-domain-samconfig.toml
Keep everything else to their default values. You will use the SAM deploy output for the subsequent steps. At this point the production (live) traffic is routed to blue environment.
Test the production (live) traffic which is routed to blue environment
Follow the test method mentioned in step 3 to test the production environment, but replace ApiEndpoint with CustomDomainUrl. Check that the production environment response contains the environment attribute set to blue and the version attribute set to v1.0.0
Deploy the green environment
You will now deploy the v2.0.0 of the application on green environment. Run the following commands to deploy the green environment:
sam build -t green-stack.yaml
sam deploy -g -t green-stack.yaml
Enter the following details:
Stack name: (for example, blue-green-api-green)
AWS Region: Select the same Region as the blue environment (for example, us-east-1)
GreenLambdaFunction has no authentication. Is this okay?: y
SAM configuration file: green-samconfig.toml
Keep everything else to default values. You will use the SAM deploy output for the subsequent steps. Going forward, you can run the following commands to deploy the green environment.
sam build -t green-stack.yaml
sam deploy -t green-stack.yaml --config-file green-samconfig.toml
Test the green environment Follow the test method shown in step 3 to test the production environment, but replace ApiEndpoint with GreenApiEndpoint. Validate that the response contains the environment attribute set to green and the version attribute set to v2.0.0
Switch the live traffic to the green environment Run the following command to switch live traffic to the green environment:
sam deploy -g -t custom-domain-stack.yaml --config-file custom-domain-samconfig.toml
Enter the following details:
Stack name: Keep it as it is.
AWS Region: Keep it as it is.
PublicHostedZoneId: Keep it as it is.
CustomDomainName: Keep it as it is.
CertificateArn: Keep it as it is.
ActiveApiId: The value of GreenApiEndpoint output from the green-stack deployment
ActiveApiStage: The value of GreenApiStage output from the green-stack deployment
SAM configuration file: Keep it as it is.
Keep everything else at their default values.
Test the production environment (now green) again
Follow the test method shown in step 3 to test the production environment (now green) again, and be sure to replace ApiEndpoint with CustomDomainUrl from SAM deploy output. Validate that the response now contains the environment attribute set to green and the version attribute set to v2.0.0. Note that it may take a minute or two for the change to be seen due to local DNS caching, during this time some of the traffic may be still served from the blue environment. After switching the live traffic to the green environment, if there is an issue, you can switch the live traffic back to the blue environment and fix the green environment. Depending on whether you need to roll back to the previous stable blue environment or decommission the blue environment when you no longer need it, follow either step 10 or 11.
(Option 1) Roll back to the blue environment, if necessary Run the following command to roll back to the blue environment, if necessary.
sam deploy -g -t custom-domain-stack.yaml --config-file custom-domain-samconfig.toml
Enter the following details:
Stack name: Keep it as it is.
AWS Region: Keep it as it is.
PublicHostedZoneId: Keep it as it is.
CustomDomainName: Keep it as it is.
CertificateArn: Keep it as it is.
ActiveApiId: Value of BlueApiEndpoint output from the blue-stack deployment.
ActiveApiStage: The value of BlueApiStage output from the blue-stack deployment.
SAM configuration file: Keep it as it is.
Keep everything else to their default values. Live traffic is switched to the blue environment. You can confirm that by following step 3.
(Option 2) Decommission the blue environment when you no longer need it Run the following command to decommission (delete) the blue environment when you no longer need it. Replace blue-stack-name with your blue deployment stack name:
sam delete --stack-name <blue-stack-name> --no-prompts
Clean up
To avoid costs, remove all resources created along this post once you’re done.
Run the following command after replacing the <placeholder> variables to delete the resources you deployed for this post’s solution:
# Delete all stacks (in reverse order)
# Delete custom domain
sam delete --stack-name <api-custom-domain-stack-name> --no-prompts
# Delete green stack
sam delete --stack-name <green-stack-name> --no-prompts
# Delete blue stack, if already not deleted in step 10
sam delete --stack-name <blue-stack-name> --no-prompts
Conclusion
Blue/green deployments with API Gateway provide a robust, scalable solution for zero-downtime deployments that deliver significant technical and operational advantages. This post’s solution architecture enables traffic switching at the API Gateway level while maintaining complete isolation between the blue and green environments to prevent interference. The solution offers immediate rollback capabilities for quick issue resolution and supports comprehensive testing through production-like validation before any traffic switching occurs.
Following this solution you can build a solid foundation for production blue/green deployments for your serverless microservice architecture that maintains the flexibility to adapt to your specific requirements while ensuring reliability, scalability, and operational excellence. To learn more about serverless architectures see Serverless Land.
This is a guest post by Supreet Padhi, Technology Architect, and Manasa Ramesh, Technology Architect at Precisely in partnership with AWS.
Enterprises rely on mainframes to run mission-critical applications and store essential data, enabling real-time operations that help achieve business objectives. These organizations face a common challenge: how to unlock the value of their mainframe data in today’s cloud-first world while maintaining system stability and data quality. Modernizing these systems is critical for competitiveness and innovation.
The digital transformation imperative has made mainframe data integration with cloud services a strategic priority for enterprises worldwide. Organizations that can seamlessly bridge their mainframe environments with modern cloud platforms gain significant competitive advantages through improved agility, reduced operational costs, and enhanced analytics capabilities. However, implementing such integrations presents unique technical challenges that require specialized solutions. Some of the challenges include converting EBCDIC data to ASCII, where the handling of data types is unique to the mainframe, such as binary data and COMP data. Data stored in Virtual Storage Access Method (VSAM) files can be quite complex due to practices to store multiple different record types in a single file. To address these challenges, Precisely—a global leader in data integrity, serving over 12,000 customers—has partnered with Amazon Web Services (AWS) to enable real-time synchronization between mainframe systems and Amazon Relational Database Service (Amazon RDS). For more on this collaboration, check out our previous blog post: Unlock Mainframe Data with Precisely Connect and Amazon Aurora.
In this post, we introduce an alternative architecture to synchronize mainframe data to the cloud using Amazon Managed Streaming for Apache Kafka (Amazon MSK) for greater flexibility and scalability. This event-driven approach provides additional possibilities for mainframe data integration and modernization strategies.
A key enhancement in this solution is the use of the AWS Mainframe Modernization – Data Replication for IBM z/OS Amazon Machine Image (AMI) available in AWS Marketplace, which simplifies deployment and reduces implementation time.
Real-time processing and event-driven architecture benefits
Real-time processing makes data actionable within seconds rather than waiting for batch processing cycles. For example, financial institutions such as Global Payments have leveraged this solution to modernize mission-critical banking operations, including payments processing. By migrating these operations to the AWS Cloud, they enhanced user experience, improved scalability and maintainability, while enabling advanced fraud detection – all without impacting the performance of existing mainframe systems. Change data capture (CDC) enables this by identifying database changes and delivering them in real time to cloud environments.
CDC offers two key advantages for mainframe modernization:
Incremental data movement – Eliminates disruptive bulk extracts by streaming only changed data to cloud targets, minimizing system impact and ensuring data currency
Real-time synchronization – Keeps cloud applications in sync with mainframe systems, enabling immediate insights and responsive operations
Solution overview
In this post, we provide a detailed implementation guide for streaming mainframe data changes from DB2z through AWS Mainframe Modernization – Data Replication for IBM z/OS AMI to Amazon MSK and then applying those changes to Amazon Relational Database Service (Amazon RDS) for PostgreSQL using MSK Connect with the Confluent JDBC Sink Connector.
By introducing Amazon MSK into architecture and streamlining deployment through the AWS Marketplace AMI, we create new possibilities for data distribution, transformation, and consumption that expand upon our previously demonstrated direct replication approach. This streaming-based architecture offers several additional benefits:
Simplified deployment – Accelerate implementation using the preconfigured AWS Marketplace AMI
Decoupled systems – Separate the concern of data extraction from data consumption, allowing both sides to scale independently
Multi-consumer support – Enable multiple downstream applications and services to consume the same data stream according to their own requirements
Extensibility – Create a foundation that can be extended to support additional mainframe data sources such as IMS and VSAM, as well as additional AWS targets using MSK Connect sink connectors
The following diagram illustrates the solution architecture.
Capture/Publisher – Connect CDC Capture/Publisher captures Db2 changes from Db2 logs using IFI 306 Read and communicates captured data changes to a target engine through TCP/IP.
Controller Daemon – The Controller Daemon authenticates all connection requests, managing secure communication between the source and target environments.
Apply Engine – The Apply Engine is a multifaceted and multifunctional component in the target environment. It receives the changes from the Publisher agent and applies the changed data to the target Amazon MSK.
Connect CDC Single Message Transform (SMT) – Performs all necessary data filtering, transformation, and augmentation required by the sink connector.
JDBC Sink Connector – As data arrives, an instance of the JDBC Sink Connector along with Apache Kafka writes the data to target tables in Amazon RDS.
This architecture provides a clean separation between the data capture process and the data consumption process, allowing each to scale independently. The use of MSK as an intermediary enables multiple systems to consume the same data stream, opening possibilities for complex event processing, real-time analytics, and integration with other AWS services.
Prerequisites
To complete the solution, you need the following prerequisites:
Create a DB cluster by using the following AWS Command Line Interface (AWS CLI) command. Replace the placeholder strings with values that correspond to your cluster’s subnet and subnet group IDs.
To create a serverless MSK cluster, complete the following steps:
Copy the following JSON and paste it into a new file create-msk-serverless-cluster.json. Replace the placeholder strings with values that correspond to your cluster’s subnet and security group IDs.
To create a Kafka topic, you need to install the Kafka CLI first. Follow these steps:
Download the binary distribution of Apache Kafka and extract the archive in folder kafka:
wget https://dlcdn.apache.org/kafka/3.9.0/kafka_2.13-3.9.0.tgz
tar -xzf kafka_2.13-3.9.0.tgz
ln -sfn kafka_2.13-3.9.0 kafka
To use IAM to authenticate with the MSK cluster, download the Amazon MSK Library for IAM and copy to the local Kafka library directory as shown in the following code. For complete instructions, refer to Configure clients for IAM access control.
Copy the following JSON and paste it into a new file create-custom-plugin.json. Replace the placeholder strings with values that correspond to your bucket.
Prepare the source table. Before configuring the Capture/Publisher, ensure the DEPT source table exists on your mainframe Db2 system. The table definition should match the structure defined at \$SQDATA_VAR_DIR/templates/dept.ddl. If you need to create this table on your mainframe, use the DDL from this file as a reference to ensure compatibility with the replication process.
Access the Interactive System Productivity Facility (ISPF) interface. Sign in to your mainframe system and access the AWS Mainframe Modernization – Data Repication for IBM z/OS ISPF panels through the supplied ISPF application menu. Select option 3 (CDC) to access the CDC configuration panels, as demonstrated in our previous blog post.
Add source tables for capture:
From the CDC Primary Option Menu, choose option 2 (Define Subscriptions).
Choose option 1 (Define Db2 Tables) to add source tables.
On the (Add DB2 Source Table to CAB File panel), enter a wildcard value (%) or the specific table name DEPT in the (Table Name) field.
Press Enter to display the list of available tables.
Type S next to the DEPT table to select it for replication, then press Enter to confirm.
This process is like the table selection process shown in figure 3 and figure 4 of our previous post but now focuses specifically on the DEPT table structure.
With the completion of both the Db2 Capture/Publisher setup on the mainframe and the AWS environment configuration (Amazon MSK, Apply Engine, and MSK Connect JDBC Sink Connector), you now have a fully functional pipeline ready to capture data changes from the mainframe and stream them to the MSK topic. Inserts, updates, or deletions to the DEPT table on the mainframe will be automatically captured and pushed to the MSK topic in near real time. From there, the MSK Connect JDBC Sink Connector and the custom SMT will process these messages and apply the changes to the PostgreSQL database on Amazon RDS, completing the end-to-end replication flow.
Configure Apply Engine for Amazon MSK integration
Configure the AWS side components to receive data from the mainframe and forward it to Amazon MSK. Follow these steps to define and manage a new CDC pipeline from DB2 z/OS to Amazon MSK:
Use the following command to switch to the connect user:
Copy the following content and paste it in a new file $SQDATA_VAR_DIR/apply/DB2ZTOMSK/scripts/DB2ZTOMSK.sqd. Replace the placeholder strings with values that correspond to the DB2z endpoint:
-----------------------------------------------------------------------
Name: DB2TOKAF: Z/OS DB2 To Kafka
-----------------------------------------------------------------------
SUBSTITUTION PARMS USED IN THIS SCRIPT:
---------------------------------------------------------------------
JOBNAME DB2TOKAFKA;
-----------------------------
TABLE DESCRIPTIONS
---------------------------
BEGIN GROUP SOURCE_TABLES;
DESCRIPTION Db2SQL /var/precisely/di/sqdata/apply/DB2ZTOMSK/ddl/dept.ddl AS DEPT KEY IS DEPTNO;
END GROUP;
-------------------------------------------------------------
DATASTORE SECTION
-------------------------------------------------------------
SOURCE DATASTORE
DATASTORE cdc://<DB2z endpoint with port>/dbcg/DBCG_TBTSS388T6 OF UTSCDC AS CDCIN DESCRIBED BY GROUP SOURCE_TABLES;
-- TARGET DATASTORE
DATASTORE kafka:///pgsql-sink-topic/table_key OF JSON AS TARGET KEY IS DEPTNO DESCRIBED BY GROUP SOURCE_TABLES;
---------------------------------
PROCESS INTO TARGET
SELECT { REPLICATE(TARGET) } FROM CDCIN;
The following is an example of the output that you get when you invoke the command successfully:
SQDC042I mounting/running sqdparse with arguments:
SQDC041I args[0]:sqdparse
SQDC041I args[1]:/var/precisely/di/sqdata/apply/DB2ZTOMSK/scripts/DB2ZTOMSK.sqd
SQDC041I args[2]:/var/precisely/di/sqdata/apply/DB2ZTOMSK/scripts/DB2ZTOMSK.prc
SQDC000I *******************************************************
SQDC021I sqdparse Version 5.0.1-rel (Linux-x86_64)
SQDC022I Build-id 4f2d7c16728aa2e40c610db7d5a6e373476a9889
SQDC023I (c) 2001, 2025 Syncsort Incorporated. All rights reserved.
SQDC000I *******************************************************
SQDC000I
SQD0000I 2025-03-31 00:59:10
>>> Start Preprocessed /var/precisely/di/sqdata/apply/DB2ZTOMSK/scripts/DB2ZTOMSK.sqd
000001 ----------------------------------------------------------------------
000002 -- Name: DB2TOKAF: Z/OS DB2 To Kafka
000003 ----------------------------------------------------------------------
000004 -- SUBSTITUTION PARMS USED IN THIS SCRIPT:
000005 ----------------------------------------------------------------------
000006
000007 JOBNAME DB2TOKAFKA;
000008
000009 ----------------------------
000010 -- TABLE DESCRIPTIONS
000011 ----------------------------
000012 BEGIN GROUP SOURCE_TABLES;
000013 DESCRIPTION Db2SQL /var/precisely/di/sqdata/apply/DB2ZTOMSK/ddl/dept.ddl AS DEPT
000014 KEY IS DEPTNO;
000015 END GROUP;
000016
000017 ------------------------------------------------------------
000018 -- DATASTORE SECTION
000019 ------------------------------------------------------------
000020
000021 -- SOURCE DATASTORE
000022 DATASTORE /var/precisely/di/sqdata/apply/DB2ZTOMSK/scripts/DB0A.ENGINE3.DEPT.COPY
000023 OF UTSCDC
000024 AS CDCIN
000025 DESCRIBED BY GROUP SOURCE_TABLES;
000026
000027 -- TARGET DATASTORE
000028 DATASTORE
000029 OF JSON
000030 AS TARGET
000031 KEY IS DEPTNO
000032 DESCRIBED BY GROUP SOURCE_TABLES;
000033
000034 ----------------------------------
000035
000036 PROCESS INTO TARGET
000037 SELECT
000038 {
000039 REPLICATE(TARGET)
000040 }
000041 FROM CDCIN;
<<< End Preprocessed /var/precisely/di/sqdata/apply/DB2ZTOMSK/scripts/DB2ZTOMSK.sqd
>>> Start Preprocessed /var/precisely/di/sqdata/apply/DB2ZTOMSK/ddl/dept.ddl
000001 CREATE TABLE DEPARTMENT
000002 (
000003 DEPTNO char(3) NOT NULL,
000004 DEPTNAME varchar(36) NOT NULL,
000005 MGRNO char(6),
000006 ADMRDEPT char(3) NOT NULL,
000007 LOCATION char(16),
000008 CONSTRAINT PK_DEPTNO PRIMARY KEY (DEPTNO)
000009 ) ;
<<< End Preprocessed /var/precisely/di/sqdata/apply/DB2ZTOMSK/ddl/dept.ddl
Number of Data Stores...................: 2
Data Store..............................: /var/precisely/di/sqdata/apply/DB2ZTOMSK/scripts/DB0A.ENGINE3.DEPT.COPY
Alias.................................: CDCIN
Type..................................: UTS Change Data Capture
Number of Records.....................: 1
Record Name.........................: DEPARTMENT
Record Description Alias............: DEPT
Record Description Length...........: 72
Number of Fields....................: 5
................................... TYPE OFF LEN XLEN EXT
................................... ---------- ----- ----- ----- -----
DEPTNO............................: CHAR(3) 0 3 3
DEPTNAME..........................: VARCHAR(36) 3 38 38
MGRNO.............................: CHAR(6) 7 6 6
ADMRDEPT..........................: CHAR(3) 14 3 3
LOCATION..........................: CHAR(16) 17 16 16
Data Store..............................:
Alias.................................: TARGET
Type..................................: JSON
Number of Records.....................: 1
Record Name.........................: DEPARTMENT
Record Description Alias............: DEPT
Record Description Length...........: 70
Number of Fields....................: 5
................................... TYPE OFF LEN XLEN EXT
................................... ---------- ----- ----- ----- -----
DEPTNO............................: CHAR(3) 0 3 3
DEPTNAME..........................: VARCHAR(36) 3 38 38
MGRNO.............................: CHAR(6) 41 6 6
ADMRDEPT..........................: CHAR(3) 47 3 3
LOCATION..........................: CHAR(16) 50 16 16
Section.................................: SQDSTP000
Number of steps.......................: 1
SQDC017I sqdparse(pid=4023) terminated successfully
Copy the following content and paste it in a new file /var/precisely/di/sqdata_logs/apply/DB2ZTOMSK/sqdata_kafka_producer.conf. Replace the placeholder strings with values that correspond to your bootstrap server and AWS Region.
Invoke the following command to verify the data in the PostgreSQL database:
PGPASSWORD="password" psql --host=<DATABASE-HOST> --username=<user> --dbname=<database> -c "select * from \"DEPT\""
With these steps completed, you’ve successfully set up end-to-end data replication from DB2z to RDS for PostgreSQL, using AWS Mainframe Modernization – Data Replication for IBM z/OS AMI, Amazon MSK, MSK Connect, and the Confluent JDBC Sink Connector.
Cleanup
When you’re finished testing this solution, you can clean up the resources to avoid incurring additional charges. Follow these steps in sequence to ensure proper cleanup.
By capturing changed data from DB2z and streaming it to AWS targets, organizations can modernize their legacy mainframe data stores, enabling operational insights and AI initiatives. Businesses can use this solution to take advantage of cloud-based applications with mainframe data to provide scalability, cost-efficiency, and enhanced performance.
The integration of AWS Mainframe Modernization – Data Replication for IBM z/OS AMI with Amazon MSK and RDS for PostgreSQL provides an enhanced framework for real-time data synchronization that maintains data integrity. This architecture can be extended to support additional mainframe data sources such as VSAM and IMS, as well as other AWS targets. Organizations can then tailor their data integration strategy to specific business needs. Data consistency and latency challenges can be effectively managed through AWS and Precisely’s monitoring capabilities. By adopting this architecture, organizations keep their mainframe data continually available for analytics, machine learning (ML), and other advanced applications.Streaming mainframe data to AWS in near real time represents a strategic step toward modernizing legacy systems while unlocking new opportunities for innovation, with data transfers occurring in subseconds. With Precisely and AWS, organizations can effectively navigate their modernization journey and maintain their competitive advantage.
Learn more about AWS Mainframe Modernization – Data Replication for IBM z/OS AMI in the Precisely documentation. AWS Mainframe Modernization Data Replication is available for purchase in AWS Marketplace. For more information about the solution or to see a demonstration, contact Precisely.
At AWS, we’ve designed our global infrastructure with isolated AWS Regions to help you achieve high fault tolerance and stability for your applications. These AWS Regions are organized into partitions, each with distinct network and security boundaries.
As your business evolves, you might need to migrate workloads between AWS Regions. Perhaps you’re looking to reduce latency for users in new geographic areas, meet Region-specific compliance requirements, or you’re an ISV expanding your product’s availability. Whatever your motivation, cross-Region migration needs careful planning, especially when dealing with encrypted resources.
When migrating Amazon Elastic Compute Cloud (Amazon EC2) instances with encrypted Amazon Elastic Block Storage (Amazon EBS) volumes across AWS Regions with in the same account or a different account, you face a particular challenge: AWS Key Management Service (AWS KMS) keys are AWS Region-specific and cannot be shared across AWS Regions. This post provides a step-by-step approach to successfully migrate your encrypted EC2 instances without compromising your security posture by sharing your KMS keys.
Solution overview
The following diagram and steps are an overview of how an EC2 instance can be migrated to a different Region in a different account without sharing the KMS keys.
Figure 1:Design to migrate EC2 between two accounts
Prerequisites
The following prerequisites are necessary to complete this solution:
Create an S3 bucket in both the source and target Region.
Check the availability of the AMI under the EC2 section in the target. You should find a new AMI ID along with the source Region information.
Figure 9: AMI created in the target account
Launch the instance using the migrated AMI in the target Region.
Figure 10: Launched EC2 instance in the target account
Limitations
Following are the limitations with this process:
To store an AMI, your AWS account must either own the AMI and its snapshots, or the AMI and its snapshots must be shared directly with your account. You can’t store an AMI if it is only publicly shared.
Only Amazon EBS-backed AMIs can be stored using these APIs.
Paravirtual (PV) AMIs are not supported.
The size of an AMI (before compression) that can be stored is limited to 5,000 GB.
Quota on store image requests: 1,200 GB of storage work (snapshot data) in progress.
Quota on restore image requests: 600 GB of restore work (snapshot data) in progress.
For the duration of the store task, the snapshots must not be deleted and the AWS Identity and Access Management (IAM) principal doing the store must have access to the snapshots, otherwise the store process fails.
You can’t create multiple copies of an AMI in the same S3 bucket.
An AMI that is stored in an S3 bucket can’t be restored with its original AMI ID. You can mitigate this by using AMI aliasing.
Currently the store and restore APIs are only supported by using the AWS Command Line Interface (AWS CLI),AWS SDKs, and Amazon EC2 API. You can’t store and restore an AMI using the Amazon EC2 console.
Clean up resources
When you have successfully deployed the server in the target Region you can delete the S3 buckets that were created for this migration. You can also terminate EC2 and delete associated EBS volumes and snapshots if you do not need them to avoid additional cost.
Conclusion
In this post, we showed you how to migrate an Amazon EC2 instances into another Region in a different account without sharing any AWS KMS keys in a secured manner.
AWS Nitro Enclaves provide isolated environments that keep critical operations such as decryption and cryptographic key management secure from both from root user and external threats.
Many customers have applications that require end-to-end authentication using Transport Layer Security (TLS) and requiring control over TLS termination.
TLS termination refers to the process where encrypted TLS traffic is decrypted using the server’s private key, converting the secure encrypted communication back to plaintext for processing. TLS termination can be done directly within an enclave, helping to ensure that encrypted traffic is not exposed outside the trusted boundary.
This is particularly valuable for public-facing services such as anonymization proxies and Model Context Protocol (MCP) servers, where clients demand assurance that their communications are protected and the application’s integrity can be independently verified using cryptographic attestation in a remote fashion.
Specifically, in this blog we explore patterns on how:
you can build applications that are remotely verifiable by clients, including enclave-based TLS termination using Nitriding, an open-source framework built by Brave and AWS Nitro Enclaves.
This post builds on our workshop “Build multi-party crypto wallets with AWS Nitro Enclaves” which demonstrates a Shamir Secret Sharing (SSS) application. The SSS app securely splits cryptographic private keys into multiple shards, requiring a threshold number to reconstruct the original key, ideal for Nitro Enclaves as it prevents any single party from accessing the complete key while maintaining operational functionality.
To follow along hands-on, you’ll need to deploy the provided AWS Cloud Development Kit (CDK) stack from the workshop repository on GitHub. However, you can understand the concepts and architecture discussed in this post without deploying the solution yourself.
Solution architecture
The following diagram depicts the high-level architecture of the solution.
Before we dive deep into the application design, lets introduce the high-level components enclosed in the AWS Cloud Development Kit (AWS CDK) stack:
A dedicated virtual private cloud (VPC) and private subnets are created. Internet access is only possible through a NAT gateway, avoiding public exposure of the Amazon Elastic Compute Cloud (EC2) instances.
EC2 instances are placed in several private subnets and in different Availability Zones (AZ) using the auto-scaling group (ASG) to provide high availability. Network Load Balancer (NLB) is used to distribute the requests between different EC2 instances in the ASG. Each EC2 instance has one AWS Nitro enclave associated.
Amazon DynamoDB is used to store the key shards for the Shamir Secret Sharing (SSS) solution.
Application design
During the AWS CDK deployment process (shown in the following figure), the following application will be built and deployed to the EC2 instance and the associated enclave. You can review the Python source code for the different components in the public GitHub repository.
EC2 instance (left side)
gvproxy: Proxy component that manages outbound and inbound TCP to vsock connections.
watchdog: Systemd service that starts the enclave and makes sure it stays up and healthy.
imds proxy: Systemd service that forwards Instance Metadata calls originating from vsock to 169.254.169.254. This allows the enclave to request fresh IMDSv2 credentials.
Enclave (right side)
TAP interface: gvproxy counterpart. A fully routed network interface created by nitriding-daemon that allows inbound and outbound traffic routing in the enclave.
imds proxy: IMDS proxy counterpart that allows the enclave to request credentials from its parent instance metadata service.
nitriding-daemon: HTTPS service that terminates incoming HTTPS connections, responds to attestation requests, and forwards all /app* HTTP requests to the sss app HTTP listener.
SSS application: An SSS application that interacts with all AWS services such as AWS KMS or DynamoDB through Boto3 and provides key management and signing capabilities.
Nitro Secure Module: Enclave internal /dev/nsm device that provides attestation and random number generator capabilities. Attestation private/public keys are managed by AWS.
Enclave based TLS termination and Remote Validation
Let’s now see how we can achieve TLS termination inside the enclave and allow remote clients to verify the enclaves code.
To do so, we are using Nitriding, a Go toolkit that simplifies running web applications inside AWS Nitro Enclaves without requiring networking stack changes. It uses gvproxy to create a tap0 interface, enabling controlled inbound and outbound traffic for the application inside the enclave.
Let’s have a look at the most important features nitriding offers.
TLS Termination: Nitriding generates an ephemeral private/public key pair on first launch, issuing a self-signed certificate for TLS. Furthermore, it supports Let’s Encrypt certificates for production use.
Application integration: Nitriding terminates TLS and forwards all /app* HTTP requests to the HTTP listener of the configured application. In the workshop these requests are forwarded to the SSS application.
Attestation endpoint: By default, nitriding exposes an /attestation endpoint that accepts a nonce value and returns a signed cryptographic attestation document.
This cryptographic attestation document includes hash measurements, also referred to as platform configuration registers (PCR), such as the hash of the enclave images (PCR0) or details about the parent EC2 instance (PCR4). For details on these measurements, refer to Where to get an enclave’s measurements.
The attestation document supports optional, customizable fields, namely nonce, public-key and user_data, which can be set individually for every attestation doc. For more information on the Nitro Enclaves attestation process and document structure, refer to Nitro Enclaves Attestation Process or check out the workshop sections about Customizing Attestation or document Validation.
Nitriding adds the nonce to the attestation document as a measure of freshness. Furthermore, the fingerprint (hash) of TLS certificate used by the enclave, is being added to the user_data field, as shown in the following sequence diagram.
This binds the certificate to the specific enclave instance.
By comparing the TLS certificate fingerprint presented during the HTTPs connection and the fingerprint in the attestation document, you can prove the following aspects:
The private key for TLS termination resides securely inside the enclave (in a trusted AWS environment).
The enclave is running trusted code, as verified by the attestation’s PCR (Platform Configuration Register) measurements.
The identity of the enclave is validated, whether the code is open source (allowing deterministic measurement through reproducible builds) or closed source (with measurements distributed by the provider). For more information on deterministic and reproducible builds, refer to Establishing verifiable security: Reproducible builds and AWS Nitro Enclaves.
Horizontal scaling
Let’s now have look into the scaling properties of a AWS Nitro Enclave based nitriding application and learn how we can improve the processing capacities of our application by scaling out horizontally.The provided CDK, by default, provisions a single EC2 instance with its associated enclave. As depicted in the preceding sequence diagram, nitriding generates a self-signed certificate at the start and uses it to terminate TLS connections. This approach is limited to a single worker because load balancing requests over several workers would introduce non-identical TLS certificates. Non-identical TLS certificates behind NLB can cause certificate mismatch errors and TLS handshake failures when clients are routed to different backend servers with certificates that don’t match (the expected domain name) or have different validation properties.There are different ways you can address this issue besides implementing your own cryptographic attestation-based method:
Create a symmetric KMS key and associate it with your enclaves using AWS KMS condition keys for AWS Nitro Enclaves. Use AWS Certificate Manager (ACM) to create an exportable TLS certificate. Alternatively, generate a custom TLS certificate in a trusted environment. Encrypt all sensitive key material via AWS KMS and store the ciphertext in a database such as DynamoDB. Provide the encrypted TLS certificate to each enclave that requires access and use cryptographic attestation to decrypt the TLS certificate or key.
Nitriding provides an enclave key synchronization mechanism based on AWS Nitro Enclaves cryptographic attestation. This mechanism supports Let’s Encrypt certificates out of the box so organizations can avoid all the operational and security challenges associated with self-signed certificates, particularly in context of web browsers.
Virtual Networking for Enclaves with Tap Interface
Now let’s deep dive into how nitriding provides tap0based networking (to the enclave) and learn how we can use tap0 networking without nitriding.
As mentioned previously, nitriding uses gvisor-tap-vsock package to provide tap0 based networking to the enclave.
gvisor-tap-vsock delivers a user-mode network stack for virtual machines (VMs) and containers, enabling secure, flexible connectivity between AWS Nitro Enclaves and external networks.
You can use gvisor-tap-vsock independently from nitriding if you only require tap0 networking without TLS termination and http forwarding capabilities. The setup remains the same as in the workshop; however instead of nitriding binary, you need to include the gvforwarder binary in the enclave Dockerfile. The build instructions can be found in Makefile.
After copying the binary into your Docker file, use a similar command in your enclave start.sh file to activate DNS resolution and start gvforwarder:
After you have started your enclave with gvforwarder you can manage port forwarding using the gvproxy process running on EC2 parent instances as done in the workshop.
IMDSv2 access from inside Enclaves
This section explores the requirement of accessing EC2 Instance Metadata Service Version 2 (IMDSv2) from inside an enclave and discusses different ways on how access can be provided.
Applications inside AWS Nitro Enclaves often need access to IMDSv2 to obtain temporary AWS credentials to interact with AWS services such as AWS KMS for decrypt operations. IMDSv2 is only accessible from within the associated EC2 instance and can be accessed at 169.254.169.254.You can enable IMDSv2 access for enclaves using one of the following two approaches:
Dedicated vsock proxy route (as done in the workshop)
Run a vsock proxy on the EC2 parent instance and one inside the enclave to provide access to IMDSv2 from inside the enclave. Apply the following configuration to your enclave to map 169.254.169.254 from inside the enclave to the endpoint on the parent instance:
ip addr add 169.254.169.254/16 dev lo
IN_ADDRS=169.254.169.254:80 OUT_ADDRS=3:8002 ./app/proxy &
This method is suitable if you do not need a tap interface in the enclave and want to tightly control outbound communication.
TAP interface with gvisor-tap-vsock
If your enclave uses a tap interface via gvisor, pass the -ec2-instance-metadata flag in the gvisor start command on the parent EC2 instance. This allows the host process to forward IMDSv2 traffic from the enclave (via tap0) to the metadata service. Ensure you are using gvisor-tap-vsock version v0.8.7 or newer for this feature.
Any of the EC2 parent instance or enclave related changes described in this section can be applied to an existing workshop CDK stack by rerunning the cdk deploy command as described here: Deploy the CDK application.
Encrypting and decrypting secrets inside AWS Nitro Enclaves using Python and Cryptographic Attestation
In this section we will go in depth on how KMS based decryption can be implemented inside enclaves in Python using AWS SDK for Python (Boto3).
Decryption, leverages the enclave’s unique cryptographic attestation feature unavailable directly on standard EC2 instances – ensuring enhanced security by verifying the enclave’s integrity.Encryption inside an enclave using the Boto3 SDK however mirrors the process outside the enclave, so it’s not detailed here.
High-Level Decryption Flow
The process for decrypting content inside a Nitro Enclave follows these streamlined steps:
Ensure that the enclave has outbound networking configured.
Generate an ephemeral RSA key pair.
Request an attestation document that includes the public key.
Create a KMS decrypt request with the ciphertext and attached attestation document.
This flow enables secure decryption in Python, aligning with workshop examples for practical implementation.
Make sure that the tap0 network Interface is up and running and DNS has been configured
The Python code example discussed uses Boto3 SDK. Boto3 requires a fully routed network interface such as tap0 as described previously and access to AWS credentials. The credentials can be managed manually as done in the workshop or managed automatically by the SDK. See the previous section about managing AWS credentials.
Generate an ephemeral RSA key pair inside the enclave
Generate a fresh RSA private/public key pair for each session. This key is just used for the re-encryption schema and does not need persisted.
Request an attestation document included the public key
Use the Nitro Secure Module (NSM) to generate an attestation document that cryptographically proves enclave identity and includes the ephemeral public key.
Create an AWS KMS decrypt request including the ciphertext and attestation document
Send the attestation document as part of the Recipient parameter in the AWS KMS decrypt API call. AWS KMS will verify the attestation and encrypt the response for your enclave’s public key.
Receive and parse the ciphertext_for_recipient CMS document
AWS KMS returns a Cryptographic Message Syntax (CMS) structure containing the encrypted symmetric key and ciphertext. To decrypt, use the following steps:
Load the private key from Step 2
from cryptography.hazmat.primitives import serialization
with open(private_key_file, "rb") as f:
private_key_raw = f.read()
private_key = serialization.load_der_private_key(private_key_raw,
password=None)
Parse the CMS structure
Use a library such as asn1crypto to extract the encrypted key, initialization vector (IV), and encrypted content.
CMS uses private/public key cryptography to encrypt a symmetric key that is used for the payload. Use the enclave’s RSA private key to decrypt the symmetric key with OAEP padding.
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives import hashes
decrypted_sym_key = private_key.decrypt(
encrypted_key,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None,
),
)
Decrypt the content with Advanced Encryption Standard (AES)
Use the decrypted symmetric key and IV to decrypt the content (typically using AES-CBC).
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import padding as sym_padding
cipher = Cipher(
algorithms.AES(decrypted_sym_key), modes.CBC(iv), backend=default_backend()
)
decryptor = cipher.decryptor()
decrypted_padded = decryptor.update(encrypted_content) + decryptor.finalize()
unpadder = sym_padding.PKCS7(128).unpadder()
decrypted_content = unpadder.update(decrypted_padded) + unpadder.finalize()
Encode the content for transport
Encode the decrypted content as base64 for safe transport or further processing.
import base64
result = base64.b64encode(decrypted_content).decode("utf-8")
Cleanup
To avoid incurring future charges, delete the resources following the steps described in the workshop Cleanup section.
Conclusion
In this post, you learned how to use AWS Nitro Enclaves for building secure (public) applications using TLS termination, cryptographic attestation and TAP networking. The implementation includes practical examples using gvisor-tap-vsock tap networking, secure IMDSv2 access patterns and Python based CMS decrypt..
Ready to enhance your application security? Visit our GitHub repository and workshop to start building with AWS Nitro Enclaves today.
Timely and accessible alert notifications are crucial for maintaining operational excellence, but traditional alerting mechanisms often fall short. Email notifications can get buried in crowded inboxes, SMS messages might incur high costs for international teams, and pager systems lack the rich context modern teams need for rapid incident response. WhatsApp, with over 2 billion users worldwide, offers several advantages:
Universal accessibility – Available on virtually every smartphone
Rich media support – Sends formatted messages, images, and links
Global reach – No international SMS fees
High engagement – Messages are typically delivered within seconds
Familiar interface – Many teams already use WhatsApp for daily communication
The solution uses AWS End User Messaging Social to create a seamless bridge between CloudWatch alarms and WhatsApp notifications. This serverless architecture provides real-time infrastructure alerts through WhatsApp messaging platform teams already know and use.
The architecture consists of four main AWS services working together. The data flow begins when CloudWatch alarms detect breaches of predefined thresholds and publish notifications to an Amazon Simple Notification Service (Amazon SNS) topic. The SNS topic triggers an AWS Lambda function that processes the alarm data, formats contextual WhatsApp messages, and uses AWS End User Messaging Social to deliver notifications to specified recipients.
The following diagram illustrates the solution architecture.
Prerequisites
Implementation requires an AWS account with appropriate permissions for AWS CloudFormation, Lambda, Amazon SNS, and CloudWatch. You must also have a WhatsApp Business Account integrated with AWS End User Messaging and the WhatsApp phone number ID from the AWS End User Messaging console. (For instructions to locate this information, see View a phone number’s ID in AWS End User Messaging Social).
Before you deploy this solution, create an approved template in your Meta account named cw_alarm_notification. Alternatively, use your preferred template name and modify the Lambda function code accordingly (as shown in the following screenshot).
Lambda function code
The solution uses a Python-based Lambda function that processes CloudWatch alarm notifications and formats them for WhatsApp delivery. The function receives SNS events containing CloudWatch alarm data, extracts relevant information, formats contextual messages, and delivers notifications through AWS End User Messaging Social.
The following function code shows an example to parse the SNS message content and extract key alarm information, including alarm name, state value, and reason for state change:
The send_whatsapp_message function uses AWS End User Messaging Social to deliver formatted messages through the socialmessaging client:
def send_whatsapp_message(message):
"""Send message via AWS End User Messaging"""
client = boto3.client('socialmessaging')
response = client.send_whats_app_message(
originationPhoneNumberId=os.environ['WHATSAPP_PHONE_NUMBER_ID'],
destinationPhoneNumber=os.environ['ALERT_RECIPIENT'],
messageBody={'text': message}
)
Deploy the solution
The solution uses AWS CloudFormation for infrastructure as code (IaC) deployment. The main template creates an SNS topic for alarm notifications, a Lambda function for message processing, and required AWS Identity and Access Management (IAM) roles with least-privilege permissions.
The CloudFormation template requires a recipient number with an active WhatsApp account to receive alarm notifications as messages. The template also requires the WhatsApp phone number ID retrieved from the AWS End User Messaging Social console, as noted in the prerequisites. The template must be deployed in the same AWS Region as AWS End User Messaging Social. See the following code:
The preceding template deploys an alarm called SampleHighCPUAlarm that triggers an SNS topic. The SNS topic triggers the WhatsApp alarm notifier Lambda function, which processes and sends the message using AWS End User Messaging Social.
Test the solution
You can test the solution using the sample alarm created by the CloudFormation stack. The following screenshot shows an example alarm configuration and its CloudWatch metrics, currently in the OK state.
You can use the following code to trigger the alarm by updating this metric:
As the alarm switches from OK to ALARM state, a WhatsApp Message is delivered.
Conclusion
Integrating CloudWatch with WhatsApp notifications represents a significant step forward in modern infrastructure monitoring. By using AWS End User Messaging, teams can receive critical alerts through their preferred communication channel while maintaining the reliability and scalability of AWS services.
The solution’s modular architecture, simple yet effective security model, and cost-effective design make it suitable for organizations of various sizes.
Amazon SageMaker offers a comprehensive hub that integrates data, analytics, and AI capabilities, providing a unified experience for users to access and work with their data. Through Amazon SageMaker Unified Studio, a single and unified environment, you can use a wide range of tools and features to support your data and AI development needs, including data processing, SQL analytics, model development, training, inference, and generative AI development. This offering is further enhanced by the integration of Amazon Q and Amazon SageMaker Catalog, which provide an embedded generative AI and governance experience, helping users work efficiently and effectively across the entire data and AI lifecycle, from data preparation to model deployment and monitoring.
With the SageMaker Catalog data lineage feature, you can visually track and understand the flow of your data across different systems and teams, gaining a complete picture of your data assets and how they’re connected. As an OpenLineage-compatible feature, it helps you trace data origins, track transformations, and view cross-organizational data consumption, giving you insights into cataloged assets, subscribers, and external activities. By capturing lineage events from OpenLineage-enabled systems or through APIs, you can gain a deeper understanding of your data’s journey, including activities within SageMaker Catalog and beyond, ultimately driving better data governance, quality, and collaboration across your organization.
Additionally, the SageMaker Catalog data lineage feature versions each event, so you can track changes, visualize historical lineage, and compare transformations over time. This provides valuable insights into data evolution, facilitating troubleshooting, auditing, and data integrity by showing exactly how data assets have evolved, and generates trust in data.
In this post, we discuss the visualization of data lineage in SageMaker Catalog and how capture lineage from different AWS analytics services such as AWS Glue, Amazon Redshift, and Amazon EMR Serverless automatically, and visualize it with SageMaker Unified Studio.
Solution overview
The generation of data lineage in SageMaker Catalog operates through an automated system that captures metadata and relationships between different data artifacts for AWS Glue, Amazon EMR, and Amazon Redshift. When data moves through various AWS services, SageMaker automatically tracks these movements, transformations, and dependencies, creating a detailed map of the data’s journey. This tracking includes information about data sources, transformations, processing steps, and final outputs, providing a complete audit trail of data movement and transformation.
The implementation of data lineage in SageMaker Catalog offers several key benefits:
Compliance and audit support – Organizations can demonstrate compliance with regulatory requirements by showing complete data provenance and transformation history
Impact analysis – Teams can assess the potential impact of changes to data sources or transformations by understanding dependencies and relationships in the data pipeline
Troubleshooting and debugging – When issues arise, the lineage system helps identify the root cause by showing the complete path of data transformation and processing
Data quality management – By tracking transformations and dependencies, organizations can better maintain data quality and understand how data quality issues might propagate through their systems
Lineage capture is automated using several tools in SageMaker Unified Studio. To learn more, refer to Data lineage support matrix.
In the following sections, we show you how to configure your resources and implement the solution. For this post, we create the solution resources in the us-west-2 AWS Region using an AWS CloudFormation template.
Prerequisites
Before getting started, make sure you have the following:
An active AWS account with billing enabled.
An AWS Identity and Access Management (IAM) user with administrator access (AdministratorAccess policy) or specific permissions to create and manage resources such as a virtual private cloud (VPC), subnet, security group, IAM roles, NAT gateway, internet gateway, SageMaker Unified Studio, and Amazon Simple Storage Service (Amazon S3) buckets.
An S3 bucket (for this post, datazone-{account_id}).
Launch the stack vpc-analytics-lineage-sus using the CloudFormation template:
Provide the parameter values as listed in the following table.
Parameters
Sample value
DatazoneS3Bucket
s3://datazone-{account_id}/
DomainName
dz-studio
EnvironmentName
sm-unifiedstudio
PrivateSubnet1CIDR
10.192.20.0/24
PrivateSubnet2CIDR
10.192.21.0/24
PrivateSubnet3CIDR
10.192.22.0/24
ProjectName
sidproject
PublicSubnet1CIDR
10.192.10.0/24
PublicSubnet2CIDR
10.192.11.0/24
PublicSubnet3CIDR
10.192.12.0/24
UsersList
analyst
VpcCIDR
10.192.0.0/16
The stack creation process can take approximately 20 minutes to complete. You can check the Outputs tab for the stack after the stack is created.
Next, we prepare source data, setup the AWS Glue ETL Job, Amazon EMR Serverless Spark Job and Amazon Redshift Job to generate the lineage and capture lineage from Amazon SageMaker Unified Studio
EmployeeID,Name,Department,Role,HireDate,Salary,PerformanceRating,Shift,Location
E1000,Employee_0,Quality Control,Operator,2021-08-08,33002.0,1,Night,Plant C
E1001,Employee_1,Maintenance,Supervisor,2015-12-31,69813.76,5,Evening,Plant B
E1002,Employee_2,Production,Technician,2015-06-18,46753.32,1,Evening,Plant A
E1003,Employee_3,Admin,Supervisor,2020-10-13,52853.4,5,Night,Plant A
E1004,Employee_4,Quality Control,Manager,2023-09-21,55645.27,5,Evening,Plant A
Upload the sample data from attendance.csv and employees.csv to the S3 bucket specified in the previous CloudFormation stack (s3://datazone-{account_id}/csv/).
Ingest employee data in Amazon Relational Database Dervice (Amazon RDS) for MySQL table
On the CloudFormation console, open the stack vpc-analytics-lineage-sus and collect the Amazon RDS for MySQL database endpoint to use in the following commands to create a default employeedb database.
Capture lineage from AWS Glue ETL job and notebook
To demonstrate the lineage, we set up an AWS Glue extract, transform, and load (ETL) job to read the employee data from an Amazon RDS for MySQL table and the employee attendance data from Amazon S3, and join both datasets. Finally, we write the data to Amazon S3 and create the attendance_with_emp1 table in the AWS Glue Data Catalog.
Create and configure AWS Glue job for lineage generation
Complete the following steps to create your AWS Glue ETL job:
On the AWS Glue console, create a new ETL job with AWS Glue version 5.0.
Enable Generate lineage events and provide the domain ID (retrieve from the CloudFormation template output for DataZoneDomainid; it will have the format dzd_xxxxxxxx)
Use the following code snippet in the AWS Glue ETL job script. Provide the S3 bucket (bucketname-{account_id}) used in the preceding CloudFormation stack.
from pyspark.sql import SparkSession
from pyspark.sql import SparkSession, DataFrame
from pyspark.sql.functions import *
from pyspark.sql.types import *
from pyspark import SparkContext
from pyspark.sql import SparkSession
import sys
import logging
spark = SparkSession.builder.appName("lineageglue").enableHiveSupport().getOrCreate()
connection_details = glueContext.extract_jdbc_conf(connection_name="connectionname")
employee_df = spark.read.format("jdbc").option("url", "jdbc:MySQL://dbhost:3306/database_name").option("dbtable", "employee").option("user", connection_details['user']).option("password", connection_details['password']).load()
s3_paths = {
'absent_data': 's3://bucketname-{account_id}/csv/attendance.csv'
}
absent_df = spark.read.csv(s3_paths['absent_data'], header=True, inferSchema=True)
joined_df = employee_df.join(absent_df, on="EmployeeID", how="inner")
joined_df.write.mode("overwrite").format("parquet").option("path", "s3://datazone-{account_id}/attendanceparquet/").saveAsTable("gluedbname.tablename")
Choose Run to start the job.
On the Runs tab, confirm the job ran without failure.
After the job has executed successfully, navigate to the SageMaker Unified Studio domain.
Choose Project and under Overview, choose Data Sources.
Select the Data Catalog source (accountid-AwsDataCatalog-glue_db_suffix-default-datasource).
On the Actions dropdown menu, choose Edit.
Under Connection, enable Import data lineage.
In the Data Selectionsection, under Table Selection Criteria, provide a table name or use * to generate lineage.
Update the data source and choose Run to create an asset called attendance_with_emp1 in SageMaker Catalog.
Navigate to Assets, choose the attendance_with_emp1 asset, and navigate to the LINEAGE section.
The following lineage diagram shows an AWS Glue job that integrates data from two sources: employee information stored in Amazon RDS for MySQL and employee absence records stored in Amazon S3. The AWS Glue job combines these datasets through a join operation, then creates a table in the Data Catalog and registers it as an asset in SageMaker Catalog, making the unified data available for further analysis or machine learning purposes.
Create and configure AWS Glue notebook for lineage generation
Complete the following steps to create the AWS Glue notebook:
On the AWS Glue console, choose Author using an interactive code notebook.
Under Options, choose Start fresh and choose Create notebook.
In the notebook, use the following code to generate lineage.
In the following code, we add the required Spark configuration to generate lineage and then read CSV data from Amazon S3 and write in Parquet format to the Data Catalog table. The Spark configuration includes the following parameters:
spark.extraListeners=io.openlineage.spark.agent.OpenLineageSparkListener – Registers the OpenLineage listener to capture Spark job execution events and metadata for lineage tracking
spark.openlineage.transport.type=amazon_datazone_api – Specifies Amazon DataZone as the destination service where the lineage data will be sent and stored
spark.openlineage.transport.domainId=dzd_xxxxxxx – Defines the unique identifier of your Amazon DataZone domain where the lineage data will be associated
spark.glue.accountId={account_id} – Specifies the AWS account ID where the AWS Glue job is running for proper resource identification and access
spark.openlineage.facets.custom_environment_variables – Lists the specific environment variables to capture in the lineage data for context about the AWS and AWS Glue environment
spark.glue.JOB_NAME=lineagenotebook – Sets a unique identifier name for the AWS Glue job that will appear in lineage tracking and logs
After the notebook has executed successfully, navigate to the SageMaker Unified Studio domain.
Choose Project and under Overview, choose Data Sources.
Choose the Data Catalog source ({account_id}-AwsDataCatalog-glue_db_suffix-default-datasource).
Choose Run to create the asset attendance_with_empnote in SageMaker Catalog.
Navigate to Assets, choose the attendance_with_empnote asset, and navigate to the LINEAGE section.
The following lineage diagram shows an AWS Glue job that reads data from the employee absence records stored in Amazon S3. The AWS Glue job transform CSV data into Parquet format, then creates a table in the Data Catalog and registers it as an asset in SageMaker Catalog.
Capture lineage from Amazon Redshift
To demonstrate the lineage, we are creating an employee table and an attendance table and join both datasets. Finally, we create a new table called employeewithabsent in Amazon Redshift. Complete the following steps to create and configure lineage for Amazon Redshift tables:
In SageMaker Unified Studio, open your domain.
Under Compute, choose Data warehouse.
Open project.redshift and copy the endpoint name (redshift-serverless-workgroup-xxxxxxx).
On the Amazon Redshift console, open the Query Editor v2, and connect to the Redshift Serverless workgroup with a secret. Use the AWS Secrets Manager option and choose the secret redshift-serverless-namespace-xxxxxxxx.
Use the following code to create tables in Amazon Redshift and load data from Amazon S3 using the COPY command. Make sure the IAM role has GetObject permission on the S3 files attendance.csv and employees.csv.
Create Redshift table absent
CREATE TABLE public.absent (
employeeid character varying(65535),
date date,
shiftstart timestamp without time zone ,
shiftend timestamp without time zone,
absent boolean,
overtimehours integer
);
Load data into absent table.
COPY absent
FROM 's3://datazone-{account_id}/csv/attendance.csv'
IAM_ROLE 'arn:aws:iam::accountid:role/RedshiftAdmin'
csv
IGNOREHEADER 1;
Create Redshift table employee
CREATE TABLE public.employee (
employeeid character varying(65535),
name character varying(65535),
department character varying(65535),
role character varying(65535),
hiredate date,
salary double precision,
performancerating integer,
shift character varying(65535),
location character varying(65535)
);
Load data into employee table.
COPY employee
FROM 's3://datazone-{account_id}/csv/employees.csv'
IAM_ROLE 'arn:aws:iam::account-id:role/RedshiftAdmin'
csv
IGNOREHEADER 1;
After the tables are created and the data is loaded, perform the join between the tables and create a new table with a CTAS query:
CREATE TABLE public.employeewithabsent AS
SELECT
e.*,
a.absent,
a.overtimehours
FROM public.employee e
INNER JOIN public.absent a
ON e.EmployeeID = a.EmployeeID;
Navigate to the SageMaker Unified Studio domain.
Choose Project and under Overview, choose Data Sources.
Select the Amazon Redshift source (RedshiftServerless-default-redshift-datasource).
On the Actions dropdown menu, choose Edit.
Under Connection, Enable Import data lineage.
In the Data Selection section, under Table Selection Criteria, provide a table name or use * to generate lineage.
Update the data source and choose Run to create an asset called employeewithabsent in SageMaker Catalog.
Navigate to Assets, choose the employeewithabsent asset, and navigate to the LINEAGE section.
The following lineage diagram shows joining two redshift tables and creating a new redshift table and registers it as an asset in SageMaker Catalog.
Capture lineage from EMR Serverless job
To demonstrate the lineage, we read employee data from an RDS for MySQL table and an attendance dataset from Amazon Redshift, and join both datasets. Finally, we write the data to Amazon S3 and create the attendance_with_employee table in the Data Catalog. Complete the following steps:
On the Amazon EMR console, choose EMR Serverless in the navigation pane.
To create or manage EMR Serverless applications, you need the EMR Studio UI.
If you already have an EMR Studio in the Region where you want to create an application, choose Manage applications to navigate to your EMR Studio, or select the EMR Studio that you want to use.
If you don’t have an EMR Studio in the Region where you want to create an application, choose Get started and then choose Create and launch Studio. EMR Serverless creates an EMR Studio for you so you can create and manage applications.
In the Create studio UI that opens in a new tab, enter the name, type, and release version for your application.
Choose Create application.
Create an EMR Spark serverless application with the following configuration:
For Type, choose Spark.
For Release version, choose emr-7.8.0.
For Architecture, choose x86_64.
For Application setup options, select Use custom settings.
For Interactive endpoint, enable the endpoint for EMR Studio.
For Application configuration, use the following configuration:
After application has started, submit the Spark application to generate lineage events. Copy the following script and upload it to the S3 bucket (s3://datazone-{account_id}/script/). Upload the MySQL-connector-java JAR file to the S3 bucket (s3://datazone-{account_id}/jars/) to read the data from MySQL.
from pyspark.sql import SparkSession
from pyspark.sql import SparkSession, DataFrame
from pyspark.sql.functions import *
from pyspark.sql.types import *
from pyspark import SparkContext
from pyspark.sql import SparkSession
import sys
import logging
spark = SparkSession.builder.appName("lineageglue").enableHiveSupport().getOrCreate()
employee_df = spark.read.format("jdbc").option("driver","com.MySQL.cj.jdbc.Driver").option("url", "jdbc:MySQL://dbhostname:3306/databasename").option("dbtable", "employee").option("user", "admin").option("password", "xxxxxxx").load()
absent_df = spark.read.format("jdbc").option("url", "jdbc:redshift://redshiftserverlessendpoint:5439/dev").option("dbtable", "public.absent").option("user", "admin").option("password", "xxxxxxxxxx").load()
joined_df = employee_df.join(absent_df, on="EmployeeID", how="inner")
joined_df.write.mode("overwrite").format("parquet").option("path", "s3://datazone-{account_id}/emrparquetnew/").saveAsTable("gluedname.tablename")
After you upload the script, use the following command to submit the Spark application. Change the following parameters according to your environment details:
application-id: Provide the Spark application ID you generated.
execution-role-arn: Provide the EMR execution role.
entryPoint: Provide the Spark script S3 path.
domainID: Provide the domain ID (from the CloudFormation template output for DataZoneDomainid: dzd_xxxxxxxx).
After the job has executed successfully, navigate to the SageMaker Unified Studio domain.
Choose Project and under Overview, choose Data Sources.
Select the Data Catalog source ({account_id}-AwsDataCatalog-glue_db_xxxxxxxxxx-default-datasource).
On the Actions dropdown menu, choose Edit.
Under Connection, enable Import data lineage.
In the Data Selection section, under Table Selection Criteria, provide a table name or use * to generate lineage.
Update the data source and choose Run to create an asset called attendancewithempnew in SageMaker Catalog.
Navigate to Assets, choose the attendancewithempnew asset, and navigate to the LINEAGE section.
The following lineage diagram shows an AWS Glue job that integrates employee information stored in Amazon RDS for MySQL and employee absence records stored in Amazon Redshift. The AWS Glue job combines these datasets through a join operation, then creates a table in the Data Catalog and registers it as an asset in SageMaker Catalog.
Clean up
To clean up your resources, complete the following steps:
On the AWS CloudFormation console, delete the CloudFormation stack vpc-analytics-lineage-sus.
Conclusion
In this post, we showed how data lineage in SageMaker Catalog helps you track and understand the complete lifecycle of your data across various AWS analytics services. This comprehensive tracking system provides visibility into how data flows through different processing stages, transformations, and analytical workflows, making it an essential tool for data governance, compliance, and operational efficiency.
Try out these lineage visualization methods for your own use cases, and share your questions and feedback in the comments section.
In hospital intensive care units (ICUs), continuous patient monitoring is critical. Medical devices generate vast amounts of real-time data on vital signs such as heart rate, blood pressure, and oxygen saturation. The key challenge lies in early detection of patient deterioration through vital sign trending. Healthcare teams must process thousands of data points daily per patient to identify concerning patterns, a task crucial for timely intervention and potentially life-saving care.
AWS Lambda event source mapping can help in this scenario by automatically polling data streams and triggering functions in real-time without additional infrastructure management. By using AWS Lambda for real-time processing of sensor data and storing aggregated results in secure data structures designed for large analytic datasets called Iceberg tables in Amazon Simple Storage Service (Amazon S3) buckets, medical teams can achieve both immediate alerting capabilities and gain long-term analytical insights, enhancing their ability to provide timely and effective care.
In this post, we demonstrate how to build a serverless architecture that processes real-time ICU patient monitoring data using Lambda event source mapping for immediate alert generation and data aggregation, followed by persistent storage in Amazon S3 with an Iceberg catalog for comprehensive healthcare analytics. The solution demonstrates how to handle high-frequency vital sign data, implement critical threshold monitoring, and create a scalable analytics platform that can grow with your healthcare organization’s needs and help monitor sensor alert fatigue in the ICU.
Architecture
The following architecture diagram illustrates a real-time ICU patient analytics system.
In this architecture, real-time patient monitoring data from hospital ICU sensors is ingested into AWS IoT Core, which then streams the data into Amazon Kinesis Data Streams. Two Lambda functions consume this streaming data concurrently for different purposes, both using Lambda event source mapping integration with Kinesis Data Streams. The first Lambda function uses the filtering feature of event source mapping to detect critical health events where SpO2(blood oxygen saturation) levels fall below 90%, immediately triggering notifications to caregivers through Amazon Simple Notification Service (Amazon SNS) for rapid response. The second Lambda function employs the tumbling window feature of event source mapping to aggregate sensor data over 10-minute time intervals. This aggregated data is then systematically stored in S3 buckets in Apache Iceberg format for historical analysis and reporting. The entire pipeline operates in a serverless manner, providing scalable, real-time processing of critical healthcare data while maintaining both immediate alerting capabilities and long-term data storage for analytics.
Amazon S3 data, with its support for Apache Iceberg table format, enables healthcare organizations to efficiently store and query large volumes of time-series patient data. This solution allows for complex analytical queries across historical patient data while maintaining high performance and cost efficiency.
Prerequisites
To implement the solution provided in this post, you should have the following:
An active AWS account
IAM permissions to deploy CloudFormation templates and provision AWS resources
Python installed on your machine to run the ICU patient sensor data simulator code
Deploy a real-time ICU patient analytics pipeline using CloudFormation
You use AWS CloudFormation templates to create the resources for a real-time data analytics pipeline.
To get started, Sign in to the console as Account user and select the appropriate Region.
Amazon CloudWatch log groups to record for Kinesis Firehose activity and Lambda functions.
Solution walkthrough
Now that you’ve deployed the solution, let’s review a functional walkthrough. First, simulate patient vital signs data and send it to AWS IoT Core using the following Python code on your local machine. To run this code successfully, ensure you have the necessary IAM permissions to publish messages to the IoT topic in the AWS account where the solution is deployed.
import boto3
import json
import random
import time
# AWS IoT Data client
iot_data_client = boto3.client(
'iot-data',
region_name='us-west-2'
)
# IOT Topic to publish
topic = 'icu/sensors'
# Fixed set of patient IDs
patient_ids = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print("Infinite sensor data simulation...")
try:
while True:
for patient_id in patient_ids:
# Generate sensor data
message = {
"patient_id": patient_id,
"timestamp": int(time.time()),
"spo2": random.randint(91, 99),
"heart_rate": random.randint(60, 100),
"temperature_f": round(random.uniform(97.0, 100.0), 1)
}
# Publish to topic
response = iot_data_client.publish(
topic=topic,
qos=1,
payload=json.dumps(message)
)
print(f"Published: {message}")
# Wait 30 seconds before next round
print("Sleeping for 30 seconds...\n")
time.sleep(30)
except KeyboardInterrupt:
print("\nSimulation stopped by user.")
The following is the format of a sample ICU sensor message produced by the simulator.
Data is published to the icu/sensors IoT topic every 30 seconds for 10 different patients, creating a continuous stream of ICU patient monitoring data. Messages published to AWS IoT Core are passed to Kinesis Data Streams using the following message routing rule deployed by our solution.
Two Lambda functions consume data from Data Streams concurrently, both using the Lambda event source mapping integration with Kinesis Data Streams.
Event source mapping
Lambda event source mapping automatically triggers Lambda functions in response to data changes from supported event sources like Amazon DynamoDB Streams, Amazon Kinesis Data Streams, Amazon Simple Queue Service (Amazon SQS), Amazon MQ, and Amazon Managed Streaming for Apache Kafka. This serverless integration works by having Lambda poll these sources for new records, which are then processed in configurable batch sizes ranging from 1 to 10,000 records. When new data is detected, Lambda automatically invokes the function synchronously, handling the scaling automatically based on the workload. The service supports at-least-once delivery and provides robust error handling through retry policies and dead-letter queues for failed events. Event source mappings can be fine-tuned through various parameters such as batch windows, maximum record age, and retry attempts, making them highly adaptable to different use cases. This feature is particularly valuable in event-driven architectures, so that customers can focus on business logic while AWS manages the complexities of event processing, scaling, and reliability.
Event source mapping uses tumbling windows and filtering to process and analyze data.
Tumbling windows
Tumbling windows in Lambda event processing enable data aggregation in fixed, non-overlapping time intervals, where each event belongs to exactly one window. This is ideal for time-based analytics and periodic reporting. When combined with event source mapping, this approach allows efficient batch processing of events within defined time periods (for example, 10-minute windows), enabling calculations such as average vital signs or cumulative fluid intake and output while optimizing function invocations and resource usage.
When you configure an event source mapping between Kinesis Data Streams and a Lambda function, use the Tumbling Window Duration setting, which appears in the trigger configuration in the Lambda console. The solution you deployed using the CloudFormation template includes the AggregateSensorData Lambda function, which uses a 10-minute tumbling window configuration. Depending on the volume of messages flowing through the Amazon Kinesis stream, the AggregateSensorData function can be invoked multiple times for each 10-minute window, sequentially, with the following attributes in the event supplied to the function.
Window start and end: The beginning and ending timestamps for the current tumbling window.
State: An object containing the state returned from the previous window, which is initially empty. The state object can contain up to 1 MB of data.
isFinalInvokeForWindow: Indicates if this is the last invocation for the tumbling window. This only occurs once per window period.
isWindowTerminatedEarly: A window ends early only if the state exceeds the maximum allowed size of 1 MB.
In a tumbling window, there is a series of Lambda invocations in the following pattern:
AggregateSensorData Lambda code snippet:
def handler(event, context):
state_across_window = event['state']
# Iterate through each record and decode the base64 data
for record in event['Records']:
encoded_data = record['kinesis']['data']
partition_key = record['kinesis']['partitionKey']
decoded_bytes = base64.b64decode(encoded_data)
decoded_str = decoded_bytes.decode('utf-8')
decoded_json = json.loads(decoded_str)
# create partition_key attribute if it do not exists in state
if partition_key not in state_across_window:
state_across_window[partition_key] = {"min_spo2": decoded_json['spo2'], "max_spo2": decoded_json['spo2'], "avg_spo2": decoded_json['spo2'], "sum_spo2": decoded_json['spo2'], "min_heart_rate": decoded_json['heart_rate'], "max_heart_rate": decoded_json['heart_rate'], "avg_heart_rate": decoded_json['heart_rate'], "sum_heart_rate": decoded_json['heart_rate'], "min_temperature_f": decoded_json['temperature_f'], "max_temperature_f": decoded_json['temperature_f'], "avg_temperature_f": decoded_json['temperature_f'], "sum_temperature_f": decoded_json['temperature_f'], "record_count": 1}
else:
min_spo2 = state_across_window[partition_key]['min_spo2'] if state_across_window[partition_key]['min_spo2'] < decoded_json['spo2'] else decoded_json['spo2']
max_spo2 = state_across_window[partition_key]['max_spo2'] if state_across_window[partition_key]['max_spo2'] > decoded_json['spo2'] else decoded_json['spo2']
sum_spo2 = state_across_window[partition_key]['sum_spo2'] + decoded_json['spo2']
min_heart_rate = state_across_window[partition_key]['min_heart_rate'] if state_across_window[partition_key]['min_heart_rate'] < decoded_json['heart_rate'] else decoded_json['heart_rate']
max_heart_rate = state_across_window[partition_key]['max_heart_rate'] if state_across_window[partition_key]['max_heart_rate'] > decoded_json['heart_rate'] else decoded_json['heart_rate']
sum_heart_rate = state_across_window[partition_key]['sum_heart_rate'] + decoded_json['heart_rate']
min_temperature_f = state_across_window[partition_key]['min_temperature_f'] if state_across_window[partition_key]['min_temperature_f'] < decoded_json['temperature_f'] else decoded_json['temperature_f']
max_temperature_f = state_across_window[partition_key]['max_temperature_f'] if state_across_window[partition_key]['max_temperature_f'] > decoded_json['temperature_f'] else decoded_json['temperature_f']
sum_temperature_f = state_across_window[partition_key]['sum_temperature_f'] + decoded_json['temperature_f']
record_count = state_across_window[partition_key]['record_count'] + 1
avg_spo2 = sum_spo2/record_count
avg_heart_rate = sum_heart_rate/record_count
avg_temperature_f = sum_temperature_f/record_count
state_across_window[partition_key] = {"min_spo2": min_spo2, "max_spo2": max_spo2, "avg_spo2": avg_spo2, "sum_spo2": sum_spo2, "min_heart_rate": min_heart_rate, "max_heart_rate": max_heart_rate, "avg_heart_rate": avg_heart_rate, "sum_heart_rate": sum_heart_rate, "min_temperature_f": min_temperature_f, "max_temperature_f": max_temperature_f, "avg_temperature_f": avg_temperature_f, "sum_temperature_f": sum_temperature_f, "record_count": record_count}
# Determine if the window is final (window end)
is_final_window = event.get('isFinalInvokeForWindow', False)
# Determine if the window is terminated (window ended early)
is_terminated_window = event.get('isWindowTerminatedEarly', False)
window_start = event['window']['start']
window_end = event['window']['end']
if is_final_window or is_terminated_window:
firehose_client = boto3.client('firehose')
firehose_stream = os.environ['FIREHOSE_STREAM_NAME']
for key, value in state_across_window.items():
value['patient_id'] = key
value['window_start'] = window_start
value['window_end'] = window_end
firehose_client.put_record(
DeliveryStreamName= firehose_stream,
Record={'Data': json.dumps(value) }
)
return {
"state": {},
"batchItemFailures": []
}
else:
print(f"interim call for window: ws: {window_start} we: {window_end}")
return {
"state": state_across_window,
"batchItemFailures": []
}
The first invocation contains an empty state object in the event. The function returns a state object containing custom attributes that are specific to the custom logic in the aggregation.
The second invocation contains the state object provided by the first Lambda invocation. This function returns an updated state object with new aggregated values. Subsequent invocations follow this same sequence. Following is a sample of the aggregated state, which can be supplied to subsequent Lambda invocations within the same 10-minute tumbling window.
The final invocation in the tumbling window has the isFinalInvokeForWindow flag set to the true. This contains the state returned by the most recent Lambda invocation. This invocation is responsible for passing aggregated state messages to the Data Firehose stream, which delivers data to the Amazon S3 bucket using Iceberg data format.
After the aggregated data is sent to Amazon S3, you can query the data using Athena.
Query: SELECT * FROM "cfdb_<<Database>>"."table_<<Table>>"
Sample result of the preceding Athena query:
Event source mapping with filtering
Lambda event source mapping with filtering optimizes data processing from sources like Amazon Kinesis by applying JSON pattern filtering before function invocation. This is demonstrated in the ICU patient monitoring solution, where the system filters for SpO2 readings from Kinesis Data Streams that are below 90%. Instead of processing all incoming data, the filtering capability is used to selectively processes only critical readings, significantly reducing costs and processing overhead. The solution uses DynamoDB for sophisticated state management, tracking low SpO2 events through a schema combining PatientID and timestamp-based keys within defined monitoring windows.
This state-aware implementation balances clinical urgency with operational efficiency by sending immediate Amazon SNS notifications when critical conditions are first detected while implementing a 15-minute alert suppression window to prevent alert fatigue among healthcare providers. By maintaining state across multiple Lambda invocations, the system helps ensure rapid response to potentially life-threatening situations while minimizing unnecessary notifications for the same patient condition. The integration of Lambda’event filtering, DynamoDB state management, and reliable alert delivery provided by Amazon SNS creates a robust, scalable healthcare monitoring solution that exemplifies how AWS services can be strategically combined to address complex requirements while balancing technical efficiency with clinical effectiveness.
Filter sensor data Lambda code snippet:
sns_client = boto3.client('sns')
dynamodb = boto3.resource('dynamodb')
table_name = os.environ['DYNAMODB_TABLE']
sns_topic_arn = os.environ['SNS_TOPIC_ARN']
table = dynamodb.Table(table_name)
FIFTEEN_MINUTES = 15 * 60 # 15 minutes in seconds
def handler(event, context):
for record in event['Records']:
print(f"Aggregated event: {record}")
encoded_data = record['kinesis']['data']
partition_key = record['kinesis']['partitionKey']
decoded_bytes = base64.b64decode(encoded_data)
decoded_str = decoded_bytes.decode('utf-8')
# Check last notification timestamp from DynamoDB
try:
response = table.get_item(Key={'partition_key': partition_key})
item = response.get('Item')
now = int(time.time())
if item:
last_sent = item.get('timestamp', 0)
if now - last_sent < FIFTEEN_MINUTES:
print(f"Notification for {partition_key} skipped (sent recently)")
continue
# Send SNS Notification
sns_response = sns_client.publish(
TopicArn=sns_topic_arn,
Message=f"Patient SpO2 below 90 percentage event information: {decoded_str}",
Subject=f"Low SpO2 detected for patient ID {partition_key}"
)
print("Message sent to SNS! MessageId:", sns_response['MessageId'])
# Update DynamoDB with current timestamp and TTL
table.put_item(Item={
'partition_key': partition_key,
'timestamp': now,
'ttl': now + FIFTEEN_MINUTES + 60 # Add extra buffer to TTL
})
except Exception as e:
print("Error processing event:", e)
return {
'statusCode': 500,
'body': json.dumps('Error processing event')
}
return {
'statusCode': 200,
'body': {}
}
To generate an alert notification through the deployed solution, update the preceding simulator code by setting the SpO2 value to less than 90 and run it again. Within 1 minute, you should receive an alert notification at the email address you provided during stack creation. The following image is an example of an alert notification generated by the deployed solution.
Clean up
To avoid ongoing costs after completing this tutorial, delete the CloudFormation stack that you deployed earlier in this post. This will remove most of the AWS resources created for this solution. You might need to manually delete objects created in Amazon S3, because CloudFormation won’t remove non-empty buckets during stack deletion.
Conclusion
As demonstrated in this post, you can build a serverless real-time analytics pipeline for healthcare monitoring by using AWS IoT Core, Amazon S3 buckets with iceberg format, and Amazon Kinesis Data Streams integration with AWS Lambda event source mapping. This architectural approach eliminates the need for complex code while enabling rapid critical patient care alerts and data aggregation for analysis using Lambda. The solution is particularly valuable for healthcare organizations looking to modernize their patient monitoring systems with real-time capabilities. The architecture can be extended to handle various medical devices and sensor data streams, making it adaptable for different healthcare monitoring scenarios. This post presents one implementation approach, and organizations adopting this solution should ensure the architecture and code meets their specific application performance, security, privacy, and regulatory compliance needs.
If this post helps you or inspires you to solve a problem, we would love to hear about it!
Amazon Connect Email provides built-in capabilities that make it straightforward to prioritize, assign, and automate the resolution of customer service emails, improving customer satisfaction and agent productivity. With Amazon Connect Email, you can receive and respond to emails sent by customers to business addresses or submitted through web forms on your website or mobile app. You can configure auto-responses, prioritize emails, create or update cases, and route emails to the best available agent when agent assistance is required. Additionally, these capabilities work seamlessly with Amazon Connect outbound campaigns, helping you deliver proactive and personalized email communications.
This post guides you through setting up email in Amazon Connect by routing emails from your email server (Microsoft 365 or Google Workspace) to Amazon Simple Email Service (Amazon SES) SMTP endpoints using a custom email domain onboarded to Amazon SES. By configuring Amazon Connect with your custom email domain in Amazon SES, you can create a unified communication hub that enhances customer experience while simplifying agent workflows. The result is a more responsive, efficient contact center that meets customers where they are, whether they prefer speaking, chatting, or sending emails.
Use case overview
AnyCompany has invested heavily in its email infrastructure over the years, developing a robust and centralized email server that manages both internal and external email traffic. This unified system has become an integral part of their operations, streamlining communication across departments and with customers. AnyCompany has also established a public support email address that has gained significant recognition and trust among their customer base. This email address, featured prominently in all their product documentation, marketing materials, and customer communications, has become a cornerstone of their brand identity in customer support.
Now, AnyCompany faces the challenge of enhancing their customer support process by implementing an automated acknowledgment system for incoming support emails. However, they want to maintain their existing email setup due to its deep integration with internal workflows and the substantial investment it represents. Additionally, preserving their well-known support email address is crucial to protect the brand equity they’ve built over years of customer interactions.
By integrating Amazon Connect with their current email server, AnyCompany can create a seamless solution that addresses these complex requirements. With this integration, customers can continue sending emails to the familiar public support address (for example, [email protected]), maintaining consistency in their customer experience. When new emails are received, Amazon Connect can trigger automated acknowledgment messages, providing immediate assurance to customers that their inquiries have been received and are being processed.
This approach offers multiple benefits. It improves customer satisfaction by providing prompt responses and reduces the volume of follow-up emails. It also preserves AnyCompany’s significant investment in their existing email infrastructure, so they can continue using the centralized system for both internal and external communications. Perhaps most importantly, it maintains the brand recognition associated with their long-standing support email address, so customers can continue to use the contact point they’ve grown to trust over the years.
Solution overview
This post provides a contact center email solution with the following benefits:
Customers continue to send emails to your custom domain
Emails are routed through your primary email server to Amazon Connect (via Amazon SES)
Agents receive and respond to emails within the Amazon Connect agent workspace
Customers receive agent responses from your custom domain (via Amazon SES)
This solution involves three main steps:
Configure Microsoft 365 or Google Workspace to route emails to Amazon Connect
Verify your custom domain in Amazon SES to enable sending emails
Onboard your email address in Amazon Connect to handle customer communications
Prerequisites
Before you begin, make sure you have the following prerequisites:
Administrative access to modify your custom email domain’s DNS settings.
Note – modifying MX records can impact email receiving for your primary domain (example.com). It is highly recommended to create a subdomain (for example, testing.example.com) for testing to avoid impacting any email receiving on your primary domain or use the provided email domain that comes with the Amazon Connect instance (for example, @<instance-alias>.email.connect.aws).
Administrative access to modify your Microsoft 365 Exchange Online or Google Workspace Gmail configuration.
An existing user in Amazon Connect with access to managing email flows, channels, and routing. For example, CallCenterManager can be used to perform actions related to user management, metrics, and routing. Or you can create a user with a custom scoped-down security profile.
When setting up Amazon Simple Email Service for use with Amazon Connect your SES account will be in the sandbox mode, which works well for testing. You will need to request Amazon SES production access before you can fully utilize Amazon SES with Amazon Connect.
Configure Amazon SES
Part of creating a domain identity is configuring its DKIM-based verification. DomainKeys Identified Mail (DKIM) is an email authentication method that Amazon SES uses to verify domain ownership, and receiving mail servers use to validate email authenticity. To learn more, refer to Creating a domain identity.
Complete the following steps to configure your domain identity in Amazon SES:
Open your AWS console and choose the AWS Region where your Amazon Connect instance is deployed.
On the Amazon SES console, choose Identities under Configuration in the navigation pane.
Choose Create identity and provide the following information:
Choose Domain as the identity type.
Enter your custom email domain name.
Enable Use a custom MAIL FROM domain.
Set MAIL FROM domain to feedback.
Set Behavior on MX failure to Use default MAIL FROM domain.
For DKIM verification, provide the following information (unless instructed otherwise):
Choose Easy DKIM under Advanced DKIM settings.
Choose RSA_2048_BIT for DKIM signing key length.
Enable Publish DNS records to Route53 if applicable.
Enable DKIM signatures.
Choose Create identity.
Amazon SES will generate DNS records needed to verify the domain, including:
DKIM CNAME records
Custom MAIL FROM domain MX and TXT records
DMARC TXT records
If the domain is hosted in Route 53, Amazon SES provides an option to automatically Publish DNS records to Route53. When your domain is hosted with Route 53, SES domain verification typically completes within a few minutes. You will see the status Verification pending, followed by Verified.
If the domain is not hosted in Route53, Amazon SES will present individual copy buttons per record as well as a CSV file download option. These records must be added to your DNS so Amazon SES can verify the domain.
After your externally managed DNS has been updated, return to the Amazon SES console and confirm that the identity status has changed to Verified. The time to complete this step is highly variable. You can choose to configure DKIM by using either Easy DKIM or Bring Your Own DKIM (BYODKIM), and depending on your choice, you will have to configure the signing key length of the private key. For detailed steps, refer to Creating a domain identity.
When you first setup Amazon SES, your account is placed in the SES sandbox which we use to prevent unauthorized or unintended sending. While in sandbox mode, you can only send mail to email addresses and domains you verify. After you receive Amazon SES production access for your custom domain, you can send and receive email to and from a valid email address without verification. For more information about the Amazon SES sandbox, refer to Request production access (Moving out of the Amazon SES sandbox).
For setup and testing purposes, complete the following steps to configure an email identity in Amazon SES:
On the Amazon SES console, choose Identities under Configuration in the navigation pane.
Choose Create identity and choose Email Address.
Enter your work email address (you will need access to the inbox to verify ownership). This is the email address that Amazon Connect and Amazon SES will use to send and receive email while your SES account is in the sandbox.
Click Create identity.
Check your email inbox and click the link to verify this is an email address you control.
Configure Amazon Connect
Complete the following steps to configure Amazon Connect:
On the Amazon Connect console, open your instance by clicking on Instance alias.
Under Channels and communications, choose Email.
Choose Add domain.
Choose the domain you verified in Amazon SES.
In your instance, choose Email addresses under Channels.
Choose Create email address and provide the following information:
Create an email address with the same name and domain as the inbound address your customers will use ([email protected]).
Provide a friendly sender name that will appear in customer inboxes.
Create a new flow or attach an existing flow to the custom domain email address (this flow will route inbound emails).
Choose Save.
Configure Outbound email configuration in your outbound queue:
For Default email address, provide the email address you created earlier.
For Outbound email flow, provide the email flow for outbound emails (this flow will route outbound emails).
Choose Save.
Configure Microsoft 365 Exchange or Google Workspace
In this section, we provide step-by-step guidance to configure your primary email service with a rule (Microsoft) or route (Google) that sends inbound email addressed to a specific address(s) to Amazon Connect.
Option A: Microsoft 365 Exchange configuration
Complete the following steps to configure Microsoft 365 Exchange:
Find the email receiving endpoint for your Region. For example, inbound-smtp.us-west-2.amazonaws.com.
Create a connector in Exchange:
Navigate to the Exchange admin center.
Under Mail flow, choose Connectors.
Choose Add a connector.
Set Connection from to Office 365
Set Connection to to Your organization’s email server.
Choose Next.
Name the connector to identify the Region.
Choose Next.
For Use of connector, select Only when I have a transport rule set up that redirects messages to this connector.
For Routing, enter the SES email receiving endpoint.
Choose the plus sign, then choose Next.
For Security restrictions, select Always use Transport Layer Security (TLS) to secure the connection.
Follow your internal process for this step. In this example, we select Any digital certificate, including self-signed certificates.
Choose Next.
For Validation email, enter a valid email address currently used in your Amazon Connect instance.
Choose the plus sign, then choose Next. This will send a test email address to that email address. No action needs to be taken with the test email. You should see the email validated and receive the validation test email in the agent workspace.
Review your connector configuration and choose Create connector.
Validate that the connector status is set to On, then proceed to the next steps.
Create a mail flow rule to send your inbound email to Amazon Connect:
Under Mail flow, choose Rules.
Choose Add a rule¸ then choose Create a new rule.
Name the rule.
Set conditions to apply if the recipient is this person and choose the email address for Amazon Connect.
Set the action to Redirect the message to and the following connector and choose your new connector.
Choose Next.
Set Rule mode to Enforce.
Activate the rule immediately by specifying the current time.
Set Match sender address in message to Header or envelope.
Choose Next.
Review your rule configuration and choose Finish.
After you confirm your rule is enabled, you can test your configuration.
Option B: Google Workspace Gmail configuration
Complete the following steps to configure with Google Workspace:
Log into your Google Workspace admin account.
Navigate to Gmail.
Choose Hosts and choose Add Route.
Configure the mail route:
Provide a name indicating the Region.
Enter the SES email receiving endpoint and port 25.
Enable security options:
Select Require mail to be transmitted via a secure (TLS) connection.
Select Require CA signed certificate.
Select Validate certificate hostname.
Choose Test TLS connection.
If the connection is successful, choose SAVE.
Configure default routing:
Navigate to Default routing and choose Configure.
Enter the email address that should route to Amazon Connect.
Change the route to the mail route you created.
Select Perform this action on non-recognized and recognized addresses.
Save and confirm the route is enabled.
Test your configuration
After you have completed the appropriate steps above, test both inbound (to Amazon Connect) and outbound (from Amazon Connect) message-flows.
Test inbound (to Amazon Connect)
Test your inbound configuration:
Open your email application.
Send a test email to the email address you configured to be sent to Amazon Connect.
In the Amazon Connect agent workspace, accept the incoming email.
Confirm the email received in your agent workspace matches the email address you configured to be sent to Amazon Connect.
Test outbound (to external recipient from Amazon Connect)
Test your outbound configuration:
Log in to your Amazon Connect instance.
Choose New email.
Enter To address (use your work email address), Subject & Body.
Alternatively, To address (use your work email address) and choose a Template.
Click Send.
Check your work email inbox for the message. Verify the email’s From address is the email address you configured to be sent from Amazon Connect.
Once you have successfully tested email receiving and sending within Amazon Connect, request Amazon SES production access (see Moving out of the Amazon SES sandbox) in the Amazon SES Developer Guide. Importantly, you will not be able to send email from your domain via Amazon Connect until your account is removed from the SES sandbox.
Conclusion
In this post, we showed how to configure Amazon Connect to handle emails using your custom domain through Microsoft 365 or Google Workspace. This setup provides a seamless email experience for your customers while giving your agents the powerful tools available in the Amazon Connect agent workspace.
To get started with Amazon Connect Email, refer to the Amazon Connect Administrator Guide. For hands-on learners, the Amazon Connect Email Enablement Workshop provides guidance and exercises to configure Amazon Connect Email, set up email queues and routing rules, and discusses best practices for delivering exceptional email-based customer service.
Additional resources
For additional guidance and information, refer to the following resources:
In this post, we show how to configure customer trust stores to work with public certificates issued through AWS Certificate Manager (ACM). Organizations can encounter challenges when configuring trust stores for ACM certificates and incorrect trust store configuration can lead to SSL/TLS errors and application downtime. While most modern web browsers and operating systems trust ACM certificates by default, understanding how this trust is established and verifying proper configuration is important for IT professionals and developers. We also describe the relationship between public certificates issued through ACM and Amazon Trust Services. Whether you’re developing applications that connect to endpoints using ACM certificates or managing systems with customer trust stores that need to trust ACM certificates, this guide will provide you with insight regarding ACM certificate trust.
Background
ACM is a managed service that you can use to provision, manage, and deploy public and private SSL/TLS certificates. When you visit a website over HTTPS that has an ACM certificate, most modern web browsers will show a Connection is secure message in the address bar. This indicates that the web browser trusted the certificate. ACM certificates are trusted by popular browsers such as Chrome, Firefox, and Safari because they are issued by Amazon Trust Services, a public certificate authority (CA) managed by Amazon, whose root CA certificates are included by default in most web browsers’ and operating systems’ trust stores.
What is a trust store?
Web browsers, devices, and applications trust a collection of certificates known as CA certificates. These collections of CA certificates are called trust stores. Most often, the CA certificates in a trust store are root CA certificates. Root CA certificates are CA certificates that act as the foundation of trust. It’s best practice that root CAs issue intermediate CA certificates, which then issue end-entity certificates to minimize interaction with the root CA. When navigating to a website protected with HTTPS using a web browser, the website will present the end-entity certificate and the certificate chain. The certificate chain is a series of certificates, each issued by the next, leading back to a root CA certificate. The web browser will then check the end-entity certificate. It will make sure it’s derived from a root certificate that is in its trust store. It is important to note that trust store configurations can vary depending on the web browser, device or application.
Amazon Trust Services
Amazon Trust Services is a publicly trusted CA that is managed by Amazon. Amazon Trust Services root CA certificates are included in the trust stores of most web browsers and operating systems. As shown in Figure 1, when you request a public ACM certificate through DNS, Email, or HTTP validation, it will be issued by one of the multiple intermediate CAs that Amazon manages. These intermediate CAs are issued by one of the five Amazon Trust Services root CAs. Therefore, by trusting the Amazon Trust Services root CAs, you will be trusting ACM certificates. It’s important to note that ACM uses a dynamic intermediate CA model. This means you cannot predict which specific intermediate CA will issue an ACM certificate. The issuing intermediate CA is selected dynamically from a group of intermediate CAs at the time of certificate issuance. This means that the intermediate CA that issues ACM certificates is non-deterministic. In summary, we recommend customer trust stores include the five Amazon Trust Services root CA certificates. This includes Amazon Root CA 1, Amazon Root CA 2, Amazon Root CA 3, Amazon Root CA 4 and Starfield Services Root Certificate Authority – G2.
Figure 1 – ACM certificate chain
Best practices
To help establish reliable HTTPS connections to endpoints using ACM certificates, we recommend that your trust stores include the fiveAmazon root CAs.
Adding the five Amazon root CAs provide maximum compatibility for trusting ACM certificates. If you must use certificate pinning in your application, we recommend that you pin to the public key of the mentioned root CAs.
While addressing the best practices, it is important to review how trust stores should notbe configured.
Don’t limit your trust stores to only the intermediate CA certificates that issue ACM certificates. Examples of such intermediate CAs include Amazon RSA 2048 M01, Amazon RSA 2048 M02, Amazon RSA 2048 M03. Adding only these intermediate CA certificates to your trust store will introduce risk to your application. This is because of the dynamic intermediate CA (ICA) model. When an ACM certificate is issued or when it’s renewed, it will be from one of the many intermediate CAs. Furthermore, they are non-deterministic. If an ACM certificate was first issued by Amazon RSA 2048 M01,there is no guarantee that it will renew from that same intermediate CA.
In summary, here are the best practices for trusting ACM certificates.
Add the five Amazon root CAs listed in Amazon Trust Services to your trust stores: Amazon Root CA 1 through 4 and Starfield Services Root Certificate Authority – G2.
You should only add Amazon root CAs to your trust store, not their intermediate CAs or end-entity certificates. Because of the dynamic intermediate CA (ICA) model, installing only intermediate CAs or end-entity certificates will introduce risk to your trust store and application.
Do not pin an ACM certificate (end-entity) or its intermediate CA certificate.
If you require pinning, we recommend that you pin to the public key of the Amazon root CAs.
How do I verify that the Amazon root CAs are in my trust store?
As mentioned in the previous section, most modern web browsers and operating systems already include the five Amazon root CAs in their respective trust stores by default. It’s still recommended to verify that the Amazon root CAs are installed correctly. It’s important to note that many applications have different trust store locations. For example, an application might use the Windows trust store location—Trusted Root Certification Authorities—as its trust store or it might use a PEM trust store in a custom directory. This is why we recommend that you review your application’s trust store documentation.
To verify, check your system’s trust store for existing Amazon root CA certificates. If they are not present, you can proceed with adding the five Amazon root CA certificates.
Windows: Check for the Amazon root CAs in Windows operating systems (GUI)
Press Windows + R, enter certmgr.msc , then press Enter.
Go to Trusted Root Certification Authorities and choose Certificates.
Figure 2: Windows certificate store: Trusted Root Certification Authorities
Check for the Amazon root CAs in Windows operating systems (CLI)
You can use Powershell to check for the Amazon root CAs. Use the certutil command.
Open Windows Powershell and use the following certutil commands. These will search for the five Amazon root CAs.
To add the Amazon root CAs to the default trust store
1. Navigate to the following directory for adding CA certificates $ cd /etc/pki/ca-trust/source/anchors/
2. Using cURL, download each Amazon Trust Services root CA in the preceding folder. Do this for each of the Amazon root CAs replacing the name of the PEM file as needed.
3. Add the root CAs by updating the system trust store. $ sudo update-ca-trust extract
4. Verify that the bundle has been updated with OpenSSL. $ openssl crl2pkcs7 -nocrl -certfile /etc/pki/tls/certs/ca-bundle.crt | openssl pkcs7 -print_certs -noout | grep -i "Amazon\|Starfield Services"
Java: Check for the Amazon root CAs in a Java trust store (Java Keystore)
Many custom Java applications use Java Keystore (JKS) as a trust store. You can use the keytool CLI tool to verify if the Amazon root CAs exist in your JKS trust store.
keytool -list -keystore custom_truststore.jks -storepass mypassword
Keystore type: PKCS12
Keystore provider: SUN
Your keystore contains 5 entries
amazonrootca1, Jun 27, 2025, trustedCertEntry, Certificate fingerprint (SHA-256): 8E:CD:E6:88:4F:3D:87:B1:12:5B:A3:1A:C3:FC:B1:3D:70:16:DE:7F:57:CC:90:4F:E1:CB:97:C6:AE:98:19:6E
amazonrootca2, Jun 27, 2025, trustedCertEntry, Certificate fingerprint (SHA-256): 1B:A5:B2:AA:8C:65:40:1A:82:96:01:18:F8:0B:EC:4F:62:30:4D:83:CE:C4:71:3A:19:C3:9C:01:1E:A4:6D:B4
amazonrootca3, Jun 27, 2025, trustedCertEntry, Certificate fingerprint (SHA-256): 18:CE:6C:FE:7B:F1:4E:60:B2:E3:47:B8:DF:E8:68:CB:31:D0:2E:BB:3A:DA:27:15:69:F5:03:43:B4:6D:B3:A4
amazonrootca4, Jun 27, 2025, trustedCertEntry, Certificate fingerprint (SHA-256): E3:5D:28:41:9E:D0:20:25:CF:A6:90:38:CD:62:39:62:45:8D:A5:C6:95:FB:DE:A3:C2:2B:0B:FB:25:89:70:92
starfieldg2, Jun 27, 2025, trustedCertEntry, Certificate fingerprint (SHA-256): 56:8D:69:05:A2:C8:87:08:A4:B3:02:51:90:ED:CF:ED:B1:97:4A:60:6A:13:C6:E5:29:0F:CB:2A:E6:3E:DA:B5
The output should show the Amazon root CAs listed as “trustedCertEntry” with those exact certificate fingerprints.
To add the Amazon root CAs to a Java trust store (Java Keytool)
1. Download each Amazon Trust Services root CA in PEM or DER format. Use the PowerShell command Invoke-WebRequest if you’re using Windows, or use cURL if you’re using a Linux-based operating system or MacOS.
2. Import the Amazon root CAs to the trust store—custom_truststore.jks. Replace changeit with your JKS password. Do this command for each of the Amazon root CAs, replacing the name of the root CA as needed.
After you have set up your trust store with the five Amazon root CA certificates, you can perform tests to confirm that the installed root CAs are correctly providing trust. Remember that your custom application might be sourcing its trust from a store other than the stores mentioned in this article. For custom applications, we recommend checking your testing documentation.
PEM
For operating systems or applications that use PEM certificate bundles, such as Amazon Linux 2023, you can use OpenSSL or cURL to test. For additional test URLs, see the Amazon Trust Services website. Replace CAbundle.pem with your certificate bundle.
Because Windows doesn’t use PEM certificate bundles, but a trust store in certmgr called Trusted Root Certification Authorities, you can use PowerShell to test.
1. Copy the following PowerShell script and save it in a file named ssl-connect.ps1.
2. Run the PowerShell script with the following command:
> .\ssl-connect.ps1
You can test with the other test URLs by passing them in -url:
> .\ssl-connect.ps1 -url https://s3.amazonaws.com
3. After running the command, you should see the subject and issuer of the end-entity certificate and the full trust chain, including the intermediate CA and root CA. If the command returns Certificate is valid and trusted, the certificate is trusted. If it returns an error with Certificate error, the error should tell you what went wrong.
Java
To test your Java applications that use JKS as a trust store, you can make HTTPS connections to endpoints that use Amazon Trust Services certificates.
1. Copy the Java code and name the file SSLTester.java.
In the code, you can replace the urls variable with additional URLs to test HTTPS. See the Amazon Trust Services website for additional test URLs.
Update your_keystore.jks and your password with your JKS file path and password.
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import java.io.FileInputStream;
import java.net.URL;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
public class SSLTester {
public static void main(String[] args) {
// Enable revocation checking
System.setProperty("com.sun.net.ssl.checkRevocation", "true");
System.setProperty("com.sun.security.enableCRLDP", "true");
System.setProperty("com.sun.security.enableAIAcaIssuer", "true");
// Define your HTTPS URLs here
String[] urls = {
"https://valid.rootca1.demo.amazontrust.com/", // Use an Amazon Trust Services Valid test URL (Example: https://valid.rootca1.demo.amazontrust.com/)
"https://revoked.rootca1.demo.amazontrust.com/", // Use an Amazon Trust Services Revoked test URL (Example: https://revoked.rootca1.demo.amazontrust.com/)
"https://expired.rootca1.demo.amazontrust.com/", // Use an Amazon Trust Services Expired test URL (Example: https://expired.rootca1.demo.amazontrust.com/)
"https://ec2.amazonaws.com" // AWS Service Endpoint
};
String keystorePath = "your_keystore.jks"; // Define your .jks file
String keystorePassword = "your password"; // Pass your keystore password
try {
// Load the JKS
KeyStore trustStore = KeyStore.getInstance("JKS");
FileInputStream fis = new FileInputStream(keystorePath);
trustStore.load(fis, keystorePassword.toCharArray());
fis.close();
// Initialize TrustManagerFactory with JKS
TrustManagerFactory tmf =
TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(trustStore);
// Initialize SSLContext
SSLContext sslContext =
SSLContext.getInstance("TLS");
sslContext.init(null, tmf.getTrustManagers(), null);
// Test SSL connections to URLs
for (String urlStr : urls) {
System.out.println("Testing URL: " + urlStr);
try {
URL url = new URL(urlStr);
javax.net.ssl.HttpsURLConnection conn = (javax.net.ssl.HttpsURLConnection) url.openConnection(); conn.setSSLSocketFactory(sslContext.getSocketFactory());
conn.connect();
// Get server certificate
Certificate[] certs =
conn.getServerCertificates();
for (Certificate cert : certs) {
if (cert instanceof X509Certificate) {
X509Certificate x509Cert = (X509Certificate) cert;
System.out.println("Certificate: " + x509Cert.getSubjectDN());
}
}
System.out.println("Connection successful for " + urlStr);
conn.disconnect();
} catch (Exception e) {
System.err.println("Failed for " + urlStr + ": " + e.getMessage());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
2. After you save the file, compile it and run.
javac SSLTester.java java SSLTester.java
3. Check the output after it’s finished running.
For Valid URLs, you should see Connection successful:
Connection successful for https://valid.rootca1.demo.amazontrust.com/
For Revoked URLs, you should see Certificate has been revoked:
failed: java.security.cert.CertPathValidatorException: Certificate has been revoked, reason: UNSPECIFIED
For Expired URLs, you should see Validity check failed:
When your web browser, device, or application performs HTTPS connections, it validates the certificate presented by the server using its trust store. A trust store is a collection of trusted CA certificates, primarily consisting of root CA certificates. When trusting endpoints using public certificates issued through ACM, best practice recommends installing the five Amazon Trust Services root CA certificates into your trust store. Be aware that trusting only the Amazon Trust Services intermediate CA certificates, such as Amazon RSA 2048 M01 and Amazon RSA 2048 M02, increases your application’s risk for outages. This is because of the non-deterministic nature of the dynamic intermediate CA (ICA) model. It’s worth noting that trust store configurations can vary across different applications. Furthermore, applications can also source their trust store from different locations. For example, you can have a Java application hosted on a Windows-based operating system that sources its trust store from a Java Keystore (JKS) file rather than the default Windows trust store location Trusted Root Certification Authorities. This means that you should thoroughly test your application after installing the Amazon Trust Services root CA certificates in your trust store. This will help to sustain reliable HTTPS connections to endpoints using ACM certificates.
If you have feedback about this post, submit comments in the Comments section below. If you have questions about this post, contact AWS Support.
Over the years, organizations have invested in building purpose-built cloud-based data warehouses that are siloed from one another. One of the major challenges these organizations encounter today is enabling cross-organization discovery and access to data across these siloed data warehouses built using different technology stacks. The data mesh pattern addresses these issues, founded in four principles: domain-oriented decentralized data ownership and architecture, treating data as a product, providing self-serve data infrastructure as a platform, and implementing federated governance. The data mesh pattern helps organizations mimic their organizational structure into data domains and makes it possible to share the data across the organization and beyond to improve their business models.
In 2019, Volkswagen AG and Amazon Web Services (AWS) started their collaboration to co-develop the Digital Production Platform (DPP), with the goal of enhancing production and logistics efficiency by 30% while reducing production costs by the same margin. The DPP was developed to streamline access to data from shop floor devices and manufacturing systems by handling integrations and providing a range of standardized interfaces. However, as applications and use cases evolved on the platform, a significant challenge emerged: the ability to share data across applications stored in isolated data warehouses (within Amazon Redshift in isolated AWS accounts designated for specific use cases), without the need to consolidate data into a central data warehouse. Another challenge was discovering all the available data stored across multiple data warehouses and facilitating a workflow to request access to data across business domains within each plant. The common method used was largely manual, relying on emails and general communication (through tickets and emails). The manual approach not only increased the overhead but also varied from one use case to another in terms of data governance.
In this post, we introduce Amazon DataZone and explore how Volkswagen used Amazon DataZone to build their data mesh, tackle the challenges encountered, and break the data silos. A key aspect of the solution was enabling data providers to automatically publish their data products to Amazon DataZone, serving as a central data mesh for enhanced data discoverability. Additionally, we provide code to guide you through the deployment and implementation process.
Introduction to Amazon DataZone
Amazon DataZone is a data management service that makes it faster and straightforward to catalog, discover, share, and govern data stored across AWS, on-premises, and third-party sources. Key features of Amazon DataZone include the business data catalog, with which users can search for published data, request access, and start working on data in days instead of weeks. In addition, the service facilitates collaboration across teams and helps them manage and monitor data assets across different organizational units. The service also includes the Amazon DataZone portal, which offers a personalized analytics experience for data assets through a web-based application or API. Lastly, Amazon DataZone offers governed data sharing, which makes sure the right data is accessed by the right user for the right purpose with a governed workflow.
Solution overview
The following architecture diagram represents a high-level design that is built on top of the data mesh pattern. It separates source systems, data domain producers (data publishers), data domain subscribers (data consumers), and central governance to highlight the key aspects. This data mesh architecture is specially tailored for cross-AWS account usage. The objective of this approach is to create a foundation for building data governance on a scale, supporting the objectives of data producers and consumers with strong and consistent governance.
This architecture allows for the integration of multiple data warehouses into a centralized governance account that stores all the metadata from each environment.
A data domain producer uses Amazon Redshift as their analytical data warehouse to store, process, and manage structured and semi-structured data. The data domain producers load data into their respective Amazon Redshift clusters through extract, transform, and load (ETL) pipelines they manage, own, and operate. The producers maintain control over their data through Amazon Redshift security features, including column-level access controls and dynamic data masking, supporting data governance at the source. A data domain producer uses Amazon Redshift ETL and Amazon Redshift Spectrum to process and transform raw data into consumable data products. The data products could be Amazon Redshift tables, views, or materialized views.
Data domain producers expose datasets to the rest of the organization by registering them to Amazon DataZone service, which acts as a central data catalog. They can choose what data assets to share, for how long, and how consumers can interact with these. They’re also responsible for maintaining the data and making sure it’s accurate and current.
The data assets from the producers are then published using the data source run to Amazon DataZone in the central governance account. This process populates the technical metadata into the business data catalog for each data asset. The business metadata can be added by business users (data analysts) to provide business context, tags, and data classification for the datasets. This approach provides the required features to allow producers to create catalog entries with Amazon Redshift from all their data warehouses built in with Redshift clusters. In addition, the central data governance account is used to share datasets securely between producers and consumers. It’s important to note that sharing is done through metadata linking alone. No data (except logs) exists in the governance account. The data isn’t copied to the central account; just a reference to the data is used, so that the data ownership remains with the producer.
Amazon DataZone provides a streamlined way to search for data. The Amazon DataZone data portal provides a personalized view for users to discover and search data assets. An Amazon DataZone user (consumer) with permissions to access the data portal can search for assets and submit requests for subscription of data assets using a web-based application. An approver can then approve or reject the subscription request.
When a data domain consumer has access to an asset in the catalog, they can consume it (query and analyze) using the Amazon Redshift query editor. Each consumer runs their own workload based on their use case. In this way, the team can choose the tools for the job to perform analytics and machine learning activities in its AWS consumer environment.
Publishing and registering data assets to Amazon DataZone
To publish a data asset from the producer account, each asset must be registered in Amazon DataZone for consumer subscription. For more information, refer to Create and run an Amazon DataZone data source for Amazon Redshift. In the absence of an automated registration process, required tasks must be completed manually for each data asset.
Using the automated registration workflow, the manual steps can be automated for the Amazon Redshift data asset (Redshift table or view) that needs to be published in an Amazon DataZone domain or when there’s a schema change in an already published data asset.
The following architecture diagram represents how data assets from Amazon Redshift data warehouses have been automatically published to the data mesh created with Amazon DataZone.
The process consists of the following steps:
In the producer account (Account B), the data to be shared resides in a Redshift cluster.
The producer account (Account B) uses a mechanism to trigger the dataset registration AWS Lambda function with a specific payload containing the information and name of the database, schema, table, or view that has a change in metadata.
The Lambda function performs the steps to automatically register and publish the dataset in Amazon DataZone:
Get the Amazon Redshift clusterName, dbName, schemas, and tables from the JSON payload, which is used as the event to trigger the Lambda function.
Get the Amazon DataZone data warehouse blueprint ID.
Enable the blueprint in the data producer account.
Identify the Amazon DataZone Domain ID and project ID for the producer via assuming role in Amazon DataZone account (Account A).
Check if an environment already exists in the project. If not, create an environment.
Create a new Redshift data source by providing the correct Redshift database information in the newly created environment.
Initiate a data source run request in the data source to make the Redshift tables or views available in Amazon DataZone.
Publish the tables or views in the Amazon DataZone catalog.
Prerequisites
The following prerequisites are required before starting:
Two AWS accounts to implement the solution have been described in this post. However, you can also use Amazon DataZone to publish data within a single account or across multiple accounts.
Amazon DataZone account (Account A) – This is the central data governance account, which will have the Amazon DataZone domain and project.
Data domain producer account (Account B) – This account acts as the data domain producer. It has been added as an associated account to Account A.
Prerequisites in data domain producer account (Account B)
As part of this post, we want to publish assets and subscribe to assets from a Redshift cluster that already exists. Complete the following prerequisite steps to set up Account B:
Set up the Redshift cluster, including database, schema, tables, and views (optional). The node type must be from the RA3 family. For more information, see Amazon Redshift provisioned clusters.
Create a superuser in Amazon Redshift for Amazon DataZone. For the Redshift cluster, the database user you provide in AWS Secrets Manager must have superuser permissions. For reference please see the note section in this QuickStart guide with sample Amazon Redshift data
Store the user’s credentials in Secrets Manager. Select the credential type, enter the credential values, and choose the AWS Key Management Service (AWS KMS) key with which to encrypt the secret.
Add the tags to the Secret Manager secret to allow Amazon DataZone to find this secret and limit the access to a particular Amazon DataZone domain and Amazon DataZone project. The Redshift cluster Amazon Resource Name (ARN) must be added as a tag so it can be used by Amazon Redshift as a valid credential. For reference please see the note section in this QuickStart guide with sample Amazon Redshift data
If your secret is encrypted with a custom KMS key, append the key policy with the following statement and add a tag to the key: AmazonDatazoneEnvironment = All. You can skip this step if you’re using an AWS managed KMS key.
Place a mechanism to generate the following payload to trigger the dataset registration Lambda function. The payload must contain the relevant Redshift database, schema, and table or view that you want to publish in the Amazon DataZone domain. The following example code assumes you have three databases in your Redshift cluster and within those databases you have different schemas, tables, and views. You should adjust the payload based on your use case.
Prerequisites in Amazon DataZone account (Account A)
Complete the following steps to set up your Amazon DataZone account (Account A):
Sign in to Account A and make sure you have already deployed an Amazon DataZone domain and a project within that domain. Refer to Create Amazon DataZone domains for instructions to create a domain.
If your Amazon DataZone domain is encrypted with a KMS key, add the data domain account (Account B) to the KMS key policy with the following actions:
Create an IAM role that is assumable by Account B and make sure the role has a following policy attached and is a member (as contributor) of your Amazon DataZone project. For this post, we call the role dz-assumable-env-dataset-registration-role. By adding this role, you can successfully run the registration Lambda function.
In the following policy, provide the AWS Region and account ID corresponding to where your Amazon DataZone domain is created, and the KMS key ARN used to encrypt the domain:
Add the role as a member of the Amazon DataZone project in which you want to register your data sources. For more information, see Add members to a project.
Additional tools
The following tools are needed to deploy the solution using the AWS CDK:
After you complete the prerequisites, use the AWS CDK stack provided on the GitHub repo to deploy the solution for automatic registration of data assets into the Amazon DataZone domain. Complete the following steps:
Clone the repository from GitHub to your preferred integrated development environment (IDE) using the following commands:
Bootstrap the AWS CDK environment with the following commands at the base of the repository folder. Provide the profile name of your deployment account (Account B). Bootstrapping is a one-time activity and is not needed if your AWS account is already bootstrapped.
$ export AWS_PROFILE=<<PROFILE_NAME>>
$ npm run cdk bootstrap
Replace the placeholder parameters (marked with the suffix _PLACEHOLDER) in the file config/DataZoneConfig.ts:
Amazon DataZone domain and project name of your Amazon DataZone instance. Make sure all names are in lowercase.
The AWS account ID of the Amazon DataZone account (Account A).
The assumable IAM role from the prerequisites.
The AWS Systems Manager parameter name containing the Secrets Manager secret ARN of the Amazon Redshift credentials.
Use the following command in the base folder to deploy the AWS CDK solution. During deployment, enter y if you want to deploy the changes for some stacks when you see the prompt Do you wish to deploy these changes (y/n)?
npm run cdk deploy --all
After the deployment is complete, sign in to Account B and open the AWS CloudFormation console to verify that the infrastructure was deployed.
Test automatic data registration to Amazon DataZone
Complete the following steps to test the solution:
Sign in to Account B (producer account).
On the Lambda console, open the datazone-redshift-dataset-registration function.
Under TEST EVENTS, choose Create new test event.
For Event name, enter Redshift, and for Event JSON, enter the following JSON structure (change the cluster, schema, database, and table names according to your environment):
Complete the following steps to clean up the resources deployed through the AWS CDK:
Sign in to Account B, go to the Amazon DataZone domain portal, and check there is no subscription for your published data asset. If there is a subscription, either ask the subscriber to unsubscribe or revoke the subscription request.
Delete the published data assets that were created in the Amazon DataZone project by the dataset registration Lambda function.
Delete the remaining resources created using the following command in the base folder:
npm run cdk destroy –all
Conclusion
Amazon DataZone offers a seamless integration with AWS services, providing a powerful solution for organizations like Volkswagen to break down their data silos and implement effective data mesh architectures through a straightforward implementation highlighted in this post. By using Amazon DataZone, Volkswagen addressed its immediate data sharing hurdles and laid the groundwork for a more agile, data-driven future in automotive manufacturing. The automated data publishing from various warehouses, coupled with standardized governance workflows, has significantly reduced the manual overhead that once slowed down Volkswagen’s data engineering teams. Now, instead of navigating a labyrinth of emails, tickets, and communication, Volkswagen’s data engineers and data scientists can quickly discover and access the data they need, all while maintaining their security and compliance standards.
By using Amazon DataZone, organizations can bring their isolated data together in ways that make it simpler for teams to collaborate while maintaining security and compliance at scale. This approach not only addresses current data governance challenges but also creates a highly scalable foundation for future data-driven innovations. For guidance on establishing your organization’s data mesh with Amazon DataZone, contact your AWS team today.
Migrating from Google Cloud’s BigQuery to ClickHouse Cloud on AWS allows businesses to leverage the speed and efficiency of ClickHouse for real-time analytics while benefiting from AWS’s scalable and secure environment. This article provides a comprehensive guide to executing a direct data migration using AWS Glue ETL, highlighting the advantages and best practices for a seamless transition.
AWS Glue ETL enables organizations to discover, prepare, and integrate data at scale without the burden of managing infrastructure. With its built-in connectivity, Glue can seamlessly read data from Google Cloud’s BigQuery and write it to ClickHouse Cloud on AWS, removing the need for custom connectors or complex integration scripts. Beyond connectivity, Glue also provides advanced capabilities such as a visual ETL authoring interface, automated job scheduling, and serverless scaling, allowing teams to design, monitor, and manage their pipelines more efficiently. Together, these features simplify data integration, reduce latency, and deliver significant cost savings, enabling faster and more reliable migrations.
Prerequisites
Before using AWS Glue to integrate data into ClickHouse Cloud, you must first set up the ClickHouse environment on AWS. This includes creating and configuring your ClickHouse Cloud on AWS, making sure network access and security groups are properly defined, and verifying that the cluster endpoint is accessible. Once the ClickHouse environment is ready, you can leverage the AWS Glue built-in connector to seamlessly write data into ClickHouse Cloud from sources such as Google Cloud BigQuery. You can follow the next section to complete the setup.
Choose View purchase options on the right top of the view
Review Terms and Conditions and choose Accept Terms
Choose Continue to Configuration once it’s enabled
On Follow the vendor’s instructions part in the connector instructions as below, choose the connector enabling link at step 3
Configure AWS Glue ETL Job for ClickHouse Integration
AWS Glue enables direct migration by connecting with ClickHouse Cloud on AWS through built-in connectors, allowing for seamless ETL operations. Within the Glue console, users can configure jobs to read data from S3 and write it directly to ClickHouse Cloud. Using AWS Glue Data Catalog, data in S3 can be indexed for efficient processing, while Glue’s PySpark support allows for complex data transformations, including data type conversions, to support compatibility with ClickHouse’s schema.
Open AWS Glue in the AWS Management Console
Navigate to Data Catalog and Connections
Create a new connection
Configure BigQuery Connection in Glue
Prepare a Google Cloud BigQuery Environment
Create and Store Google Cloud Service Account Key (JSON format) in AWS Secret Manager, you can find the details in BigQuery connections.
Grant the IAM role associated with your AWS Glue job permission for S3, Secret Manager, Glue services, and AmazonEC2ContainerRegistryReadOnly for accessing connectors purchased from AWS Marketplace (reference doc)
Create ClickHouse connection in AWS Glue
Enter clickhouse-connection as its connection name
Choose Create connection and activate connector
Create a Glue job
On the Connectors view as below, select clickhouse-connection and choose Create job
Enter bq_to_clickhouse as its job name and configure gc_connector_role as its IAM Role
Configure BigQuery connection and clickhouse-connection to the Connection property
Choose the Script tab and Edit script. Then choose Confirm on the Edit script popup view.
Copy and paste the following code onto the script editor which can be referred from clickhouse official doc
The source code is as following:
import sys
from pyspark.sql import SparkSession
from awsglue.context import GlueContext
from awsglue.job import Job
from awsglue.utils import getResolvedOptions
args = getResolvedOptions(sys.argv, ['JOB_NAME'])
spark = SparkSession.builder.getOrCreate()
glueContext = GlueContext(spark.sparkContext)
job = Job(glueContext)
job.init(args['JOB_NAME'], args)
connection_options = {
"connectionName": "Bigquery connection",
"parentProject": "YOUR_GCP_PROJECT_ID",
"query": "SELECT * FROM `YOUR_GCP_PROJECT_ID.bq_test_dataset.bq_test_table`",
"viewsEnabled": "true",
"materializationDataset": "bq_test_dataset"
}
jdbc_url = " jdbc:clickhouse://YOUR_CLICKHOUSE_CONNECTION.us-east-1.aws.clickhouse.cloud:8443/clickhouse_database?ssl=true "
username = "default"
password = "YOUR_PASSWORD"
query = "select * from clickhouse_database.clickhouse_test_table"
# Add this before writing to test connection
try:
# Read from BigQuery with Glue Connection
print("Reading data from BigQuery...")
GoogleBigQuery_node1742453400261 = glueContext.create_dynamic_frame.from_options(
connection_type="bigquery",
connection_options=connection_options,
transformation_ctx="GoogleBigQuery_node1742453400261"
)
# Convert to DataFrame
bq_df = GoogleBigQuery_node1742453400261.toDF()
print("Show data from BigQuery:")
bq_df.show()
# Write BigQuery Data to Clickhouse with JDBC
bq_df.write \
.format("jdbc") \
.option("driver", 'com.clickhouse.jdbc.ClickHouseDriver') \
.option("url", jdbc_url) \
.option("user", username) \
.option("password", password) \
.option("dbtable", "clickhouse_test_table") \
.mode("append") \
.save()
print("Write BigQuery Data to ClickHouse successfully")
# Read from Clickhouse with JDBC
reaf_df = (spark.read.format("jdbc")
.option("driver", 'com.clickhouse.jdbc.ClickHouseDriver')
.option("url", jdbc_url)
.option("user", username)
.option("password", password)
.option("query", query)
.option("ssl", "true")
.load())
print("Show Data from ClickHouse:")
reaf_df.show()
except Exception as e:
print(f"ClickHouse connection test failed: {str(e)}")
raise e
finally:
job.commit()
Choose Save and Run on the right top of the current view
Testing and Validation
Testing is crucial to verify data accuracy and performance in the new environment. After the migration completes, run data integrity checks to confirm record counts and data quality in ClickHouse Cloud. Schema validation is essential, as each data field must align correctly with ClickHouse’s format. Running performance benchmarks, such as sample queries, will help verify that ClickHouse’s setup delivers the desired speed and efficiency gains.
The Schema and Data in source BigQuery and destination Clickhouse
AWS Glue output logs
Clean Up
After completing the migration, it’s important to clean up unused resources—such as BigQuery for sample data import and database resources in ClickHouse Cloud—to avoid unnecessary costs. Regarding IAM permissions, adhering to the principle of least privilege is advisable. This involves granting users and roles only the permissions necessary for their tasks and removing unnecessary permissions when they are no longer required. This approach enhances security by minimizing potential threat surfaces. Additionally, reviewing AWS Glue job costs and configurations can help identify optimization opportunities for future migrations. Monitoring overall costs and analyzing usage can reveal areas where code or configuration improvements may lead to cost savings.
Conclusion
AWS Glue ETL offers a robust and user-friendly solution for migrating data from BigQuery to ClickHouse Cloud on AWS. By utilizing Glue’s serverless architecture, organizations can perform data migrations that are efficient, secure, and cost-effective. The direct integration with ClickHouse streamlines data transfer, supporting high performance and flexibility. This migration approach is particularly well-suited for companies looking to enhance their real-time analytics capabilities on AWS.
Organizations manage content across multiple languages as they expand globally. Ecommerce platforms, customer support systems, and knowledge bases require efficient multilingual search capabilities to serve diverse user bases effectively. This unified search approach helps multinational organizations maintain centralized content repositories while making sure users, regardless of their preferred language, can effectively find and access relevant information.
Building multi-language applications using language analyzers with OpenSearch commonly involves a significant challenge: multi-language documents require manual preprocessing. This means that in your application, for every document, you must first identify each field’s language, then categorize and label it, storing content in separate, pre-defined language fields (for example, name_en, name_es, and so on) in order to use language analyzers in search to improve search relevancy. This client-side effort is complex, adding workload for language detection, potentially slowing data ingestion, and risking accuracy issues if languages are misidentified. It’s a labor-intensive approach. However, Amazon OpenSearch Service 2.15+ introduces an AI-based ML inference processor. This new feature automatically identifies and tags document languages during ingestion, streamlining the process and removing the burden from your application.
By harnessing the power of AI and using context-aware data modeling and intelligent analyzer selection, this automated solution streamlines document processing by minimizing manual language tagging, and enables automatic language detection during ingestion, providing organizations sophisticated multilingual search capabilities.
Using language identification in OpenSearch Service offers the following benefits:
Enhanced user experience – Users can now find relevant content regardless of the language they search in
Increased content discovery – The service can surface valuable content across language silos
Improved search accuracy – Language-specific analyzers provide better search relevance
Automated processing – You can reduce manual language tagging and classification
In this post, we share how to implement a scalable multilingual search solution using OpenSearch Service.
Solution overview
The solution eliminates manual language preprocessing by automatically detecting and handling multilingual content during document ingestion. Instead of manually creating separate language fields (en_notes, es_notes, and so on) or implementing custom language detection systems, the ML inference processor identifies languages and creates appropriate field mappings.
This automated approach improves accuracy compared to traditional manual methods and reduces development complexity and processing overhead, allowing organizations to focus on delivering better search experiences to their global users.
The solution comprises the following key components:
ML inference processor – Invokes ML models during document ingestion to enrich content with language metadata
Amazon SageMaker integration – Hosts pre-trained language identification models that analyze text fields and return language predictions
Language-specific indexing – Applies appropriate analyzers based on detected languages, providing proper handling of stemming, stop words, and character normalization
In the following sections, we walk through the steps to deploy the solution. For detailed implementation instructions, including code examples and configuration templates, refer to the comprehensive tutorial in the OpenSearch ML Commons GitHub repository.
Deploy a pre-trained language identification model on Amazon SageMaker. The XLM-RoBERTa model provides robust multilingual language detection capabilities suitable for most use cases.
Configure the connector
Create an ML connector to establish a secure connection between OpenSearch Service and Amazon SageMaker endpoints, primarily for language detection tasks. The process begins with setting up authentication through IAM roles and policies, applying proper permissions for both services to communicate securely.
After you configure the connector with the appropriate endpoint URLs and credentials, the model is registered and deployed in OpenSearch Service and its modelID is used in subsequent steps.
POST /_plugins/_ml/models/_register
{
"name": "sagemaker-language-identification",
"version": "1",
"function_name": "remote",
"description": "Remote model for language identification",
"connector_id": "your_connector_id"
}
After you configure the connector, you can test is by sending text to the model through OpenSearch Service, and it will return the detected language (for example, sending “Say this is a test” returns en for English).
POST /_plugins/_ml/models/your_model_id/_predict
{
"parameters": {
"inputs": "Say this is a test"
}
}
{
"inference_results": [
{
"output": [
{
"name": "response",
"dataAsMap": {
"response": [
{
"label": "en",
"score": 0.9411176443099976
}
]
}
}
]
}
]
}
Set up the ingest pipeline
Configure the ingest pipeline, which uses ML inference processors to automatically detect the language of the content in the name and notes fields of incoming documents. After language detection, the pipeline creates new language-specific fields by copying the original content to new fields with language suffixes (for example, name_en for English content).
The pipeline uses an ml_inference processor to perform the language detection and copy processors to create the new language-specific fields, making it straightforward to handle multilingual content in your OpenSearch Service index.
Create an index with the ingest pipeline that automatically detects the language of incoming documents and applies appropriate language-specific analysis. When documents are ingested, the system identifies the language of key fields, creates language-specific versions of those fields, and indexes them using the correct language analyzer. This allows for efficient and accurate searching across documents in multiple languages without requiring manual language specification for each document.
Here’s a sample index creation API call demonstrating different language mappings.
{
"name": "Kaufen Sie Katzenminze",
"notes": "Mittens mag die Sachen von Humboldt wirklich."
}
The German text used in the preceding code will be processed using a German-specific analyzer, supporting proper handling of language-specific characteristics such as compound words and special characters.
After successful ingestion into OpenSearch Service, the resulting document appears as follows:
{
"_source": {
"predicted_notes_language": "en",
"name_en": "Buy catnip",
"notes": "Mittens really likes the stuff from Humboldt.",
"predicted_name_language": "en",
"name": "Buy catnip",
"notes_en": "Mittens really likes the stuff from Humboldt."
}
}
Search documents
This step demonstrates the search capability after the multilingual setup. By using a multi_match query with name_* fields, it searches across all language-specific name fields (name_en, name_es, name_de) and successfully finds the Spanish document when searching for “comprar” because the content was properly analyzed using the Spanish analyzer. This example shows how the language-specific indexing enables accurate search results in the correct language without needing to specify which language you’re searching in.
Implementing multilingual search with OpenSearch Service can help organizations break down language barriers and unlock the full value of their global content. The ML inference processor provides a scalable, automated approach to language detection that improves search accuracy and user experience.
This solution addresses the growing need for multilingual content management as organizations expand globally. By automatically detecting document languages and applying appropriate linguistic processing, businesses can deliver comprehensive search experiences that serve diverse user bases effectively.
About the authors
The collective thoughts of the interwebz
Manage Consent
To provide the best experiences, we use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us to process data such as browsing behavior or unique IDs on this site. Not consenting or withdrawing consent, may adversely affect certain features and functions.
Functional
Always active
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
The technical storage or access that is used exclusively for statistical purposes.The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
Marketing
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.