Of course! This is an excellent use case for the aws-cdk-monitoring-constructs library. I'll guide you through building a complete, deployable CDK application that accomplishes your goal.
The solution involves two main parts:
- The CDK Code (in the Workload Account): This code will define your Lambda, SQS queues, the monitoring configuration, a CloudWatch Dashboard, and a special IAM Role that the other account can assume to view the metrics.
- AWS Console Configuration (in the Monitoring Account): A one-time setup in the monitoring account's CloudWatch console to tell it how to access the dashboard from the workload account.
Let's break down the CDK code first.
Prerequisites
- Install AWS CDK: If you haven't already, install the AWS CDK toolkit.
npm install -g aws-cdk
- Initialize a new CDK Project:
mkdir cdk-cross-account-monitoring
cd cdk-cross-account-monitoring
cdk init app --language typescript
- Install the Monitoring Construct:
npm install aws-cdk-monitoring-constructs
Project Structure
Your project directory should look like this. We'll create the lambda/processor directory for our Lambda function's code.
.
├── bin
│ └── cdk-cross-account-monitoring.ts
├── lib
│ └── workload-monitoring-stack.ts
├── lambda
│ └── processor
│ └── index.ts
├── package.json
└── tsconfig.json
...
Step 1: Create the Lambda Handler
This is the code for the Lambda function that will process SQS messages.
lambda/processor/index.ts
import { SQSEvent } from 'aws-lambda';
// A simple handler that processes messages from an SQS queue.
export const handler = async (event: SQSEvent): Promise<void> => {
console.log(`Processing ${event.Records.length} records...`);
for (const record of event.Records) {
console.log('Processing message:', record.messageId);
console.log('Message body:', record.body);
// To test error handling, uncomment the following line.
// Any message containing "error" in its body will fail and go to the DLQ.
// if (record.body.includes('error')) {
// throw new Error(`Simulating a processing error for message: ${record.messageId}`);
// }
// Simulate some work
await new Promise(resolve => setTimeout(resolve, 100));
}
console.log('Finished processing records.');
};
Step 2: Define the CDK Stack
This is the core of our solution. This stack will be deployed into your Workload Account (the one with the Lambda and SQS queue).
lib/workload-monitoring-stack.ts
import * as cdk from 'aws-cdk-lib';
import { Construct } from 'constructs';
import * as sqs from 'aws-cdk-lib/aws-sqs';
import * as lambda from 'aws-cdk-lib/aws-lambda';
import * as lambdaEventSources from 'aws-cdk-lib/aws-lambda-event-sources';
import * as iam from 'aws-cdk-lib/aws-iam';
import * as sns from 'aws-cdk-lib/aws-sns';
import {
MonitoringFacade,
SqsQueueMonitoring,
LambdaFunctionMonitoring,
} from 'aws-cdk-monitoring-constructs';
// --- IMPORTANT ---
// Replace these with your actual account IDs
const WORKLOAD_ACCOUNT_ID = '111111111111'; // The account where this stack is deployed
const MONITORING_ACCOUNT_ID = '222222222222'; // The account that needs access to the dashboard
const SNS_PUBLISHER_ACCOUNT_ID = '333333333333'; // The account where the SNS topic lives
export class WorkloadMonitoringStack extends cdk.Stack {
constructor(scope: Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);
// 1. Define the SQS Dead-Letter Queue (DLQ)
// This queue will store messages that fail processing.
const deadLetterQueue = new sqs.Queue(this, 'MySqsDlq', {
retentionPeriod: cdk.Duration.days(14),
});
// 2. Define the main SQS Queue
// It's configured to use the DLQ after 3 receive attempts.
const mainQueue = new sqs.Queue(this, 'MySqsQueue', {
visibilityTimeout: cdk.Duration.seconds(300),
deadLetterQueue: {
maxReceiveCount: 3,
queue: deadLetterQueue,
},
});
// 3. Define the Lambda Function to process queue messages
const processingLambda = new lambda.Function(this, 'SqsProcessorLambda', {
runtime: lambda.Runtime.NODEJS_18_X,
handler: 'index.handler',
code: lambda.Code.fromAsset('lambda/processor'),
timeout: cdk.Duration.minutes(1),
});
// 4. Grant the Lambda permission to consume messages from the queue
// and attach the queue as an event source.
processingLambda.addEventSource(new lambdaEventSources.SqsEventSource(mainQueue, {
batchSize: 10,
}));
// 5. Allow the SNS Topic from another account to publish to our SQS queue.
// NOTE: For this example, we find the topic by its ARN. In a real-world scenario,
// you would get this ARN from the team managing the other account.
const sourceTopic = sns.Topic.fromTopicArn(this, 'SourceSnsTopic', `arn:aws:sns:${this.region}:${SNS_PUBLISHER_ACCOUNT_ID}:your-source-topic-name`);
// The SQS queue needs a resource policy to accept messages from the SNS topic.
mainQueue.addToResourcePolicy(
new iam.PolicyStatement({
actions: ['sqs:SendMessage'],
resources: [mainQueue.queueArn],
principals: [new iam.ServicePrincipal('sns.amazonaws.com')],
conditions: {
ArnEquals: { 'aws:SourceArn': sourceTopic.topicArn },
},
})
);
// This step is crucial: In the SNS account, you must add a subscription
// pointing to this SQS queue's ARN.
// 6. Set up the monitoring using the 'aws-cdk-monitoring-constructs' library
const monitoringFacade = new MonitoringFacade(this, 'MonitoringFacade', {
alarmFactoryDefaults: {
// Human-readable names for alarms in the console
actionsEnabled: true,
alarmNamePrefix: 'MyWorkload',
},
});
// 7. Add monitoring for the Lambda Function
monitoringFacade.addMonitoring(new LambdaFunctionMonitoring({
lambdaFunction: processingLambda,
// Add a custom alarm for high error rates
addErrorRateAlarm: {
Warning: { maxErrorRate: 1 }, // 1% error rate is a warning
Critical: { maxErrorRate: 5 }, // 5% error rate is critical
},
}));
// 8. Add monitoring for the SQS Queues (main and DLQ)
monitoringFacade.addMonitoring(new SqsQueueMonitoring({
queue: mainQueue,
// This is a powerful feature: it automatically adds alarms for the DLQ
addDeadLetterQueueMonitoring: {
queue: deadLetterQueue,
maxMessageAgeInDays: 7, // Alarm if messages are stuck in DLQ for >7 days
maxMessageCount: 10, // Alarm if >10 messages are in the DLQ
},
}));
// 9. Create the IAM Role for Cross-Account Dashboard Access
// This is the role that the Monitoring Account will assume.
const crossAccountDashboardRole = new iam.Role(this, 'CrossAccountDashboardRole', {
// A descriptive name makes it easy to find in the console.
roleName: `CrossAccount-Dashboard-Role-${this.stackName}`,
// The Principal is the AWS account that is allowed to assume this role.
assumedBy: new iam.AccountPrincipal(MONITORING_ACCOUNT_ID),
});
// Grant the role read-only access to CloudWatch. This is all it needs.
crossAccountDashboardRole.addManagedPolicy(iam.ManagedPolicy.fromAwsManagedPolicyName('CloudWatchReadOnlyAccess'));
// --- CDK Outputs ---
// These outputs will be printed after you run `cdk deploy`. They are very useful!
new cdk.CfnOutput(this, 'DashboardUrl', {
value: `https://console.aws.amazon.com/cloudwatch/home?region=${this.region}#dashboards:name=${monitoringFacade.dashboard.dashboardName}`,
description: 'URL of the CloudWatch Dashboard in the Workload account',
});
new cdk.CfnOutput(this, 'CrossAccountRoleArn', {
value: crossAccountDashboardRole.roleArn,
description: 'ARN of the IAM role for the Monitoring account to assume',
});
}
}
Step 3: Configure the Main CDK App File
Update your bin file to instantiate the stack. Make sure to provide your account and region details.
bin/cdk-cross-account-monitoring.ts
#!/usr/bin/env node
import 'source-map-support/register';
import * as cdk from 'aws-cdk-lib';
import { WorkloadMonitoringStack } from '../lib/workload-monitoring-stack';
const app = new cdk.App();
// Deploy the stack to your WORKLOAD account.
new WorkloadMonitoringStack(app, 'WorkloadMonitoringStack', {
env: {
account: '111111111111', // <-- Replace with your WORKLOAD account ID
region: 'us-east-1' // <-- Replace with your target region
},
});
Step 4: Deploy the CDK Stack
Now, you are ready to deploy.
-
Bootstrap CDK (if you haven't already for this account/region):
cdk bootstrap aws://111111111111/us-east-1
-
Deploy the Stack:
cdk deploy
After the deployment finishes, look at the Outputs section in your terminal. You will see something like this:
Outputs:
WorkloadMonitoringStack.CrossAccountRoleArn = arn:aws:iam::111111111111:role/CrossAccount-Dashboard-Role-WorkloadMonitoringStack
WorkloadMonitoringStack.DashboardUrl = https://console.aws.amazon.com/cloudwatch/home?region=us-east-1#dashboards:name=WorkloadMonitoringStack-MonitoringFacade-Dashboard
Copy the CrossAccountRoleArn value. You will need it for the final step.
Step 5: Configure Cross-Account Access in the Monitoring Account
This is the final, manual step that you or an administrator of the Monitoring Account (222222222222) must perform.
-
Log in to the AWS Management Console as a user in the Monitoring Account.
-
Navigate to the CloudWatch service.
-
In the left-hand navigation pane, under Dashboards, you will see your list of dashboards. At the top of this pane, there is a dropdown menu. Click it and select View cross-account dashboards.
-
Click the Configure button.
-
In the configuration dialog:
- Under "Accounts", select Specific accounts.
- For Account ID, enter the ID of your Workload Account (111111111111).
- For IAM Role, paste the
CrossAccountRoleArn that you copied from the CDK deployment output.
- Click Add account.
-
Click Save.
Now, when you use the same dropdown menu from Step 3, you will see your Workload Account listed. Selecting it will allow you to see and interact with the dashboard that was created in that account, all from the comfort of your central Monitoring Account's console.