Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AWS CDK application how to "reference" already created aws lambda function (without creating a new one in a stack)?

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?

like image 550
夢のの夢 Avatar asked Sep 01 '26 03:09

夢のの夢


1 Answers

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

  • Example of import a DynamoDb, Lambda is no different
  • Exporting Arn as stack output
  • Importing stack into CDK and using it.
like image 106
Balu Vyamajala Avatar answered Sep 03 '26 11:09

Balu Vyamajala



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!