diff --git a/lambda-managed-instances-python-sam/README.md b/lambda-managed-instances-python-sam/README.md new file mode 100644 index 000000000..176ebdbf0 --- /dev/null +++ b/lambda-managed-instances-python-sam/README.md @@ -0,0 +1,116 @@ +# AWS Lambda Managed Instances with AWS SAM (Python) + +This pattern deploys a Python Lambda function running on AWS Lambda Managed Instances using AWS SAM. Lambda Managed Instances enables you to run functions on Amazon EC2 instances while AWS handles lifecycle management, patching, routing, and scaling. You benefit from EC2 pricing (Savings Plans, Reserved Instances) and multi-concurrency support. + +Learn more about this pattern at Serverless Land Patterns: [https://serverlessland.com/patterns/lambda-managed-instances-python-sam](https://serverlessland.com/patterns/lambda-managed-instances-python-sam) + +Important: this application uses various AWS services and there are costs associated with these services after the Free Tier usage - please see the [AWS Pricing page](https://aws.amazon.com/pricing/) for details. You are responsible for any AWS costs incurred. No warranty is implied in this example. + +**Note**: Lambda Managed Instances provision EC2 instances that are **NOT eligible for the AWS Free Tier**. Instances incur charges immediately upon deployment. + +## Requirements + +- [Create an AWS account](https://portal.aws.amazon.com/gp/aws/developer/registration/index.html) if you do not already have one and log in. +- [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html) installed and configured +- [Git Installed](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git) +- [AWS SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html) installed (v1.164.0+) +- [Python 3.13](https://www.python.org/downloads/) installed and available in your PATH + +## Deployment Instructions + +1. Create a new directory, navigate to that directory in a terminal and clone the GitHub repository: + ``` + git clone https://github.com/aws-samples/serverless-patterns + ``` +1. Change directory to the pattern directory: + ``` + cd lambda-managed-instances-python-sam + ``` +1. From the command line, use AWS SAM to build and deploy: + ``` + sam build + sam deploy --guided --capabilities CAPABILITY_NAMED_IAM + ``` + `CAPABILITY_NAMED_IAM` is required because the template creates a named IAM role for the capacity provider operator. +1. During the prompts: + - Enter a stack name + - Enter the desired AWS Region + - Allow SAM CLI to create IAM roles with the required permissions. + + Once you have run `sam deploy --guided` mode once and saved arguments to a configuration file (samconfig.toml), you can use `sam deploy` in future to use these defaults. + +1. Note the outputs from the SAM deployment process. These contain the resource names and/or ARNs which are used for testing. + +## How it works + +This pattern creates: + +1. **VPC with private subnets**: Two private subnets across availability zones for the capacity provider. The subnets use a dedicated private route table with no internet route (no NAT, no internet gateway). Egress to AWS services stays inside the VPC via PrivateLink: interface endpoints for Amazon CloudWatch Logs, Amazon ECR (`ecr.api` and `ecr.dkr`), and Amazon EC2, plus an Amazon S3 gateway endpoint for pulling the runtime image layers. + +2. **Capacity Provider Operator IAM Role**: An Amazon IAM role with the `AWSLambdaManagedEC2ResourceOperator` managed policy that Lambda uses to provision and manage EC2 instances. + +3. **Lambda Capacity Provider**: Defines where functions run — VPC config, instance architecture (arm64 / AWS Graviton), and the operator role for instance management. + +4. **Lambda function on Managed Instances**: A Python function attached to the capacity provider via `CapacityProviderConfig`. Once a version is published, Lambda provisions instances and starts execution environments. + +5. **Multi-concurrency**: Unlike default Lambda (1 invocation per environment), Managed Instances support multiple concurrent invocations per environment. The example uses thread-safe patterns to demonstrate this. + +### When to use Managed Instances + +- High-volume, predictable workloads (steady-state traffic) +- Cost optimization via EC2 Savings Plans or Reserved Instances +- Performance-critical apps needing specific CPU/network characteristics +- Regulatory requirements needing VPC placement control + +### Key constraints + +- Minimum `MemorySize` is 2048 MB (2 GB) +- A published version or alias is required for invocation +- Capacity provider scales within 5 minutes for traffic doubling + +## Testing + +1. Invoke the function via the `live` alias: + + ```bash + aws lambda invoke \ + --function-name '-api-handler' \ + --qualifier live \ + --cli-binary-format raw-in-base64-out \ + --payload '{"name": "Serverless Land"}' \ + /tmp/response.json && cat /tmp/response.json + ``` + +2. Expected response: + + ```json + { + "statusCode": 200, + "body": "{\"message\": \"Hello, Serverless Land!\", \"invocation\": 1, \"timestamp\": \"2026-09-16T14:30:00.123456+00:00\", \"version\": \"1\"}" + } + ``` + +3. Test multi-concurrency by invoking in parallel: + ```bash + for i in $(seq 1 10); do + aws lambda invoke \ + --function-name '-api-handler' \ + --qualifier live \ + --cli-binary-format raw-in-base64-out \ + --payload "{\"name\": \"Request-$i\"}" \ + /tmp/response-$i.json & + done + wait + ``` + +## Cleanup + +```bash +sam delete +``` + +--- + +Copyright 2026 Amazon.com, Inc. or its affiliates. All Rights Reserved. + +SPDX-License-Identifier: MIT-0 diff --git a/lambda-managed-instances-python-sam/example-pattern.json b/lambda-managed-instances-python-sam/example-pattern.json new file mode 100644 index 000000000..1147f189b --- /dev/null +++ b/lambda-managed-instances-python-sam/example-pattern.json @@ -0,0 +1,54 @@ +{ + "title": "Lambda Managed Instances with SAM (Python)", + "description": "Deploy a Python Lambda function on AWS-managed EC2 instances with multi-concurrency, Graviton4 support, and EC2 pricing advantages.", + "language": "Python", + "level": "300", + "framework": "SAM", + "introBox": { + "headline": "How it works", + "text": [ + "This pattern creates a Lambda Capacity Provider with VPC configuration and deploys a Python function that runs on managed EC2 instances.", + "Lambda handles instance lifecycle, OS patching, routing, and auto-scaling while you benefit from EC2 pricing models.", + "Multi-concurrency allows one execution environment to handle multiple invocations simultaneously." + ] + }, + "gitHub": { + "template": { + "repoURL": "https://github.com/aws-samples/serverless-patterns/tree/main/lambda-managed-instances-python-sam", + "templateURL": "serverless-patterns/lambda-managed-instances-python-sam", + "projectFolder": "lambda-managed-instances-python-sam", + "templateFile": "template.yaml" + } + }, + "resources": { + "bullets": [ + { + "text": "Lambda Managed Instances", + "link": "https://docs.aws.amazon.com/lambda/latest/dg/lambda-managed-instances.html" + }, + { + "text": "Build high-performance apps with Lambda Managed Instances", + "link": "https://aws.amazon.com/blogs/compute/build-high-performance-apps-with-aws-lambda-managed-instances/" + } + ] + }, + "deploy": { + "text": ["sam deploy --guided"], + "file": "template.yaml" + }, + "testing": { + "text": ["See the GitHub repo for detailed testing instructions."], + "file": "README.md" + }, + "cleanup": { + "text": ["Delete the stack: sam delete"], + "file": "template.yaml" + }, + "authors": [ + { + "name": "Ajaya Shrestha", + "bio": "Cloud Support Engineer at AWS", + "linkedin": "ajaya-shrestha" + } + ] +} diff --git a/lambda-managed-instances-python-sam/template.yaml b/lambda-managed-instances-python-sam/template.yaml new file mode 100644 index 000000000..969c0e72a --- /dev/null +++ b/lambda-managed-instances-python-sam/template.yaml @@ -0,0 +1,305 @@ +AWSTemplateFormatVersion: "2010-09-09" +Transform: AWS::Serverless-2016-10-31 +Description: > + Lambda Managed Instances with SAM (Python). + Runs a Lambda function on EC2 instances managed by AWS, with EC2 pricing + advantages (Savings Plans, Reserved Instances) and multi-concurrency support. + +Parameters: + VpcCIDR: + Type: String + Default: "10.0.0.0/16" + Description: CIDR block for the VPC + +Resources: + # VPC for Managed Instances + ManagedInstancesVPC: + Type: AWS::EC2::VPC + Properties: + CidrBlock: !Ref VpcCIDR + EnableDnsHostnames: true + EnableDnsSupport: true + Tags: + - Key: Name + Value: !Sub "${AWS::StackName}-vpc" + + PrivateSubnet1: + Type: AWS::EC2::Subnet + Properties: + VpcId: !Ref ManagedInstancesVPC + CidrBlock: "10.0.1.0/24" + AvailabilityZone: !Select [0, !GetAZs ""] + Tags: + - Key: Name + Value: !Sub "${AWS::StackName}-private-1" + + PrivateSubnet2: + Type: AWS::EC2::Subnet + Properties: + VpcId: !Ref ManagedInstancesVPC + CidrBlock: "10.0.2.0/24" + AvailabilityZone: !Select [1, !GetAZs ""] + Tags: + - Key: Name + Value: !Sub "${AWS::StackName}-private-2" + + SecurityGroup: + Type: AWS::EC2::SecurityGroup + Properties: + GroupDescription: Security group for Lambda Managed Instances + VpcId: !Ref ManagedInstancesVPC + # Egress to 443 so instances can reach the VPC interface endpoints + SecurityGroupEgress: + - IpProtocol: tcp + FromPort: 443 + ToPort: 443 + CidrIp: !Ref VpcCIDR + Description: HTTPS to VPC endpoints within the VPC + Tags: + - Key: Name + Value: !Sub "${AWS::StackName}-sg" + + # --- Private networking (no internet path) --- + # Managed Instances egress (e.g. CloudWatch Logs, ECR image pull) stays inside + # the VPC and reaches AWS services over PrivateLink interface/gateway endpoints. + + # Explicit private route table for the subnets. It has only the implicit + # local route (10.0.0.0/16) plus the S3 gateway endpoint route below — + # there is deliberately no 0.0.0.0/0 route, so no internet egress. + PrivateRouteTable: + Type: AWS::EC2::RouteTable + Properties: + VpcId: !Ref ManagedInstancesVPC + Tags: + - Key: Name + Value: !Sub "${AWS::StackName}-private-rt" + + PrivateSubnet1RouteTableAssociation: + Type: AWS::EC2::SubnetRouteTableAssociation + Properties: + SubnetId: !Ref PrivateSubnet1 + RouteTableId: !Ref PrivateRouteTable + + PrivateSubnet2RouteTableAssociation: + Type: AWS::EC2::SubnetRouteTableAssociation + Properties: + SubnetId: !Ref PrivateSubnet2 + RouteTableId: !Ref PrivateRouteTable + + # Security group for the interface endpoints: allow inbound 443 from the + # instance security group only. + VPCEndpointSecurityGroup: + Type: AWS::EC2::SecurityGroup + Properties: + GroupDescription: Allow HTTPS from Managed Instances to VPC interface endpoints + VpcId: !Ref ManagedInstancesVPC + SecurityGroupIngress: + - IpProtocol: tcp + FromPort: 443 + ToPort: 443 + SourceSecurityGroupId: !Ref SecurityGroup + Description: HTTPS from Managed Instances + Tags: + - Key: Name + Value: !Sub "${AWS::StackName}-vpce-sg" + + # Interface endpoint: CloudWatch Logs (documented egress requirement for LMI) + LogsEndpoint: + Type: AWS::EC2::VPCEndpoint + Properties: + VpcId: !Ref ManagedInstancesVPC + ServiceName: !Sub "com.amazonaws.${AWS::Region}.logs" + VpcEndpointType: Interface + PrivateDnsEnabled: true + SubnetIds: + - !Ref PrivateSubnet1 + - !Ref PrivateSubnet2 + SecurityGroupIds: + - !Ref VPCEndpointSecurityGroup + + # Interface endpoints: ECR API + Docker registry (instances pull the runtime image) + EcrApiEndpoint: + Type: AWS::EC2::VPCEndpoint + Properties: + VpcId: !Ref ManagedInstancesVPC + ServiceName: !Sub "com.amazonaws.${AWS::Region}.ecr.api" + VpcEndpointType: Interface + PrivateDnsEnabled: true + SubnetIds: + - !Ref PrivateSubnet1 + - !Ref PrivateSubnet2 + SecurityGroupIds: + - !Ref VPCEndpointSecurityGroup + + EcrDkrEndpoint: + Type: AWS::EC2::VPCEndpoint + Properties: + VpcId: !Ref ManagedInstancesVPC + ServiceName: !Sub "com.amazonaws.${AWS::Region}.ecr.dkr" + VpcEndpointType: Interface + PrivateDnsEnabled: true + SubnetIds: + - !Ref PrivateSubnet1 + - !Ref PrivateSubnet2 + SecurityGroupIds: + - !Ref VPCEndpointSecurityGroup + + # Interface endpoint: EC2 (instance lifecycle calls) + Ec2Endpoint: + Type: AWS::EC2::VPCEndpoint + Properties: + VpcId: !Ref ManagedInstancesVPC + ServiceName: !Sub "com.amazonaws.${AWS::Region}.ec2" + VpcEndpointType: Interface + PrivateDnsEnabled: true + SubnetIds: + - !Ref PrivateSubnet1 + - !Ref PrivateSubnet2 + SecurityGroupIds: + - !Ref VPCEndpointSecurityGroup + + # Gateway endpoint: S3 (ECR image layers are stored in S3). Bound to the + # private route table via an AWS managed prefix list route. + S3GatewayEndpoint: + Type: AWS::EC2::VPCEndpoint + Properties: + VpcId: !Ref ManagedInstancesVPC + ServiceName: !Sub "com.amazonaws.${AWS::Region}.s3" + VpcEndpointType: Gateway + RouteTableIds: + - !Ref PrivateRouteTable + + # IAM role for Capacity Provider operator + CapacityProviderOperatorRole: + Type: AWS::IAM::Role + Properties: + RoleName: !Sub "${AWS::StackName}-cp-operator-role" + AssumeRolePolicyDocument: + Version: "2012-10-17" + Statement: + - Effect: Allow + Principal: + Service: lambda.amazonaws.com + Action: sts:AssumeRole + ManagedPolicyArns: + - arn:aws:iam::aws:policy/AWSLambdaManagedEC2ResourceOperator + + # Lambda Capacity Provider — defines where functions run + LambdaCapacityProvider: + Type: AWS::Lambda::CapacityProvider + Properties: + CapacityProviderName: !Sub "${AWS::StackName}-capacity-provider" + VpcConfig: + SubnetIds: + - !Ref PrivateSubnet1 + - !Ref PrivateSubnet2 + SecurityGroupIds: + - !Ref SecurityGroup + InstanceRequirements: + Architectures: + - arm64 + PermissionsConfig: + CapacityProviderOperatorRoleArn: !GetAtt CapacityProviderOperatorRole.Arn + + # CloudWatch Logs + ApiHandlerLogGroup: + Type: AWS::Logs::LogGroup + Properties: + LogGroupName: !Sub "/aws/lambda/${AWS::StackName}-api-handler" + RetentionInDays: 14 + + # Lambda execution role + ApiHandlerRole: + Type: AWS::IAM::Role + Properties: + AssumeRolePolicyDocument: + Version: "2012-10-17" + Statement: + - Effect: Allow + Principal: + Service: lambda.amazonaws.com + Action: sts:AssumeRole + ManagedPolicyArns: + - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole + + # Lambda function running on Managed Instances + # Note: no explicit DependsOn is needed — the LoggingConfig !Ref to + # ApiHandlerLogGroup and the CapacityProviderConfig !GetAtt to + # LambdaCapacityProvider already enforce correct creation order. + ApiHandlerFunction: + Type: AWS::Lambda::Function + Properties: + FunctionName: !Sub "${AWS::StackName}-api-handler" + Runtime: python3.13 + Handler: index.lambda_handler + Code: + ZipFile: | + import json + import threading + from datetime import datetime, timezone + + _lock = threading.Lock() + _count = 0 + + def lambda_handler(event, context): + global _count + with _lock: + _count += 1 + count = _count + name = event.get("name", "Managed Instances") + return { + "statusCode": 200, + "body": json.dumps({ + "message": f"Hello, {name}!", + "invocation": count, + "timestamp": datetime.now(timezone.utc).isoformat(), + "version": context.function_version + }) + } + Architectures: + - arm64 + MemorySize: 2048 + Timeout: 30 + Description: Python API handler running on Lambda Managed Instances + Role: !GetAtt ApiHandlerRole.Arn + CapacityProviderConfig: + LambdaManagedInstancesCapacityProviderConfig: + CapacityProviderArn: !GetAtt LambdaCapacityProvider.Arn + LoggingConfig: + LogGroup: !Ref ApiHandlerLogGroup + + # Publish a version (required for Managed Instances invocation) + ApiHandlerVersion: + Type: AWS::Lambda::Version + Properties: + FunctionName: !Ref ApiHandlerFunction + Description: Initial version for Managed Instances + + # Alias for stable invocation endpoint + ApiHandlerAlias: + Type: AWS::Lambda::Alias + Properties: + FunctionName: !Ref ApiHandlerFunction + FunctionVersion: !GetAtt ApiHandlerVersion.Version + Name: live + +Outputs: + FunctionName: + Description: Lambda function name + Value: !Ref ApiHandlerFunction + + FunctionAlias: + Description: Function alias ARN for invocation + Value: !Ref ApiHandlerAlias + + CapacityProviderArn: + Description: Capacity provider ARN + Value: !GetAtt LambdaCapacityProvider.Arn + + VpcId: + Description: VPC ID + Value: !Ref ManagedInstancesVPC + + PrivateRouteTableId: + Description: Private route table ID (no internet route; S3 gateway + local only) + Value: !Ref PrivateRouteTable