Skip to content

How to reference an existing Lambda FunctionUrl within CDK stack.

0

I am trying to deploy a distribution with the CDK. I want this distribution to be able to call an existing lambda function url which is setup with AWS_AIM authentication. I also have an existing AOC I want to reference. I am able to load the existing function but I cannot figure out how to reference the existing URL. I can call existingFunction.add_function_url but this fails since the function is already configured in a different stack. How can I setup this origin?

existing_lambda: lambda_.IFunction = lambda_.Function.from_function_arn( self, "ExistingLambda", existing_lambda_arn ) origins.FunctionUrlOrigin( <need IFunctionUrl reference to existing url>, origin_access_control_id="MY_AOC", ),

2 Answers
1

To reference an existing Lambda Function URL within your CDK stack, you need to use a different approach than creating a new URL with add_function_url(). Since the Function URL already exists in another stack, you'll need to reference it directly.

Here's how you can set up your CloudFront distribution with an existing Lambda Function URL:

# Import the existing Lambda function
existing_lambda = lambda_.Function.from_function_arn(
self, "ExistingLambda", existing_lambda_arn
)

# Reference the existing Function URL
function_url = lambda_.FunctionUrl.from_function_url_attributes(
self, "ExistingFunctionUrl",
function_name=existing_lambda.function_name,
url="https://your-existing-function-url.lambda-url.region.on.aws"  # Replace with actual URL
)

# Reference your existing OAC
oac = cloudfront.FunctionUrlOriginAccessControl.from_origin_access_control_id(
self, "ExistingOAC", 
origin_access_control_id="MY_AOC"
)

# Create the distribution with the function URL origin
distribution = cloudfront.Distribution(
self, "MyDistribution",
default_behavior=cloudfront.BehaviorOptions(
origin=origins.FunctionUrlOrigin.with_origin_access_control(
function_url,
origin_access_control=oac
)
)
)

This approach allows you to reference the existing Function URL by its attributes rather than trying to create a new one. You'll need to know the actual URL of your existing Function URL endpoint to use this method.

If you don't have the URL readily available, you can retrieve it using AWS CLI, SDK, or from the AWS Console before deploying your CDK stack.
Sources
class FunctionUrlOrigin · AWS CDK
interface FunctionUrlOriginWithOACProps · AWS CDK
class FunctionUrl (construct) · AWS CDK
aws-cdk-lib.aws_cloudfront_origins module · AWS CDK

answered a year ago
EXPERT
reviewed a year ago
0

Sadly, lambda_.FunctionUrl.from_function_url_attributes does not exist

answered a year ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.