AWS CDK: Deploy AWS Lambda function

February 3rd, 2020 139 Words

AWS Lambda functions are great. Using the AWS Cloud Development Kit in TypeScript, you can easily deploy files to AWS Lambda functions and configure an AWS Lambda Layer in the same CloudFormation Stack. After the deployment is done, the AWS Lambda function name to invoke the uploaded sources will be exposed as a CloudFormation Stack Output.

import path from "path";

import * as CDK from "@aws-cdk/core";
import * as Lambda from "@aws-cdk/aws-lambda";

const filesLambda = path.resolve(__dirname, "lambda");
const filesLayer = path.resolve(__dirname, "layer");

export class LambdaStack extends CDK.Stack {
  constructor(app: CDK.App, id: string, props?: CDK.StackProps) {
    super(app, id, props);

    const layer = new LayerVersion(this, "Layer", {
      compatibleRuntimes: [Runtime.NODEJS_12_X],
      code: Code.fromAsset(filesLayer),
    });

    const lambda = new Lambda.Function(this, "Function", {
      code: Lambda.Code.fromAsset(filesLambda),
      handler: "index.run",
      runtime: Lambda.Runtime.NODEJS_12_X,
      memorySize: 1024,
      timeout: CDK.Duration.seconds(3),
      layers: [layer],
    });

    new CDK.CfnOutput(this, "FunctionName", {
      value: lambda.functionName,
    });
  }
}