How to Use AWS Lambda Function URL For FREE

·

·

,

AWS Lambda Function URL is a new feature where you can have an HTTP(S) endpoint that is dedicated to your Lambda function. Lambda automatically generates a unique URL endpoint for you.

Function URL endpoints have the following format:

https://<url-id>.lambda-url.<region>.on.aws

Before this feature was launched, the only way to expose a Lambda function with an HTTP endpoint was to use the AWS API Gateway service.

However, now that we have AWS Function URLs, you will have direct URLs that can be used to call your Lambda functions directly. Pretty cool isn’t it?

AWS Lambda Function URLs Are Completely FREE!

One great feature is the pricing. Lambda Function URLs are completely “free”. You’ll only ever be paying for the invocation and memory time, like a normal Lambda. This is one advantage over API Gateway which costs to integrate.

However, that doesn’t mean they’re a direct replacement for API Gateway. Instead, API Gateway provides more advanced features such as the ability of JWT/custom authorizers, request-response validation and transformation, usage plans, direct built-in AWS firewall support and more.

AWS Lambda Function URLs Support IPv6 and HTTPS

Function URLs are dual stack-enabled, supporting IPv4 and IPv6. After you configure a function URL for your function, you can invoke your function through its HTTP(S) endpoint via a web browser, curl, Postman, or any HTTP client.

Lambda function URLs use resource-based policies for security and access control. Function URLs also support cross-origin resource sharing (CORS) configuration options.

You can apply function URLs to any function alias, or to the $LATEST unpublished function version. You can’t add a function URL to any other function version.

AWS Lambda Function URLs are Secure

You can use the AuthType parameter coupled with IAM policies attached to your function URLs, you can control who has access to the URLs.

Who is allowed to invoke or perform other administrative actions on your function URL? Specify one of the following AuthType options:

AWS_IAM: Lambda uses AWS Identity and Access Management (IAM) to authenticate and authorize requests. Choose this option if you want only authenticated IAM users and roles to invoke your function via the function URL.

NONE: Lambda doesn’t perform any authentication before invoking your function. Choose this option to allow public, unauthenticated access to your function URL.

How to Create an AWS Lambda Function URL Using AWS CLI

Prerequisites:

AWS CLI installed and configured.

1. Create a file containing the lambda function code.

First, let's create the code.

## Create your lambda function code
cat << EOF > index.js
exports.handler = async (event) => {
  let body = JSON.parse(event.body)
  const response = {
      statusCode: 200,
      body: "Hello " + body.name + ", Welcome to KloudVM.com",
  };
  return response;
};
EOF

2. Zip the function file.

Second, we will create the zip file so we can create the Lambda function.

## Create a zip file from index.js
zip function.zip index.js

3. Create the trust policy for the Lambda role.

## Create a trust policy definition for lambda to assume the IAM role
cat << EOF > assume_policy.json
{
  "Version": "2012-10-17",
  "Statement": [
      {
          "Effect": "Allow",
          "Principal": {
              "Service": "lambda.amazonaws.com"
          },
          "Action": "sts:AssumeRole"
      }
  ]
}
EOF

4. Create the IAM role which will be assumed by lambda.

## Create an IAM role that lambda can assume
aws iam create-role \
--role-name lambda-iam-role \
--assume-role-policy-document file://assume_policy.json

5. Create an IAM policy file for the IAM role.

## Get AWS account ID
AWS_ACCOUNT_ID=$(aws sts get-caller-identity | jq -r .Account) &&
echo $AWS_ACCOUNT_ID &&
ARN="arn:aws:logs:us-east-1:"$AWS_ACCOUNT_ID":log-group:/aws/lambda/hello:*"

## Create a policy for the lambda IAM role
cat << EOF > lambda_policy.json
{
  "Version": "2012-10-17",
  "Statement": [
      {
          "Effect": "Allow",
          "Action": "logs:CreateLogGroup",
          "Resource": "arn:aws:logs:us-east-1:$AWS_ACCOUNT_ID:*"
      },
      {
          "Effect": "Allow",
          "Action": [
              "logs:CreateLogStream",
              "logs:PutLogEvents"
          ],
          "Resource": [
              "$ARN"
          ]
      }
  ]
}
EOF

6. Create an IAM policy for the lambda role.

## Create an IAM policy
aws iam create-policy \
--policy-name lambda-iam-policy \
--policy-document file://lambda_policy.json

7. Attach the IAM policy to the lambda IAM role.

## Attach to the IAM lambda role
aws iam attach-role-policy \
--policy-arn arn:aws:iam::"$AWS_ACCOUNT_ID":policy/lambda-iam-policy \
--role-name lambda-iam-role

8. Create the lambda function.

## Create the lambda function
aws lambda create-function \
--function-name hello \
--runtime nodejs14.x \
--zip-file fileb://function.zip \
--handler index.handler \
--role arn:aws:iam::"$AWS_ACCOUNT_ID":role/lambda-iam-role

9. Create the Lambda function URL.

## Create lambda function URL using AWS CLI
aws lambda create-function-url-config \
--function-name hello \
--auth-type NONE

Warning: We have defined “auth-type” as “NONE”, which allows anyone (public) who knows the endpoint URL to trigger the lambda function using the endpoint.

10. Get the lambda function URL endpoint.

## Get lambda function URL
URL=$(aws lambda get-function-url-config \
--function-name hello | jq -r .FunctionUrl)

We have successfully created the AWS Lambda URL public endpoint.

AWS Lambda function URL with example

Next, let us test the endpoint and check if the lambda function gets executed and returns the expected data.

11. Test lambda function URL public endpoint.

## Test your lambda function
curl --silent \
--request POST \
--header 'Content-Type: application/json' \
--data '{"name": "kloudvm"}' \
$URL

## Should return
## Hello kloudvm, Welcome to KloudVM.com

How to Create an AWS Lambda Function URL Using AWS Console

1. Create the lambda IAM policy.

Use the below JSON to create the IAM policy. Don’t forget to replace the REGION and ACCOUNT variables with yours.

Name the policy “lambda-iam-policy”.

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "logs:CreateLogGroup",
            "Resource": [
                "arn:aws:logs:REGION:ACCOUNT:*"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "logs:CreateLogStream",
                "logs:PutLogEvents"
            ],
            "Resource": "arn:aws:logs:REGION:ACCOUNT:log-group:/aws/lambda/hello:*"
        }
    ]
}


2. Create the lambda IAM role and attach the policy.

create-lambda-role

Secondly, choose the IAM policy that we have created earlier.

lambda-iam-policy-attach

create-lambda-role-2

3. Create the Lambda function

create-lambda-function

We will use the test function that AWS have created for us.

create-lambda-function-2

4. Create the Lambda Function URL

create-lambda-function-url create-lambda-function-url-2 lambda-function-url-3

5. Test the new URL.

You should get the below output!

lambda-function-url-result

Final Thoughts

In conclusion, function URLs are a long overdue feature of AWS Lambda.

Moreover, it feels like with every passing day, AWS is recognising many of the common workflows us developers run through during our workday, and building features to streamline or greatly simplify the process.

And finally, if you liked this tutorial, why not learn more about Lambda. I have created another article here. Check it out!

To get more details in AWS Lambda, please refer to the documentation.



Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.