I am migrating my lambda applications from serverless framework to CDK. I am fairly new to CDK and wondering if I am missing something here. I have my lambda code in ./lambda/hello.js. I am trying to deploy this to lambda. In my previous successful deployments I have directly used Code.fromAsset which was uploading the zip file to a random S3 bucket created by CDK. I am now trying to upload this to a custom bucket which already exists. In serverless, I used to just mention this bucket name and my zip files used to get upload there and lambda deployment happened from that file.
import * as cdk from 'aws-cdk-lib';
import { CfnSchedule } from 'aws-cdk-lib/aws-scheduler';
import {
Effect, PolicyStatement, Role, ServicePrincipal,
} from 'aws-cdk-lib/aws-iam';
import { Construct } from 'constructs';
import * as fs from 'fs';
import * as dotenv from 'dotenv';
import * as lambda from 'aws-cdk-lib/aws-lambda';
import * as sqs from 'aws-cdk-lib/aws-sqs';
import * as s3 from 'aws-cdk-lib/aws-s3';
import * as lambdaEventSources from 'aws-cdk-lib/aws-lambda-event-sources';
import * as s3Deploy from 'aws-cdk-lib/aws-s3-deployment';
import { convertDayOfWeekToCron } from '../utils/convertDay';
// Determine which environment to use based on NODE_ENV, default to 'development'
const environment = process.env.NODE_ENV || 'dev';
// Load environment variables from the appropriate .env file
dotenv.config({ path: `.env.${environment}` });
export class AwsCdkEventsStack extends cdk.Stack {
constructor(scope: Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);
const lambdaBucket = s3.Bucket.fromBucketName(this, 'LambdaBucket', process.env.S3_BUCKET || '');
const lambdaCodeAsset = new s3Deploy.BucketDeployment(this, 'LambdaCodeAssetDeployment', {
sources: [s3Deploy.Source.asset('./lambda')],
destinationBucket: lambdaBucket,
destinationKeyPrefix: 'scheduler-service',
exclude: ['**/*.ts'],
});
// Define the Lambda function resource
const helloWorldFunction = new lambda.Function(this, 'HelloWorldFunction', {
runtime: lambda.Runtime.NODEJS_20_X,
code: lambda.Code.fromBucket(
lambdaBucket,
'serverless/hello.zip',
),
handler: 'hello.handler',
environment: {
STAGE: process.env.NODE_ENV || 'dev',
},
});
const queueArn: string = process.env.SQS_ARN || '';
const queue = sqs.Queue.fromQueueArn(this, 'ImportQueue', queueArn);
queue.grantConsumeMessages(helloWorldFunction);
helloWorldFunction.addEventSource(new lambdaEventSources.SqsEventSource(queue));
}
}
Is such automated upload mechanism missing in CDK? What would be the recommended way of doing this? Please give me some pointers