Borislav Hadzhiev
Thu Apr 14 2022·2 min read
Photo by Drew Coffman
Updated - Thu Apr 14 2022
In order 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 snippet.
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
routeIf 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: