To create an AWS CDK script that deploys an SQS queue and a Lambda function associated with it, you'll need to follow these steps. This example assumes you have Node.js and the AWS CDK installed, and you're familiar with the basics of AWS services like SQS and Lambda.
First, ensure you have the AWS CDK installed globally:
npm install -g aws-cdk
Next, create a new directory for your project and initialize a new CDK app:
mkdir my-cdk-app
cd my-cdk-app
cdk init app --language=typescript
Replace typescript with javascript if you prefer to use JavaScript.
Now, let's create the CDK script. Open the lib/constructors.ts file and replace its content with the following code:
import * as cdk from '@aws-cdk/core';
import * as sqs from '@aws-cdk/aws-sqs';
import * as lambda from '@aws-cdk/aws-lambda';
import * as iam from '@aws-cdk/aws-iam';
export class MyCdkApp extends cdk.Stack {
constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);
// Create an SQS queue
const queue = new sqs.Queue(this, 'MyQueue', {
queueName: 'MyQueue',
});
// Create a Lambda function
const lambdaFunction = new lambda.Function(this, 'MyLambdaFunction', {
runtime: lambda.Runtime.NODEJS_14_X,
code: lambda.Code.fromAsset('lambda'), // Assuming your Lambda code is in the 'lambda' directory
handler: 'index.handler', // The file and method to execute in your Lambda
environment: {
QUEUE_URL: queue.queueUrl, // Pass the SQS queue URL to the Lambda function
},
role: new iam.Role(this, 'LambdaExecutionRole', {
assumedBy: new iam.ServicePrincipal('lambda.amazonaws.com'),
managedPolicies: [
iam.ManagedPolicy.fromAwsManagedPolicies('service-role/AWSLambdaBasicExecutionRole'),
],
}),
});
// Associate the Lambda function with the SQS queue
queue.addPermission(new iam.PolicyStatement({
action: 'lambda:InvokeFunction',
principal: new iam.ServicePrincipal('lambda.amazonaws.com'),
resource: lambdaFunction.addEventSourceAccessPolicy(),
}));
lambdaFunction.addEventSource(queue);
}
}
This script creates an SQS queue named "MyQueue" and a Lambda function named "MyLambdaFunction". The Lambda function is associated with the SQS queue, allowing it to process messages from the queue.
Before deploying the stack, make sure you have a Lambda function code in the lambda directory. Here's a simple example of a Lambda function that logs the received message:
lambda/index.js:
exports.handler = async (event) => {
console.log('Received message:', JSON.stringify(event, null, 2));
};
Now, deploy your CDK app:
cdk deploy
This command will create the SQS queue, Lambda function, and the necessary permissions to associate them.
Remember to replace the placeholders and adjust the code according to your specific requirements.