Skip to content

Commit 468843c

Browse files
authored
Merge pull request #2891 from DmitryGulin/pattern/lambda-managed-instances-tf
add Hello World lambda managed instances TF pattern
2 parents 4226d60 + 3f2c360 commit 468843c

15 files changed

Lines changed: 1021 additions & 0 deletions
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# Terraform files
2+
*.tfstate
3+
*.tfstate.*
4+
*.tfvars
5+
*.tfvars.json
6+
.terraform/
7+
.terraform.lock.hcl
8+
terraform.tfplan
9+
terraform.tfplan.*
10+
11+
# Lambda function package
12+
lambda-function.zip
13+
14+
# Test response files
15+
response.json
16+
custom-response.json
17+
output.json
18+
19+
# Node.js dependencies
20+
lambda/node_modules/
21+
lambda/package-lock.json
22+
23+
# OS files
24+
.DS_Store
25+
Thumbs.db
26+
27+
# IDE files
28+
.vscode/
29+
.idea/
30+
*.swp
31+
*.swo
Lines changed: 207 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,207 @@
1+
# Hello World on AWS Lambda Managed Instances (Terraform)
2+
3+
This pattern demonstrates how to deploy a simple Hello World Lambda function running on AWS Lambda Managed Instances using Terraform. AWS Lambda Managed Instances enables you to run Lambda functions on EC2 instances while maintaining Lambda's operational simplicity. It fully manages infrastructure tasks including instance lifecycle, OS and runtime patching, routing, load balancing, and auto scaling.
4+
5+
Learn more about this pattern at Serverless Land Patterns: https://serverlessland.com/patterns/lambda-managed-instances-tf
6+
7+
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.
8+
9+
**Note**: AWS Lambda Managed Instances provision EC2 instances that are **NOT eligible for the AWS Free Tier**. These instances will incur charges immediately upon deployment, regardless of your Free Tier status.
10+
11+
## Requirements
12+
13+
* [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. The IAM user that you use must have sufficient permissions to make necessary AWS service calls and manage AWS resources.
14+
* [AWS CLI v2](https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html) (latest available version) installed and configured
15+
* [Git Installed](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)
16+
* [Terraform](https://learn.hashicorp.com/tutorials/terraform/install-cli) (version 1.0 or later) installed
17+
* [Node.js](https://nodejs.org/) (version 24.x or later) for Lambda function dependencies
18+
19+
## Deployment Instructions
20+
21+
1. Create a new directory, navigate to that directory in a terminal and clone the GitHub repository:
22+
```
23+
git clone https://github.com/aws-samples/serverless-patterns
24+
```
25+
1. Change directory to the pattern directory:
26+
```
27+
cd lambda-managed-instances-tf
28+
```
29+
30+
### Manual Deployment
31+
32+
1. Install Lambda function dependencies:
33+
```
34+
cd lambda && npm install && cd ..
35+
```
36+
1. Initialize Terraform:
37+
```
38+
terraform init
39+
```
40+
1. Plan the deployment:
41+
```
42+
terraform plan
43+
```
44+
1. Deploy the infrastructure:
45+
```
46+
terraform apply
47+
```
48+
Note: This stack will deploy to your default AWS region. You can specify a different region by setting the `aws_region` variable.
49+
50+
### Deployment script
51+
52+
1. Use can use `deploy.sh` script to run all deployment commands:
53+
```
54+
./deploy.sh [aws-region]
55+
```
56+
57+
1. Note the outputs from the Terraform deployment process. These contain the resource names and/or ARNs which are used for testing.
58+
59+
60+
You can customize the deployment by modifying the variables in `variables.tf` or by passing variables during deployment:
61+
62+
```bash
63+
terraform apply -var="aws_region=us-east-1"
64+
```
65+
66+
## How it works
67+
68+
![Architecture Diagram](doc/architecture-diagram.png)
69+
70+
This pattern creates a capacity provider with VPC and security group configuration, then deploys a Node.js Lambda function (ARM64 architecture) that is associated with the capacity provider to run on managed EC2 instances. The Terraform configuration provisions a complete VPC infrastructure with public and private subnets across multiple availability zones, NAT gateways for outbound connectivity, and all necessary IAM roles and permissions.
71+
72+
## Testing
73+
74+
After deployment, you can test the Lambda function using AWS CLI or AWS Console.
75+
76+
### AWS CLI Testing
77+
78+
1. **Basic function invocation**:
79+
```bash
80+
aws lambda invoke \
81+
--function-name hello-world-managed-instances-tf \
82+
--payload file://events/hello-world.json \
83+
--cli-binary-format raw-in-base64-out \
84+
response.json
85+
```
86+
87+
2. **View the response**:
88+
```bash
89+
cat response.json
90+
```
91+
92+
3. **Custom name invocation**:
93+
```bash
94+
echo '{"name":"Lambda Managed Instances"}' | aws lambda invoke \
95+
--function-name hello-world-managed-instances-tf \
96+
--payload file:///dev/stdin \
97+
--cli-binary-format raw-in-base64-out \
98+
custom-response.json
99+
```
100+
101+
4. **View CloudWatch logs**:
102+
```bash
103+
aws logs filter-log-events \
104+
--log-group-name /aws/lambda/hello-world-managed-instances-tf \
105+
--start-time $(date -d '5 minutes ago' +%s)000
106+
```
107+
108+
### AWS Console Testing
109+
110+
1. Navigate to the Lambda service in the AWS Console
111+
2. Find the function named `hello-world-managed-instances-tf`
112+
3. Create a test event using the payload from `events/hello-world.json` or create a custom payload:
113+
```json
114+
{
115+
"name": "Your Custom Name"
116+
}
117+
```
118+
4. Execute the test and observe the results in the execution logs
119+
120+
### Expected Response
121+
122+
The function returns a JSON response with the following structure:
123+
124+
```json
125+
{
126+
"response": "Hello AWS Lambda on Managed Instances"
127+
}
128+
```
129+
130+
### Monitoring and Observability
131+
132+
Monitor the function execution through:
133+
- **CloudWatch Logs**: Detailed execution logs with event and response data
134+
- **Lambda Metrics**: Function performance and invocation statistics
135+
- **CloudWatch Metrics**: Custom metrics and alarms for monitoring
136+
137+
## Inspecting AWS Lambda Managed Instances Infrastructure
138+
139+
AWS Lambda Managed Instances provision EC2 instances behind the scenes to run your Lambda functions. You can inspect this infrastructure using AWS CLI commands:
140+
141+
### View Capacity Provider Details
142+
143+
```bash
144+
aws lambda get-capacity-provider --capacity-provider-name lambda-capacity-provider
145+
```
146+
147+
This shows:
148+
- Capacity provider ARN and state
149+
- VPC configuration (subnets and security groups)
150+
- Instance requirements (architecture, scaling mode)
151+
- IAM roles and permissions
152+
153+
### List Associated EC2 Instances
154+
155+
```bash
156+
aws ec2 describe-instances \
157+
--filters "Name=tag:aws:lambda:capacity-provider,Values=arn:aws:lambda:*:capacity-provider:lambda-capacity-provider" \
158+
--query 'Reservations[*].Instances[*].[InstanceId,InstanceType,State.Name,LaunchTime,SubnetId,PrivateIpAddress]' \
159+
--output table
160+
```
161+
162+
This displays:
163+
- Instance IDs and types
164+
- Current state (running, pending, terminated)
165+
- Launch times and subnet distribution
166+
- Private IP addresses within the VPC
167+
168+
**Note**: For a complete list of supported EC2 instance types for AWS Lambda Managed Instances and their pricing, see the [AWS Lambda Pricing page](https://aws.amazon.com/lambda/pricing/).
169+
170+
### Understanding Instance Behavior
171+
172+
**Auto-scaling**: Instances are automatically created and terminated based on function demand
173+
- **Scale-up**: New instances launch when function invocation increases
174+
- **Scale-down**: Unused instances terminate after periods of low activity
175+
- **Multi-AZ**: Instances are distributed across availability zones for high availability
176+
177+
**Instance Lifecycle**:
178+
- Instances typically launch within 1-2 minutes of stack deployment
179+
- They remain running to provide immediate function execution
180+
- AWS manages all instance lifecycle operations automatically
181+
182+
### Automated Testing
183+
184+
The included test script (`./test-lambda.sh`) automatically inspects both the capacity provider and EC2 instances, providing a comprehensive view of the managed instances infrastructure.
185+
186+
## Regional Availability
187+
188+
This stack will deploy to your default AWS region or the region specified in the `aws_region` variable. Before deploying, please verify that AWS Lambda Managed Instances feature is available in your target region by using the [AWS capabilities explorer](https://builder.aws.com/build/capabilities/explore) or consulting the official [AWS Lambda Managed Instances documentation](https://docs.aws.amazon.com/lambda/latest/dg/lambda-managed-instances.html).
189+
190+
## Cleanup
191+
192+
1. Delete the infrastructure:
193+
```bash
194+
terraform destroy
195+
```
196+
197+
**Alternative**: Use the automated cleanup script:
198+
```bash
199+
./cleanup.sh [aws-region]
200+
```
201+
202+
1. Confirm the resources have been deleted by checking the AWS Console.
203+
204+
----
205+
Copyright 2026 Amazon.com, Inc. or its affiliates. All Rights Reserved.
206+
207+
SPDX-License-Identifier: MIT-0
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
#!/bin/bash
2+
3+
# Cleanup script for Lambda Managed Instances Terraform pattern
4+
# Usage: ./cleanup.sh [aws-region]
5+
6+
set -e
7+
8+
# Configuration
9+
AWS_REGION=${1:-us-west-2}
10+
11+
# Colors for output
12+
RED='\033[0;31m'
13+
GREEN='\033[0;32m'
14+
YELLOW='\033[1;33m'
15+
BLUE='\033[0;34m'
16+
NC='\033[0m' # No Color
17+
18+
echo -e "${BLUE}=== Cleaning up Lambda Managed Instances Pattern (Terraform) ===${NC}"
19+
echo -e "${YELLOW}Region: ${AWS_REGION}${NC}"
20+
echo ""
21+
22+
# Confirm destruction
23+
echo -e "${YELLOW}This will destroy all resources created by this pattern.${NC}"
24+
read -p "Are you sure you want to continue? (y/N): " -n 1 -r
25+
echo
26+
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
27+
echo -e "${YELLOW}Cleanup cancelled.${NC}"
28+
exit 0
29+
fi
30+
31+
# Destroy infrastructure
32+
echo -e "${BLUE}Destroying Terraform infrastructure...${NC}"
33+
terraform destroy -var="aws_region=${AWS_REGION}" -auto-approve
34+
35+
if [ $? -eq 0 ]; then
36+
echo -e "${GREEN}✓ Infrastructure successfully destroyed${NC}"
37+
else
38+
echo -e "${RED}✗ Failed to destroy infrastructure${NC}"
39+
exit 1
40+
fi
41+
42+
# Clean up local files
43+
echo -e "${BLUE}Cleaning up local files...${NC}"
44+
rm -f lambda-function.zip
45+
rm -f response.json
46+
rm -f custom-response.json
47+
rm -f output.json
48+
49+
# Clean up Terraform temporary and state files
50+
echo -e "${BLUE}Cleaning up Terraform temporary and state files...${NC}"
51+
rm -f terraform.tfstate
52+
rm -f terraform.tfstate.backup
53+
rm -f .terraform.tfstate.lock.info
54+
rm -rf .terraform/
55+
rm -f .terraform.lock.hcl
56+
rm -f terraform.tfplan
57+
rm -f terraform.log
58+
rm -f crash.log
59+
60+
echo ""
61+
echo -e "${GREEN}=== Cleanup completed successfully! ===${NC}"
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
#!/bin/bash
2+
3+
# Deployment script for Lambda Managed Instances Terraform pattern
4+
# Usage: ./deploy.sh [aws-region]
5+
6+
set -e
7+
8+
# Configuration
9+
AWS_REGION=${1:-us-west-2}
10+
11+
# Colors for output
12+
RED='\033[0;31m'
13+
GREEN='\033[0;32m'
14+
YELLOW='\033[1;33m'
15+
BLUE='\033[0;34m'
16+
NC='\033[0m' # No Color
17+
18+
echo -e "${BLUE}=== Deploying Lambda Managed Instances Pattern (Terraform) ===${NC}"
19+
echo -e "${YELLOW}Region: ${AWS_REGION}${NC}"
20+
echo ""
21+
22+
# Step 1: Install Lambda dependencies
23+
echo -e "${BLUE}Step 1: Installing Lambda function dependencies${NC}"
24+
cd lambda
25+
if [ ! -f "package-lock.json" ]; then
26+
npm install
27+
else
28+
echo "Dependencies already installed"
29+
fi
30+
cd ..
31+
32+
# Step 2: Initialize Terraform
33+
echo -e "${BLUE}Step 2: Initializing Terraform${NC}"
34+
terraform init
35+
36+
# Step 3: Plan deployment
37+
echo -e "${BLUE}Step 3: Planning Terraform deployment${NC}"
38+
terraform plan -var="aws_region=${AWS_REGION}"
39+
40+
# Step 4: Apply infrastructure
41+
echo -e "${BLUE}Step 4: Applying Terraform configuration${NC}"
42+
terraform apply -var="aws_region=${AWS_REGION}" -auto-approve
43+
44+
echo -e "${GREEN}✓ Lambda function automatically associated with capacity provider via Terraform${NC}"
45+
46+
echo ""
47+
echo -e "${GREEN}=== Deployment completed successfully! ===${NC}"
48+
echo ""
49+
echo -e "${YELLOW}Outputs:${NC}"
50+
terraform output
51+
52+
echo ""
53+
echo -e "${YELLOW}Next steps:${NC}"
54+
CAPACITY_PROVIDER_NAME=$(terraform output -raw capacity_provider_name)
55+
FUNCTION_NAME=$(terraform output -raw function_name)
56+
echo "1. Test the function: ./test-lambda.sh"
57+
echo "2. View capacity provider: aws lambda get-capacity-provider --capacity-provider-name $CAPACITY_PROVIDER_NAME --region $AWS_REGION"
58+
echo "3. View function details: aws lambda get-function --function-name $FUNCTION_NAME --region $AWS_REGION"
28.6 KB
Loading
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
{
2+
"name": "AWS Lambda Managed Instances"
3+
}

0 commit comments

Comments
 (0)