Import an Existing Lambda Function in AWS CDK


Borislav Hadzhiev

Sun May 02 20212 min read


Photo by Drew Coffman

Importing an Existing Lambda Function in AWS CDK #

In order to import an existing lambda function in CDK, we have to use the static fromFunctionArn method on the Function class.

The code for this article is available on GitHub

Let's look at a simple example where we import a lambda function and use it in an API Gateway resource:

import * as apigateway from '@aws-cdk/aws-apigateway'; import * as lambda from '@aws-cdk/aws-lambda'; import * as cdk from '@aws-cdk/core'; export class CdkStarterStack extends cdk.Stack { constructor(scope: cdk.App, id: string, props?: cdk.StackProps) { super(scope, id, props); // ๐Ÿ‘‡ import existing Lambda by ARN const importedLambdaFromArn = lambda.Function.fromFunctionArn( this, 'external-lambda-from-arn', `arn:aws:lambda:${cdk.Stack.of(this).region}:${ cdk.Stack.of(this).account }:function:YOUR_FUNCTION_NAME`, ); console.log('functionArn ๐Ÿ‘‰', importedLambdaFromArn.functionArn); console.log('functionName ๐Ÿ‘‰', importedLambdaFromArn.functionName); // ๐Ÿ‘‡ create API const api = new apigateway.RestApi(this, 'api'); // ๐Ÿ‘‡ add a /test route on the API const test = api.root.addResource('test'); // ๐Ÿ‘‡ integrate imported Lambda at GET /test on the API test.addMethod( 'GET', new apigateway.LambdaIntegration(importedLambdaFromArn), ); } }

Let's go over what we did in the code snippet.

  1. we imported an existing lambda function in our CDK stack, using the static fromFunctionArn method. The method takes 3 parameters:
    • scope - the construct scope
    • id - an identifier for the resource, must be unique within the scope
    • functionArn - the ARN of the function we want to import
  2. we created an API Gateway and integrated the imported lambda function to serve requests for http GET at the /test route
The function ARN can be passed to the CDK stack as a secret from secrets manager, environment variable, CDK context, or a parameter.

If the function you're trying to import is in the same environment (account and region) as the CDK stack, you can use the stack values to create most of the function ARN, all you need to add is the function name.


If I deploy the CDK stack with the npx cdk deploy command, I can see that the imported Lambda has been integrated with the API at the /test route:

imported lambda integrated

Further Reading #

Add me on LinkedIn

I'm a Web Developer with TypeScript, React.js, Node.js and AWS experience.

Let's connect on LinkedIn

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee