Create Lambda Function URL using AWS CDK
Deploying Lambda Function URLs with the AWS CDK is simple.
How to deploy Function URLs using AWS Python CDK
Follow the instructions below to deploy an AWS Lambda Function with a URL.
Create a requirements.txt
For this tutorial, version 2.106.1 of the AWS CDK was used.
1aws-cdk-lib==2.106.1
2constructs>=10.0.0,<11.0.0
Install the dependencies
1pip3 install -r requirements.txt
Create /handler folder with an index.py file
1def handler(event, context):
2 return {
3 "statusCode": 200,
4 "body": {"message": "๐"}
5 }
Create stack.py with a basic lambda function
1from os import path
2
3import aws_cdk as cdk
4import aws_cdk.aws_lambda as lambda_
5
6
7class FunctionUrlStack(cdk.Stack):
8 def __init__(self, scope: cdk.App, construct_id: str, **kwargs) -> None:
9 super().__init__(scope, construct_id, **kwargs)
10
11 lambda_function = lambda_.Function(
12 self,
13 "Function",
14 runtime=lambda_.Runtime.PYTHON_3_11,
15 handler="index.handler",
16 code=lambda_.Code.from_asset(path.join(path.dirname(__file__), "handler")),
17 )
18
19 function_url = lambda_function.add_function_url(
20 auth_type=lambda_.FunctionUrlAuthType.NONE
21 )
22
23 cdk.CfnOutput(self, "FunctionUrl", value=function_url.url)
Create app.py
1import aws_cdk as cdk
2
3from stack import FunctionUrlStack
4
5app = cdk.App()
6FunctionUrlStack(app, "FunctionUrlStack")
7
8app.synth()
Create cdk.json
1{
2 "app": "python3 app.py"
3}
The directory structure should look like this:
1project/
2โโโ app.py
3โโโ cdk.json
4โโโ handler
5โย ย โโโ index.py
6โโโ requirements.txt
7โโโ stack.py
Deploy the stack
1cdk deploy
Because of the CfnOutput
, the distribution’s domain name is in an output:
1Outputs:
2FunctionUrlStack.FunctionUrl = https://<url>.lambda-url.us-east-1.on.aws/
The link will display the following text:
1{
2 "message": "๐"
3}