Import an Existing Lambda Function in AWS CDK

avatar
Borislav Hadzhiev

Last updated: Jan 26, 2024
2 min

banner

# Importing an Existing Lambda Function in AWS CDK

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.

lib/cdk-starter-stack.ts
import * as apigateway from 'aws-cdk-lib/aws-apigateway'; import * as lambda from 'aws-cdk-lib/aws-lambda'; import * as cdk from 'aws-cdk-lib'; 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 sample.

  1. We imported an existing lambda function in our CDK stack by 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.

lambda-arn-format
arn:aws:lambda:LAMBDA_REGION:LAMBDA_ACCOUNT:function:LAMBDA_NAME

If I deploy the CDK stack with the npx aws-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

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev