Using AWS Lambda with Amazon VPC Lattice - AWS Lambda

Using AWS Lambda with Amazon VPC Lattice

You can register your Lambda functions as targets within an Amazon VPC Lattice service network. By doing this, your Lambda function becomes a service within the network, and clients that have access to the VPC Lattice service network can call your service. If your Lambda function needs to access services within a service network, you can connect your function to a VPC that's already associated with the service network. Having your services live within a VPC Lattice network can help you more easily discover, connect, access, and monitor them.

VPC Lattice concepts

Throughout this guide, we'll frequently refer to the following VPC Lattice terms:

  • Service – A service is any software application that can run on an instance, container, or within a serverless function. This topic focuses only on services built using Lambda functions.

  • Service network – A service network is a logical boundary containing a network of services. This topic covers how to configure your Lambda functions as services within a VPC Lattice service network.

  • Target group – A target group is a collection of compute type destinations that run a service. Target groups for Lambda can contain only one Lambda function as the target. You cannot have a target group with multiple functions as targets.

  • Listener – A listener is a process that receives traffic and routes it to different target groups within the service network.

  • Listener rule – A listener rule encompasses the priority, actions, and conditions that a listener uses to determine where to route traffic. Each listener has a default listener rule, and a listener can have multiple listener rules. A listener rule can contain the following:

    • Protocol – The protocol that the listener uses to send the request to the destination. Can be either HTTP or HTTPS.

    • Port – The port that the listener polls for incoming requests. Can be between 1 and 65535 inclusive.

    • Path – The path to the target resource. For the default listener rule, path is the default path of /. A listener rule can have 6 paths at maximum, including the default path.

    • Priority – A listener uses the priority of a path to determine which path to route traffic to. A lower number denotes higher priority. The default path has the lowest priority. If you add a new path, VPC Lattice assigns it at the second lowest priority by default. This is just above the priority of the default path, but at a lower priority than all other non-default paths.

In addition, we'll refer to the following AWS Identity and Access Management (IAM) entities:

  • Network owner – The network owner is the IAM role that owns the VPC Lattice service network.

  • Service owner – The service owner is the IAM role that owns the service built using a Lambda function. The service owner and the network owner do not have to be the same entity.

Using Lambda with VPC Lattice and VPC-enabled functions

By default, Lambda functions cannot access any private resources in a VPC. When you configure a Lambda function to connect to private subnets in a VPC, you're allowing the VPC-enabled function to access resources within that VPC. In other words, you're only focusing on the scope of a single VPC.

Lambda functions registered as services in a VPC Lattice network are not the same as VPC-enabled functions, but they can be complementary to each other. When you register a Lambda function as a service in a VPC Lattice network, you're creating an ingress path to your function from one or more VPCs. Additionally, your function may have an optional egress path to another VPC.

When registering a Lambda function as a service, you're focusing on the ingress scenario. This encompasses the specific listener rule configurations that listeners use to route traffic to your service. From there, your Lambda function may communicate with other AWS services within your VPC through a Hyperplane ENI (elastic network interface). The following diagram illustrates this, where the Lambda function is a service within the VPC Lattice network.


          An architecture diagram showing how different components of a VPC Lattice service network
            interact, focusing on the Lambda function as a registered service.

Prerequisites and permissions

This topic assumes that you have both a VPC Lattice service network and a Lambda function. If you don't already have a VPC Lattice service network, refer to the VPC Lattice user guide to create one.

When you register your Lambda function as a target via the Lambda console or AWS Command Line Interface (AWS CLI), Lambda automatically adds the necessary permissions for you.

For Lambda to automatically add permissions for you, so that you can successfully create a Lambda function as a target of a Lambda service, your role must have the following IAM permissions:

  • AddPermission

  • CreateListener

  • CreateService

  • CreateServiceNetworkServiceAssociation

  • CreateTargetGroup

  • ListServiceNetworks (required for console workflow only)

  • RegisterTargets

To update an existing service in a VPC Lattice network to point to a Lambda function, your role must have the following IAM permissions:

  • CreateService

  • ListListeners (required for console workflow only)

  • ListServices (required for console workflow only)

  • RegisterTargets

You can also manually add the permission using the following AWS CLI command:

aws lambda add-permission --function-name my-function \ --action lambda:InvokeFunction \ --statement-id allow-vpc-lattice \ --principal vpc-lattice.amazonaws.com --source-arn target-group-arn

Limitations

When using Lambda functions with VPC Lattice networks, keep in mind the following limitations:

  • The Lambda function and the target group must be in the same account and in the same Region.

  • The maximum size of the request body that you can forward to a service created using a Lambda function is 6 MB.

  • The maximum size of the response JSON that the Lambda function can return is 6 MB.

  • You an choose HTTP and HTTPS protocols only.

Registering your Lambda function with a VPC Lattice network

You can register any existing Lambda function with a VPC Lattice network using the AWS console or AWS CLI. After registering the function as a service, it can immediately start receiving requests.

To register a Lambda function with a VPC Lattice network (console)
  1. Open the Function page of the Lambda console.

  2. Choose the name of the function you want to register.

  3. Under Function overview, choose Add trigger.

  4. In the dropdown menu, select VPC Lattice Application Network.

  5. For Intent, choose Create new.

  6. For Service name, enter a name for your service.

  7. For VPC Lattice network, select the service network that you want to associate this Lambda function with. You can also enter the full Amazon Resource Name (ARN) of the service network. If you don't have an existing service network, you can choose the link in the description, which takes you to the Amazon VPC console where you can create a VPC Lattice network.

    Note

    You don't need to select a VPC Lattice network to finish setting up the trigger. However, if you create the trigger without selecting a network, clients cannot access your service until you associate it with a VPC Lattice network.

  8. For Listener, configure the following settings:

    • Listener name – Enter a name for your listener

    • Protocol – The protocol that the listener uses to send the request to the destination. Can be either HTTP or HTTPS.

    • Port – The port that the listener polls for incoming requests. Can be between 1 and 65535 inclusive.

    • Choose Add Listener. VPC Lattice will create a default routing with the default path /. After service creation, you cannot change its name, protocol, and port settings, but you can still define new routing paths.

  9. Choose Add.

To register a Lambda function with a VPC Lattice network (AWS CLI)
  1. Create a service using the create-service command. Note down the service's ARN in the response. You'll need it in the next steps.

    aws vpc-lattice create-service --name my-vpc-lattice-service
  2. Create a target group using the create-target-group command. Note down the target group's ARN in the response. You'll need it in the next steps.

    aws vpc-lattice create-target-group \ --name my-vpc-lattice-target-group \ --type LAMBDA
    Note

    By default, this command creates a target group that sends events with the V1 event structure to your Lambda function. To send a V2 event structure that's compatible with Amazon API Gateway, specify the LambdaEventStructureVersion option. For example, append --lambda-event-structure-version V2 to the end of the previous command.

  3. Create a listener within the service network using the create-listener command. New listeners automatically use the default path of /. Replace the value of the service parameter with your service's ARN from step 1. Replace the value of TargetGroupArn in the default-action parameter with your target group ARN from step 2.

    aws vpc-lattice create-listener \ --name https --service-identifier svc-0e2f2665e1cebb720 \ --protocol HTTPS \ --default-action forward='{targetGroups={targetGroupIdentifier=tg-0e2f2665e1cebb720}}'
  4. Register your Lambda function as a target using the register-targets command. Replace the value of the target-group-arn parameter with your target group ARN from step 2. Replace the value of Id in the targets parameter with the ARN of your Lambda function.

    aws vpc-lattice register-targets \ --target-group-identifier arn:aws:vpc-lattice:us-west-2:123456789012:targetgroup/tg-0e2f2665e1cebb720 \ --targets id=arn:aws:lambda:us-west-2:123456789012:function:my-function
    Note

    In the previous register-targets command, if your Lambda function doesn't already explicitly allow VPC Lattice to invoke it, VPC Lattice attaches the necessary permissions to your function's execution role automatically. To allow VPC Lattice to automatically attach permissions, your role needs to have the AddPermission permission.

  5. Associate the service with the service network using the create-service-network-service-association command. Replace the value of the service parameter with your service ARN from step 1. Replace the value of the service-network parameter with the ARN of your VPC Lattice service network.

    aws vpc-lattice create-service-network-service-association \ --service-identifier arn:aws:vpc-lattice:us-west-2:123456789012:service/svc-0b9b89d907bc8668c \ --service-network-identifier arn:aws:vpc-lattice:us-west-2:123456789012:servicenetwork/03d622a31e5154247

Updating the target of a service in a VPC Lattice network

You can update any existing service within a VPC Lattice network to point to a Lambda function target. You can do this by adding a new routing path using the AWS console or AWS CLI. When you add a new path, VPC Lattice assigns that path the second lowest priority, just above the default path (lowest priority).

To update the target of a service to point to a Lambda function (console)
  1. Open the Function page of the Lambda console.

  2. Choose the name of the function you want to register.

  3. Under Function overview, choose Add trigger.

  4. In the dropdown menu, select VPC Lattice Application Network.

  5. For Intent, choose Select existing.

  6. For Service name, choose an existing service.

  7. For Listener, choose an existing listener.

  8. For Rule name, enter a name for the new rule.

  9. For Path, define a new routing path for the listener.

  10. Choose Add.

For the following steps, you'll need the ARN of your service, as well as the ARN of the listener that you want to add a new rule for.

  1. Create a new target group using the create-target-group command. Note down the target group's ARN in the response, as you'll need it for future steps.

    aws vpc-lattice create-target-group \ --name my-vpc-lattice-target-group \ --type LAMBDA
  2. Create a new rule for your existing listener using the create-rule command. This command assumes that your conditions are in a file called conditions-pattern.json in your current directory. Replace the value of the listener-arn parameter with the ARN of your listener. Replace the value of TargetGroupArn in the actions parameter with your target group ARN from step 1.

    aws vpc-lattice create-rule \ --name my-rule --priority 1 \ --listener-identifier listener-0e9af499f72e5251b \ --service-identifier svc-01755f67d3a427803 --match httpMatch='{pathMatch={match={prefix="/test"}}}' --default action forward='{targetGroups=[{targetGroupIdentifier=tg-042d5b70f1e743940}]}'
  3. Register your Lambda function as a target using the register-targets command. Replace the value of the target-group-arn parameter with your target group ARN from step 2. Replace the value of Id in the targets parameter with the ARN of your Lambda function.

    aws vpc-lattice register-targets \ --target-group-identifier arn:aws:vpc-lattice:us-west-2:123456789012:targetgroup/tg-0e2f2665e1cebb720 \ --targets id=arn:aws:lambda:us-west-2:123456789012:function:my-new-function

Deregistering a Lambda function target

To deregister a Lambda function target in a VPC Lattice network, use the VPC console. For more information, see the VPC Lattice user guide.

Alternatively, you can use the following AWS CLI command:

aws vpc-lattice deregister-targets \ --target-group-identifier arn:aws:vpc-lattice:us-west-2:123456789012:targetgroup/tg-0e2f2665e1cebb720 \ --targets id=arn:aws:lambda:us-west-2:123456789012:function:my-new-function

You cannot deregister a service built using Lambda functions from the Lambda console.

Cross-account networking

Services within your VPC Lattice service network don't have to all be in the same AWS account. In addition, the VPC Lattice service network itself can reside in a different account. This means that you can associate a service built using Lambda functions with a service network in a different AWS account. You'll need specific permissions from the network owner to create these service associations. For more information about permissions required, see Prepare to call the VPC Lattice API in the Amazon VPC Lattice user guide.

You can create an association between a Lambda function with a service network in a different account through the AWS console. To do this, instead of choosing the VPC Lattice network from the dropdown menu (this only displays networks in your account), paste the full ARN of the network.

In general, you can create an association between any service and any service network with the create-service-network-service-association AWS CLI command. This means you can manage your service networks in a central account and have services built using Lambda functions in other accounts across your AWS organization. In the following example, note that the service and service-network live in two different accounts:

aws vpc-lattice create-service-network-service-association \ --service arn:aws:vpc-lattice:us-west-2:123456789012:service/svc-0b9b89d907bc8668c \ --service-network arn:aws:vpc-lattice:us-west-2:444455556666:servicenetwork/03d622a31e5154247

Receiving events from VPC Lattice

The VPC Lattice service routes Lambda invocation requests over HTTP and HTTPS. The event structure version that your function receives depends on your LambdaEventStructureVersion setting when you created your target group.

Sample V1 event structure

The following is an example V1 event that your Lambda function might receive from VPC Lattice, in JSON format:

{ "raw_path": "/path/to/resource", "method": "GET|POST|HEAD|...", "headers": {"header-key": "header-value", ... }, "query_string_parameters": {"key": "value", ...}, "body": "request-body", "is_base64_encoded": true|false }

If the content-encoding header is not present, Base64 encoding depends on the content type. For the content types, text/*, application/json, application/xml, and application/javascript, the service sends the body as is and sets isBase64Encoded to false.

Note

The request body can have a maximum size of 1023 KiB if sent in plaintext, or 767 KiB if base64 encoded. The list of request headers can have a maximum of 50 key-value pairs.

Sample V2 event structure

The following is an example V2 event that your Lambda function might receive from VPC Lattice, in JSON format:

{ "version": "2.0", "path": "/", "method": "GET|POST|HEAD|...", "headers": {"header-key": "header-value", ... }, "requestContext": { "serviceNetworkArn": "arn:aws:vpc-lattice:region:123456789012:servicenetwork/sn-0bf3f2882e9cc805a", "serviceArn": "arn:aws:vpc-lattice:region:123456789012:service/svc-0a40eebed65f8d69c", "targetGroupArn": "arn:aws:vpc-lattice:region:123456789012:targetgroup/tg-6d0ecf831eec9f09", "identity": { "sourceVpcArn": "arn:aws:ec2:region:123456789012:vpc/vpc-0b8276c84697e7339", "type" : "AWS_IAM", "principal": "arn:aws:sts::123456789012:assumed-role/example-role/057d00f8b51257ba3c853a0f248943cf", "sessionName": "057d00f8b51257ba3c853a0f248943cf", "x509SanDns": "example.com" }, "region": "region", "timeEpoch": "1690497599177430" } }

Sending responses back to VPC Lattice

When you send a response from your Lambda function back to VPC Lattice, the response must include the Base64 encoding status, status code, and relevant headers. The body is optional. The following is an example response in JSON format:

{ "isBase64Encoded": false, "statusCode": 200, "statusDescription": "200 OK", "headers": { "Set-Cookie": "cookies", "Content-Type": "application/json" }, "body": "Hello from Lambda (optional)" }

To include binary content in the response body, you must Base64 encode the content and set isBase64Encoded to true. This tells VPC Lattice to decode the content before sending the response to the client.

VPC Lattice doesn't honor hop-by-hop headers such as Connection or Transfer-Encoding. Also, you can omit the Content-Length header because VPC Lattice automatically computes it before sending responses to clients.

Note

The response body can have a maximum size of 1023 KiB if sent in plaintext, or 767 KiB if base64 encoded. The list of response headers can have a maximum of 50 key-value pairs.

Monitoring a service in a VPC Lattice network

To monitor services built using Lambda functions in a VPC Lattice network, VPC Lattice provides Amazon CloudWatch metrics, AWS CloudTrail logs, and access logs. These tools can help you track key performance metrics such as the total number of requests to your service and the number of connection timeouts.

By default, Lambda automatically emits metrics to CloudWatch and event history logs to CloudTrail. Access logs are optional, and Lambda deactivates them by default. For more information on monitoring, see Monitoring Amazon VPC Lattice in the VPC Lattice user guide.