Last updated: Jan 26, 2024
Reading timeยท2 min

To import an existing Lambda function in CDK, we have to use the static fromFunctionArn method on the Function class.
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-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.
fromFunctionArn method. The method takes 3 parameters:scope - the construct scopeid - an identifier for the resource (must be
unique within the scope)functionArn - the ARN of the function we want to
import/test routeThe 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.
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.
