3

I've created a lambda function called add in my aws environment, I am trying to build a cdk application that would generate a new API Gateway and then invoke add.

I am following the tutorial on https://cdkworkshop.com/20-typescript/30-hello-cdk/300-apigw.html and I noticed all the examples I came across online seem to write their code in a similar form to following:

   const hello = new lambda.Function(this, 'HelloHandler', {
      runtime: lambda.Runtime.NODEJS_10_X,    // execution environment
      code: lambda.Code.fromAsset('lambda'),  // code loaded from "lambda" directory
      handler: 'hello.handler'                // file is "hello", function is "handler"
    });
    const api = new apiGateWay.LambdaRestApi(this, 'api', {
      handler: hello
    })

Above example directly creates a new lambda function name with HelloHanlder in it. I want to reference my previously created function add, and not add any new lambda function to the stack, something along the lines of:

    const api = new apiGateWay.LambdaRestApi(this, 'api', {
      handler: "add"
    })

Is this possible to fix?

夢のの夢
  • 5,054
  • 7
  • 33
  • 63
  • how did you create the lambda function `add`? did you do it manually or you used cloudformation or another cdk stack? – Balu Vyamajala Jan 13 '21 at 03:28
  • I manually created it first, so then I tried creating another cdk app with only lambda in it -- I can reference lambda source code by doing this. But doing this ends up creating a new function and not referencing `add`. Sorry I am entirely new to this so I might've mixed up terms. – 夢のの夢 Jan 13 '21 at 03:41
  • 1
    you can import an existing aws resource into cdk, https://stackoverflow.com/questions/61825766/step-functions-task-for-existing-lambda-in-cdk – Thanh Nguyen Van Jan 13 '21 at 03:50

1 Answers1

10

Option 1: Using existing Lambda from function Arn

const hello = lambda.Function.fromFunctionArn(
  this,
  "hello-lambda",
  "arn:aws:lambda:us-east-1:111222233333:function:hello-lambda"
);
new apigw.LambdaRestApi(this, "Endpoint", {
  handler: hello,
});

Option 2: You can import existing lambda into a new CloudFormation stack and export the Arn and import into CDK

Balu Vyamajala
  • 9,287
  • 1
  • 20
  • 42