Below is an example AWS CDK script written in TypeScript that creates an Amazon SQS queue and an AWS Lambda function. The Lambda function is configured to be triggered by messages arriving in the SQS queue. This example assumes you have the AWS CDK installed and configured on your machine.
First, ensure you have the necessary dependencies installed in your CDK project. If you're starting from scratch, you can initialize a new CDK project with TypeScript by running:
cdk init app --language typescript
Then, install the necessary constructs if you haven't already:
npm install @aws-cdk/aws-sqs @aws-cdk/aws-lambda @aws-cdk/aws-iam @aws-cdk/aws-lambda-event-sources
Now, here's the example CDK script (lib/sqs_lambda_stack.ts if you used the cdk init command):
import * as cdk from 'aws-cdk-lib';
import * as sqs from 'aws-cdk-lib/aws-sqs';
import * as lambda from 'aws-cdk-lib/aws-lambda';
import * as iam from 'aws-cdk-lib/aws-iam';
import * as lambdaEventSources from 'aws-cdk-lib/aws-lambda-event-sources';
export class SqsLambdaStack extends cdk.Stack {
constructor(scope: cdk.App, id: string, props?: cdk.StackProps) {
super(scope, id, props);
// Create an SQS Queue with a 5-minute visibility timeout
const queue = new sqs.Queue(this, 'MyQueue', {
visibilityTimeout: cdk.Duration.seconds(300), // 5 minutes
});
// Define the Lambda function with error handling
const lambdaFunction = new lambda.Function(this, 'MyFunction', {
functionName: 'MyLambdaFunction',
runtime: lambda.Runtime.NODEJS_16_X, // Change to your preferred runtime
handler: process.env.LAMBDA_HANDLER || 'index.handler', // Use environment variable for handler
code: lambda.Code.fromAsset('lambda'), // Directory containing your Lambda code
// Add error handling for unprocessed items
deadLetterQueue: {
maxReceiveCount: 3, // Adjust based on your retry policy
queue: new sqs.Queue(this, 'DeadLetterQueue'), // DLQ for failed messages
},
});
// Grant Lambda execution role permission to consume from SQS
queue.grantConsumeMessages(lambdaFunction);
// Add SQS as an event source for the Lambda Function
lambdaFunction.addEventSource(
new lambdaEventSources.SqsEventSource(queue, {
batchSize: 10, // Optional: adjust batching to your needs
})
);
}
}
Important Notes:
-
Lambda Code Location: This example assumes your Lambda function code is located in a directory named lambda relative to your CDK project's root. Ensure you replace 'lambda' with the correct path to your Lambda function code. Your Lambda code directory should contain at least an index.js (or index.ts if you're using TypeScript for the Lambda as well) with an exported handler function.
-
Runtime and Handler: Adjust the runtime and handler properties in the lambda.Function constructor to match your Lambda function's requirements. The handler is set using an environment variable for flexibility.
-
Permissions: This script grants the Lambda function's execution role the necessary permissions to consume messages from the SQS queue. Be cautious with permissions in production environments, ensuring the principle of least privilege.
-
Error Handling: A dead-letter queue (DLQ) is configured for the Lambda function to handle messages that fail processing. This prevents message loss and allows for easier debugging.
-
Testing: Before deploying to production, test your setup thoroughly. You can use the AWS CLI or SDKs to send test messages to the SQS queue and verify the Lambda function is triggered as expected.
Deploy Your Stack:
- Synthesize your template by running
cdk synth (optional but useful for verifying the CloudFormation template).
- Deploy your stack to AWS by running
cdk deploy.
Remember to cleanup when you're done experimenting to avoid incurring unintended charges:
cdk destroy