Search code examples
amazon-web-servicesaws-lambdaaws-cdkaws-codepipelineaws-sam-cli

I want to dubug lambda, but cdk synth does not include Lambda Resource, when it is deployed by pipeline stack


I am struggling to debug lambdas managed by CDK.

My CDK source is almost same to the sample below provided by AWS.

https://github.com/aws-samples/cdk-pipelines-demo/tree/typescript

The source structure is as follows:

--project_dir/
   |_cdk.json
   |_pipelines_webinar/
       |_lambda/
          |_handler.ts    <====== I WANT TO EXECUTE AND DEBUG ON LOCAL THIS.
   |_pipeline_stack.ts
   |_pipelines_webinar_stack.ts
   |_webservice_stage.ts

I think that it needs to use SAM CLI to run and debug locally.

But, If I run cdk synth to create SAM Template, Lambda function (Type: AWS::Lambda::Function) does not exist in the created SAM Template.

I think this behavior is because lambda is deployed by CDK pipeline.

Here's how to reproduce the situation:

git clone -b typescript https://github.com/aws-samples/cdk-pipelines-demo.git
cd cdk-pipelines-demo
npm install
cdk synth > template.yml

Q. Is there any way to run and debug lambda locally in this situation?


Solution

  • In the example you gave, the lambda function is instantiated in a stack which is deployed under the WebServiceStage pipeline stage. For pipeline stages cdk synth bundles the function in a JSON file inside cdk.out/ and includes a reference to this template as part of template.yml. The lambda is passed in as an artifact, which means that it won't be written to template.yml directly.

    A workaround would be to create a new file lambda-app.ts that instantiates the PipelinesWebinar Stack

    #!/usr/bin/env node
    import 'source-map-support/register';
    import { App } from '@aws-cdk/core';
    import { PipelinesWebinarStack } from './pipelines_webinar/pipelines_webinar_stack';
    
    const app = new App();
    
    new PipelinesWebinarStack(app, 'PipelineStack');
    
    app.synth();
    

    Then compile that with tsc, and make cdk synth use that file with:-

    cdk synth --app lambda-app.js --no-staging > template.yml
    

    Then you should be able to find the logical ID in template.yml and run

    sam invoke local <logicalId>
    

    to run it locally