From eeef170cba1f367586e0e100ebb23db554f0532d Mon Sep 17 00:00:00 2001 From: Dmitry Gulin Date: Thu, 11 Dec 2025 17:06:24 -0500 Subject: [PATCH 1/8] add a simplistic `lambda-managed-instances-cdk` pattern --- lambda-managed-instances-cdk/.gitignore | 91 +++++++++ lambda-managed-instances-cdk/.npmignore | 6 + lambda-managed-instances-cdk/README.md | 193 ++++++++++++++++++ lambda-managed-instances-cdk/bin/app.ts | 13 ++ lambda-managed-instances-cdk/cdk.json | 70 +++++++ .../events/hello-world.json | 3 + .../example-pattern.json | 66 ++++++ .../lambda/hello-world.mts | 24 +++ .../lib/demo-stack.ts | 47 +++++ lambda-managed-instances-cdk/package.json | 24 +++ lambda-managed-instances-cdk/test-lambda.sh | 118 +++++++++++ lambda-managed-instances-cdk/tsconfig.json | 30 +++ 12 files changed, 685 insertions(+) create mode 100644 lambda-managed-instances-cdk/.gitignore create mode 100644 lambda-managed-instances-cdk/.npmignore create mode 100644 lambda-managed-instances-cdk/README.md create mode 100644 lambda-managed-instances-cdk/bin/app.ts create mode 100644 lambda-managed-instances-cdk/cdk.json create mode 100644 lambda-managed-instances-cdk/events/hello-world.json create mode 100644 lambda-managed-instances-cdk/example-pattern.json create mode 100644 lambda-managed-instances-cdk/lambda/hello-world.mts create mode 100644 lambda-managed-instances-cdk/lib/demo-stack.ts create mode 100644 lambda-managed-instances-cdk/package.json create mode 100755 lambda-managed-instances-cdk/test-lambda.sh create mode 100644 lambda-managed-instances-cdk/tsconfig.json diff --git a/lambda-managed-instances-cdk/.gitignore b/lambda-managed-instances-cdk/.gitignore new file mode 100644 index 0000000000..70e5f6e7a7 --- /dev/null +++ b/lambda-managed-instances-cdk/.gitignore @@ -0,0 +1,91 @@ +*.js +!jest.config.js +*.d.ts +node_modules + +# CDK asset staging directory +.cdk.staging +cdk.out + +# Parcel default cache directory +.parcel-cache + +# npm +.npm + +# yarn +.yarn + +# IDE +.vscode/ +.idea/ + +# OS +.DS_Store +Thumbs.db + +# Logs +*.log + +# Runtime data +pids +*.pid +*.seed +*.pid.lock + +# Coverage directory used by tools like istanbul +coverage +*.lcov + +# nyc test coverage +.nyc_output + +# Dependency directories +node_modules/ +jspm_packages/ + +# Optional npm cache directory +.npm + +# Optional eslint cache +.eslintcache + +# Output of 'npm pack' +*.tgz + +# Yarn Integrity file +.yarn-integrity + +# dotenv environment variables file +.env +.env.test + +# parcel-bundler cache (https://parceljs.org/) +.cache +.parcel-cache + +# next.js build output +.next + +# nuxt.js build output +.nuxt + +# vuepress build output +.vuepress/dist + +# Serverless directories +.serverless/ + +# FuseBox cache +.fusebox/ + +# DynamoDB Local files +.dynamodb/ + +# TernJS port file +.tern-port + +# CDK Context & Staging files +.cdk.staging/ +cdk.out/ +cdk.context.json \ No newline at end of file diff --git a/lambda-managed-instances-cdk/.npmignore b/lambda-managed-instances-cdk/.npmignore new file mode 100644 index 0000000000..327e660d05 --- /dev/null +++ b/lambda-managed-instances-cdk/.npmignore @@ -0,0 +1,6 @@ +*.ts +!*.d.ts + +# CDK asset staging directory +.cdk.staging +cdk.out \ No newline at end of file diff --git a/lambda-managed-instances-cdk/README.md b/lambda-managed-instances-cdk/README.md new file mode 100644 index 0000000000..0ff891847b --- /dev/null +++ b/lambda-managed-instances-cdk/README.md @@ -0,0 +1,193 @@ +# Lambda Hello World on Lambda Managed Instances + +This pattern demonstrates how to deploy a simple Hello World Lambda function running on Lambda Managed Instances using AWS CDK. Lambda Managed Instances provide predictable performance and reduced cold starts for your Lambda functions. + +Learn more about this pattern at Serverless Land Patterns: https://serverlessland.com/patterns/lambda-managed-instances-cdk + +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**. These instances will incur charges immediately upon deployment, regardless of your Free Tier status. + +## 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. The IAM user that you use must have sufficient permissions to make necessary AWS service calls and manage AWS resources. +* [AWS CLI v2](https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html) (latest available version) installed and configured +* [Git Installed](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git) +* [AWS CDK](https://docs.aws.amazon.com/cdk/latest/guide/getting_started.html) (version 2.232.0 or later) installed and configured +* [Node.js](https://nodejs.org/) (version 24.x or later) + +## 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-cdk + ``` +1. Install the project dependencies: + ``` + npm install + ``` +1. Deploy the CDK stack: + ``` + cdk deploy + ``` + Note: This stack will deploy to your default AWS region. Please refer to the [AWS capabilities explorer](https://builder.aws.com/build/capabilities/explore) for feature availability in your desired region. + +1. Note the outputs from the CDK deployment process. These contain the resource names and/or ARNs which are used for testing. + +## How it works + +This pattern demonstrates the deployment of a simple Lambda function on Lambda Managed Instances: + +### Lambda Managed Instances +[Lambda Managed Instances](https://docs.aws.amazon.com/lambda/latest/dg/lambda-managed-instances.html) provide: +- Predictable performance with pre-warmed execution environments +- Reduced cold start latency +- Consistent execution characteristics +- Better resource utilization for frequently invoked functions + +The underlying EC2 infrastructure can be inspected using AWS CLI commands to understand how managed instances work (see "Inspecting Lambda Managed Instances Infrastructure" section below). + +### Hello World Function +The Lambda function is a simple Hello World implementation that: +- Accepts an event with a name parameter +- Returns a JSON response with a greeting message +- Uses AWS Lambda PowerTools for efficient event logging +- Demonstrates minimal Lambda function structure using the Handler type + +## Testing + +After deployment, you can test the Lambda function using AWS CLI or AWS Console. + +### AWS CLI Testing + +1. **Basic function invocation**: + ```bash + aws lambda invoke \ + --function-name hello-world-managed-instances \ + --payload file://events/hello-world.json \ + --cli-binary-format raw-in-base64-out \ + response.json + ``` + +2. **View the response**: + ```bash + cat response.json + ``` + +3. **Custom name invocation**: + ```bash + echo '{"name":"Lambda Managed Instances"}' | aws lambda invoke \ + --function-name hello-world-managed-instances \ + --payload file:///dev/stdin \ + --cli-binary-format raw-in-base64-out \ + custom-response.json + ``` + +4. **View CloudWatch logs**: + ```bash + aws logs filter-log-events \ + --log-group-name /aws/lambda/hello-world-managed-instances \ + --start-time $(date -d '5 minutes ago' +%s)000 + ``` + +### AWS Console Testing + +1. Navigate to the Lambda service in the AWS Console +2. Find the function named `hello-world-managed-instances` +3. Create a test event using the payload from `events/hello-world.json` or create a custom payload: + ```json + { + "name": "Your Custom Name" + } + ``` +4. Execute the test and observe the results in the execution logs + +### Expected Response + +The function returns a JSON response with the following structure: + +```json +{ + "response": "Hello AWS Lambda on Managed Instances" +} +``` + +### Monitoring and Observability + +Monitor the function execution through: +- **CloudWatch Logs**: Detailed execution logs with event and response data +- **Lambda Metrics**: Function performance and invocation statistics +- **CloudWatch Metrics**: Custom metrics and alarms for monitoring + +## Inspecting Lambda Managed Instances Infrastructure + +Lambda Managed Instances provision EC2 instances behind the scenes to provide predictable performance. You can inspect this infrastructure using AWS CLI commands: + +### View Capacity Provider Details + +```bash +aws lambda get-capacity-provider --capacity-provider-name lambda-capacity-provider +``` + +This shows: +- Capacity provider ARN and state +- VPC configuration (subnets and security groups) +- Instance requirements (architecture, scaling mode) +- IAM roles and permissions + +### List Associated EC2 Instances + +```bash +aws ec2 describe-instances \ + --filters "Name=tag:aws:lambda:capacity-provider,Values=arn:aws:lambda:*:capacity-provider:lambda-capacity-provider" \ + --query 'Reservations[*].Instances[*].[InstanceId,InstanceType,State.Name,LaunchTime,SubnetId,PrivateIpAddress]' \ + --output table +``` + +This displays: +- Instance IDs and types +- Current state (running, pending, terminated) +- Launch times and subnet distribution +- Private IP addresses within the VPC + +**Note**: For a complete list of supported EC2 instance types for Lambda Managed Instances and their pricing, see the [AWS Lambda Pricing page](https://aws.amazon.com/lambda/pricing/). + +### Understanding Instance Behavior + +**Auto-scaling**: Instances are automatically created and terminated based on function demand +- **Scale-up**: New instances launch when function invocation increases +- **Scale-down**: Unused instances terminate after periods of low activity +- **Multi-AZ**: Instances are distributed across availability zones for high availability + +**Instance Lifecycle**: +- Instances typically launch within 1-2 minutes of stack deployment +- They remain running to provide immediate function execution +- AWS manages all instance lifecycle operations automatically + +### Automated Testing + +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. + +## Regional Availability + +This stack will deploy to your default AWS region. Before deploying, please verify that 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 [Lambda Managed Instances documentation](https://docs.aws.amazon.com/lambda/latest/dg/lambda-managed-instances.html). + +## Cleanup + +1. Delete the stack + ```bash + cdk destroy + ``` +1. Confirm the stack has been deleted by checking the AWS CloudFormation console or running: + ```bash + aws cloudformation describe-stacks --stack-name lambda-managed-instances + ``` + +---- +Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. + +SPDX-License-Identifier: MIT-0 \ No newline at end of file diff --git a/lambda-managed-instances-cdk/bin/app.ts b/lambda-managed-instances-cdk/bin/app.ts new file mode 100644 index 0000000000..40463eac68 --- /dev/null +++ b/lambda-managed-instances-cdk/bin/app.ts @@ -0,0 +1,13 @@ +#!/usr/bin/env node +import { App } from 'aws-cdk-lib/core'; +import { DemoStack } from '../lib/demo-stack'; + +const app = new App(); +new DemoStack(app, 'LambdaManagedInstancesDemo', { + stackName: 'lambda-managed-instances', + env: { + account: process.env.CDK_DEFAULT_ACCOUNT, + region: process.env.CDK_DEFAULT_REGION + }, + description: 'Simple Hello World Lambda function running on Lambda Managed Instances', +}); \ No newline at end of file diff --git a/lambda-managed-instances-cdk/cdk.json b/lambda-managed-instances-cdk/cdk.json new file mode 100644 index 0000000000..5045f9c6aa --- /dev/null +++ b/lambda-managed-instances-cdk/cdk.json @@ -0,0 +1,70 @@ +{ + "app": "npx ts-node --prefer-ts-exts bin/app.ts", + "watch": { + "include": [ + "**" + ], + "exclude": [ + "README.md", + "cdk*.json", + "**/*.d.ts", + "**/*.js", + "tsconfig.json", + "package*.json", + "yarn.lock", + "node_modules", + "test" + ] + }, + "context": { + "@aws-cdk/aws-lambda:recognizeLayerVersion": true, + "@aws-cdk/core:checkSecretUsage": true, + "@aws-cdk/core:target-partitions": [ + "aws", + "aws-cn" + ], + "@aws-cdk-containers/ecs-service-extensions:enableDefaultLogDriver": true, + "@aws-cdk/aws-ec2:uniqueImdsv2TemplateName": true, + "@aws-cdk/aws-ecs:arnFormatIncludesClusterName": true, + "@aws-cdk/aws-iam:minimizePolicies": true, + "@aws-cdk/core:validateSnapshotRemovalPolicy": true, + "@aws-cdk/aws-codepipeline:crossAccountKeyAliasStackSafeResourceName": true, + "@aws-cdk/aws-s3:createDefaultLoggingPolicy": true, + "@aws-cdk/aws-sns-subscriptions:restrictSqsDescryption": true, + "@aws-cdk/aws-apigateway:disableCloudWatchRole": true, + "@aws-cdk/core:enablePartitionLiterals": true, + "@aws-cdk/aws-events:eventsTargetQueueSameAccount": true, + "@aws-cdk/aws-iam:standardizedServicePrincipals": true, + "@aws-cdk/aws-ecs:disableExplicitDeploymentControllerForCircuitBreaker": true, + "@aws-cdk/aws-iam:importedRoleStackSafeDefaultPolicyName": true, + "@aws-cdk/aws-s3:serverAccessLogsUseBucketPolicy": true, + "@aws-cdk/aws-route53-patters:useCertificate": true, + "@aws-cdk/customresources:installLatestAwsSdkDefault": false, + "@aws-cdk/aws-rds:databaseProxyUniqueResourceName": true, + "@aws-cdk/aws-codedeploy:removeAlarmsFromDeploymentGroup": true, + "@aws-cdk/aws-apigateway:authorizerChangeDeploymentLogicalId": true, + "@aws-cdk/aws-ec2:launchTemplateDefaultUserData": true, + "@aws-cdk/aws-secretsmanager:useAttachedSecretResourcePolicyForSecretTargetAttachments": true, + "@aws-cdk/aws-redshift:columnId": true, + "@aws-cdk/aws-stepfunctions-tasks:enableLogging": true, + "@aws-cdk/aws-ec2:restrictDefaultSecurityGroup": true, + "@aws-cdk/aws-apigateway:requestValidatorUniqueId": true, + "@aws-cdk/aws-kms:aliasNameRef": true, + "@aws-cdk/aws-autoscaling:generateLaunchTemplateInsteadOfLaunchConfig": true, + "@aws-cdk/core:includePrefixInUniqueNameGeneration": true, + "@aws-cdk/aws-efs:denyAnonymousAccess": true, + "@aws-cdk/aws-opensearchservice:enableLogging": true, + "@aws-cdk/aws-normlizer:disable": true, + "@aws-cdk/aws-lambda:recognizeVersionProps": true, + "@aws-cdk/aws-cloudfront:defaultSecurityPolicyTLSv1.2_2021": true, + "@aws-cdk/core:stackRelativeExports": true, + "@aws-cdk/aws-rds:lowercaseDbIdentifier": true, + "@aws-cdk/aws-efs:mountTargetOrderInsensitiveLogicalId": true, + "@aws-cdk/aws-rds:generateSecretManagerSecretName": true, + "@aws-cdk/aws-ecs-patterns:removeDefaultDesiredCount": true, + "@aws-cdk/aws-rds:auroraClusterChangeScopeOfInstanceParameterGroupWithEachParameters": true, + "@aws-cdk/aws-appsync:useArnForSourceApiAssociationIdentifier": true, + "@aws-cdk/aws-rds:preventRenderingDeprecatedCredentials": true, + "@aws-cdk/aws-codepipeline-actions:useNewDefaultBranchForSourceAction": true + } +} \ No newline at end of file diff --git a/lambda-managed-instances-cdk/events/hello-world.json b/lambda-managed-instances-cdk/events/hello-world.json new file mode 100644 index 0000000000..3d0c51d83d --- /dev/null +++ b/lambda-managed-instances-cdk/events/hello-world.json @@ -0,0 +1,3 @@ +{ + "name": "AWS Lambda on Managed Instances" +} \ No newline at end of file diff --git a/lambda-managed-instances-cdk/example-pattern.json b/lambda-managed-instances-cdk/example-pattern.json new file mode 100644 index 0000000000..4b661d85bc --- /dev/null +++ b/lambda-managed-instances-cdk/example-pattern.json @@ -0,0 +1,66 @@ +{ + "title": "Lambda Hello World on Lambda Managed Instances", + "description": "Deploy a simple Hello World Lambda function on Lambda Managed Instances using AWS CDK", + "language": "TypeScript", + "level": "200", + "framework": "CDK", + "introBox": { + "headline": "How it works", + "text": [ + "This pattern demonstrates how to deploy a simple Hello World Lambda function running on Lambda Managed Instances using AWS CDK.", + "Lambda Managed Instances provide predictable performance and reduced cold starts for your Lambda functions by pre-warming execution environments.", + "The Hello World function accepts an event with a name parameter and returns a simple JSON response with a greeting message." + ] + }, + "gitHub": { + "template": { + "repoURL": "https://github.com/aws-samples/serverless-patterns/tree/main/lambda-managed-instances-cdk", + "templateURL": "serverless-patterns/lambda-managed-instances-cdk", + "projectFolder": "lambda-managed-instances-cdk", + "templateFile": "lib/demo-stack.ts" + } + }, + "resources": { + "bullets": [ + { + "text": "Lambda Managed Instances documentation", + "link": "https://docs.aws.amazon.com/lambda/latest/dg/lambda-managed-instances.html" + }, + { + "text": "AWS Lambda Pricing (supported instance types)", + "link": "https://aws.amazon.com/lambda/pricing/" + }, + { + "text": "AWS Lambda Developer Guide", + "link": "https://docs.aws.amazon.com/lambda/latest/dg/" + }, + { + "text": "AWS CDK Developer Guide", + "link": "https://docs.aws.amazon.com/cdk/latest/guide/" + } + ] + }, + "deploy": { + "text": [ + "npm install", + "cdk deploy" + ] + }, + "testing": { + "text": [ + "See the GitHub repo for detailed testing instructions." + ] + }, + "cleanup": { + "text": [ + "Delete the stack: cdk destroy." + ] + }, + "authors": [ + { + "name": "Dmitry Gulin", + "bio": "Senior Delivery Consultant, AWS.", + "linkedin": "dmitry-gulin" + } + ] +} \ No newline at end of file diff --git a/lambda-managed-instances-cdk/lambda/hello-world.mts b/lambda-managed-instances-cdk/lambda/hello-world.mts new file mode 100644 index 0000000000..aa5c8c529f --- /dev/null +++ b/lambda-managed-instances-cdk/lambda/hello-world.mts @@ -0,0 +1,24 @@ +import { Handler } from 'aws-lambda'; +import { Logger } from '@aws-lambda-powertools/logger'; + +const logger = new Logger(); + +interface Event { + name: string; +} + +interface Response { + response: string; +} + +export const handler: Handler = async (event) => { + logger.logEventIfEnabled(event) + + const name = event.name || 'World'; + + const response = { + response: `Hello ${name}` + }; + + return response; +}; \ No newline at end of file diff --git a/lambda-managed-instances-cdk/lib/demo-stack.ts b/lambda-managed-instances-cdk/lib/demo-stack.ts new file mode 100644 index 0000000000..697f122524 --- /dev/null +++ b/lambda-managed-instances-cdk/lib/demo-stack.ts @@ -0,0 +1,47 @@ +import { Stack, StackProps, CfnOutput } from 'aws-cdk-lib/core'; +import { NodejsFunction, OutputFormat } from 'aws-cdk-lib/aws-lambda-nodejs'; +import { Architecture, CapacityProvider, Runtime, LoggingFormat } from 'aws-cdk-lib/aws-lambda'; +import { Construct } from 'constructs'; +import { SecurityGroup, Vpc } from 'aws-cdk-lib/aws-ec2'; + +export class DemoStack extends Stack { + constructor(scope: Construct, id: string, props?: StackProps) { + super(scope, id, props); + + const helloWorldFunction = new NodejsFunction(this, 'HelloWorldFunction', { + entry: 'lambda/hello-world.mts', + handler: 'handler', + runtime: Runtime.NODEJS_24_X, + architecture: Architecture.ARM_64, + functionName: 'hello-world-managed-instances', + description: 'Simple Hello World Lambda function on Managed Instances', + loggingFormat: LoggingFormat.JSON, + bundling: { + format: OutputFormat.ESM, + mainFields: ['module', 'main'], + }, + }); + + const vpc = new Vpc(this, 'LambdaManagedInstancesVPC'); + const securityGroup = new SecurityGroup(this, 'SecurityGroup', { vpc }); + + const capacityProvider = new CapacityProvider(this, 'LambdaCapacityProvider', { + capacityProviderName: 'lambda-capacity-provider', + subnets: vpc.privateSubnets, + securityGroups: [securityGroup], + architectures: [Architecture.ARM_64], + }); + + capacityProvider.addFunction(helloWorldFunction); + + new CfnOutput(this, 'FunctionName', { + value: helloWorldFunction.functionName, + description: 'Lambda function name for CLI invocation', + }); + + new CfnOutput(this, 'FunctionArn', { + value: helloWorldFunction.functionArn, + description: 'Lambda function ARN', + }); + } +} \ No newline at end of file diff --git a/lambda-managed-instances-cdk/package.json b/lambda-managed-instances-cdk/package.json new file mode 100644 index 0000000000..494b508b31 --- /dev/null +++ b/lambda-managed-instances-cdk/package.json @@ -0,0 +1,24 @@ +{ + "name": "lambda-managed-instances-cdk", + "version": "0.1.0", + "bin": { + "lambda-managed-instances-cdk": "bin/app.js" + }, + "scripts": { + "watch": "tsc -w", + "cdk": "cdk" + }, + "devDependencies": { + "@types/aws-lambda": "^8.10.159", + "@types/node": "^25.0.0", + "aws-cdk": "2.1034.0", + "esbuild": "^0.27.1", + "ts-node": "^10.9.2", + "typescript": "~5.9.3" + }, + "dependencies": { + "aws-cdk-lib": "2.232.1", + "constructs": "^10.4.4", + "@aws-lambda-powertools/logger": "^2.30.0" + } +} \ No newline at end of file diff --git a/lambda-managed-instances-cdk/test-lambda.sh b/lambda-managed-instances-cdk/test-lambda.sh new file mode 100755 index 0000000000..da6b64ef4e --- /dev/null +++ b/lambda-managed-instances-cdk/test-lambda.sh @@ -0,0 +1,118 @@ +#!/bin/bash + +# Test script for Hello World Lambda function on Managed Instances +# Usage: ./test-lambda.sh [profile] + +set -e + +# Configuration +FUNCTION_NAME="hello-world-managed-instances" +PROFILE=${1:-default} +EVENT_FILE="events/hello-world.json" + +# Colors for output +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +BLUE='\033[0;34m' +NC='\033[0m' # No Color + +echo -e "${BLUE}=== Testing Hello World Lambda Function on Managed Instances ===${NC}" +echo -e "${YELLOW}Function: ${FUNCTION_NAME}${NC}" +echo -e "${YELLOW}Profile: ${PROFILE}${NC}" +echo "" + +# Check if event file exists +if [ ! -f "$EVENT_FILE" ]; then + echo -e "${RED}Error: Event file $EVENT_FILE not found${NC}" + exit 1 +fi + +# Test 1: Basic invocation with sample event +echo -e "${BLUE}Test 1: Basic invocation with sample event${NC}" +echo "Invoking function with event from $EVENT_FILE..." + +aws lambda invoke \ + --function-name "$FUNCTION_NAME" \ + --payload file://"$EVENT_FILE" \ + --cli-binary-format raw-in-base64-out \ + --profile "$PROFILE" \ + response.json + +if [ $? -eq 0 ]; then + echo -e "${GREEN}✓ Function invoked successfully${NC}" + echo -e "${YELLOW}Response:${NC}" + cat response.json | jq '.' + echo "" +else + echo -e "${RED}✗ Function invocation failed${NC}" + exit 1 +fi + +# Test 2: View recent CloudWatch logs +echo -e "${BLUE}Test 2: Recent CloudWatch logs${NC}" +echo "Fetching recent logs from CloudWatch..." + +LOG_GROUP="/aws/lambda/$FUNCTION_NAME" +START_TIME=$(date -v-5M +%s)000 + +aws logs filter-log-events \ + --log-group-name "$LOG_GROUP" \ + --start-time "$START_TIME" \ + --profile "$PROFILE" \ + --query 'events[*].[timestamp,message]' \ + --output table + +# Test 3: View Lambda Managed Instances (EC2 instances) +echo -e "${BLUE}Test 3: Lambda Managed Instances (EC2 instances)${NC}" +echo "Checking capacity provider and associated EC2 instances..." + +echo -e "${YELLOW}Capacity Provider Details:${NC}" +aws lambda get-capacity-provider --capacity-provider-name lambda-capacity-provider --query 'CapacityProvider.[CapacityProviderArn,State,InstanceRequirements.Architectures[0],CapacityProviderScalingConfig.ScalingMode]' --output table --profile "$PROFILE" + +echo -e "${YELLOW}EC2 Instances provisioned for Lambda Managed Instances:${NC}" +# Get subnet IDs from capacity provider +SUBNET_IDS=$(aws lambda get-capacity-provider --capacity-provider-name lambda-capacity-provider --query 'CapacityProvider.VpcConfig.SubnetIds' --output text --profile "$PROFILE" | tr '\t' ',') +SECURITY_GROUP_ID=$(aws lambda get-capacity-provider --capacity-provider-name lambda-capacity-provider --query 'CapacityProvider.VpcConfig.SecurityGroupIds[0]' --output text --profile "$PROFILE") + +# List EC2 instances tagged with this capacity provider +CAPACITY_PROVIDER_ARN="arn:aws:lambda:us-west-2:220537809147:capacity-provider:lambda-capacity-provider" +aws ec2 describe-instances \ + --filters "Name=tag:aws:lambda:capacity-provider,Values=$CAPACITY_PROVIDER_ARN" \ + --query 'Reservations[*].Instances[*].[InstanceId,InstanceType,State.Name,LaunchTime,SubnetId,PrivateIpAddress]' \ + --output table \ + --profile "$PROFILE" + +# Also show instance count +INSTANCE_COUNT=$(aws ec2 describe-instances \ + --filters "Name=tag:aws:lambda:capacity-provider,Values=$CAPACITY_PROVIDER_ARN" "Name=instance-state-name,Values=running" \ + --query 'length(Reservations[*].Instances[*])' \ + --output text \ + --profile "$PROFILE") + +echo "Currently running instances: $INSTANCE_COUNT" + +echo "" +echo -e "${GREEN}=== Testing completed successfully! ===${NC}" +echo "" +echo -e "${YELLOW}Useful commands for further testing:${NC}" +echo "1. View function details:" +echo " aws lambda get-function --function-name $FUNCTION_NAME --profile $PROFILE" +echo "" +echo "2. View function configuration:" +echo " aws lambda get-function-configuration --function-name $FUNCTION_NAME --profile $PROFILE" +echo "" +echo "3. View CloudWatch logs:" +echo " aws logs filter-log-events --log-group-name $LOG_GROUP --start-time \$(date -d '10 minutes ago' +%s)000 --profile $PROFILE" +echo "" +echo "4. Custom invocation:" +echo " echo '{\"name\":\"Your Name\"}' | aws lambda invoke --function-name $FUNCTION_NAME --payload file:///dev/stdin --cli-binary-format raw-in-base64-out --profile $PROFILE output.json" +echo "" +echo "5. View capacity provider details:" +echo " aws lambda get-capacity-provider --capacity-provider-name lambda-capacity-provider --profile $PROFILE" +echo "" +echo "6. List EC2 instances for managed instances:" +echo " aws ec2 describe-instances --filters \"Name=tag:aws:lambda:capacity-provider,Values=arn:aws:lambda:*:capacity-provider:lambda-capacity-provider\" --profile $PROFILE" + +# Cleanup temporary files +rm -f response.json \ No newline at end of file diff --git a/lambda-managed-instances-cdk/tsconfig.json b/lambda-managed-instances-cdk/tsconfig.json new file mode 100644 index 0000000000..3a136ad6ca --- /dev/null +++ b/lambda-managed-instances-cdk/tsconfig.json @@ -0,0 +1,30 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "commonjs", + "lib": [ + "es2022" + ], + "declaration": true, + "strict": true, + "noImplicitAny": true, + "strictNullChecks": true, + "noImplicitThis": true, + "alwaysStrict": true, + "noUnusedLocals": false, + "noUnusedParameters": false, + "noImplicitReturns": true, + "noFallthroughCasesInSwitch": false, + "inlineSourceMap": true, + "inlineSources": true, + "experimentalDecorators": true, + "strictPropertyInitialization": false, + "typeRoots": [ + "./node_modules/@types" + ] + }, + "exclude": [ + "node_modules", + "cdk.out" + ] +} \ No newline at end of file From 9a608769ea28c83213e0ab473035c0d5cba95181 Mon Sep 17 00:00:00 2001 From: Dmitry Gulin Date: Tue, 16 Dec 2025 10:40:37 -0500 Subject: [PATCH 2/8] NPM packages updates and a few renames so that this stack doesn't conflict with the TF one. --- lambda-managed-instances-cdk/README.md | 25 +++++++++++++------ lambda-managed-instances-cdk/bin/app.ts | 2 +- .../lib/demo-stack.ts | 21 +++++++++++++--- lambda-managed-instances-cdk/package.json | 6 ++--- lambda-managed-instances-cdk/test-lambda.sh | 4 +-- 5 files changed, 41 insertions(+), 17 deletions(-) diff --git a/lambda-managed-instances-cdk/README.md b/lambda-managed-instances-cdk/README.md index 0ff891847b..e1322a395a 100644 --- a/lambda-managed-instances-cdk/README.md +++ b/lambda-managed-instances-cdk/README.md @@ -58,6 +58,13 @@ The Lambda function is a simple Hello World implementation that: - Uses AWS Lambda PowerTools for efficient event logging - Demonstrates minimal Lambda function structure using the Handler type +### CloudWatch Log Group +The pattern includes a dedicated CloudWatch log group with: +- **Custom log group name**: `/demo/lambda/hello-world-managed-instances-cdk` +- **Retention period**: 2 weeks (14 days) to manage storage costs +- **Automatic cleanup**: Configured with `RemovalPolicy.DESTROY` to be deleted when the stack is destroyed +- **Direct integration**: The Lambda function is configured to use this specific log group + ## Testing After deployment, you can test the Lambda function using AWS CLI or AWS Console. @@ -67,7 +74,7 @@ After deployment, you can test the Lambda function using AWS CLI or AWS Console. 1. **Basic function invocation**: ```bash aws lambda invoke \ - --function-name hello-world-managed-instances \ + --function-name hello-world-managed-instances-cdk \ --payload file://events/hello-world.json \ --cli-binary-format raw-in-base64-out \ response.json @@ -81,7 +88,7 @@ After deployment, you can test the Lambda function using AWS CLI or AWS Console. 3. **Custom name invocation**: ```bash echo '{"name":"Lambda Managed Instances"}' | aws lambda invoke \ - --function-name hello-world-managed-instances \ + --function-name hello-world-managed-instances-cdk \ --payload file:///dev/stdin \ --cli-binary-format raw-in-base64-out \ custom-response.json @@ -90,14 +97,14 @@ After deployment, you can test the Lambda function using AWS CLI or AWS Console. 4. **View CloudWatch logs**: ```bash aws logs filter-log-events \ - --log-group-name /aws/lambda/hello-world-managed-instances \ + --log-group-name /demo/lambda/hello-world-managed-instances-cdk \ --start-time $(date -d '5 minutes ago' +%s)000 ``` ### AWS Console Testing 1. Navigate to the Lambda service in the AWS Console -2. Find the function named `hello-world-managed-instances` +2. Find the function named `hello-world-managed-instances-cdk` 3. Create a test event using the payload from `events/hello-world.json` or create a custom payload: ```json { @@ -119,10 +126,12 @@ The function returns a JSON response with the following structure: ### Monitoring and Observability Monitor the function execution through: -- **CloudWatch Logs**: Detailed execution logs with event and response data +- **CloudWatch Logs**: Detailed execution logs with event and response data in the dedicated log group - **Lambda Metrics**: Function performance and invocation statistics - **CloudWatch Metrics**: Custom metrics and alarms for monitoring +The stack outputs include the log group name for easy reference when setting up monitoring dashboards or log analysis tools. + ## Inspecting Lambda Managed Instances Infrastructure Lambda Managed Instances provision EC2 instances behind the scenes to provide predictable performance. You can inspect this infrastructure using AWS CLI commands: @@ -130,7 +139,7 @@ Lambda Managed Instances provision EC2 instances behind the scenes to provide pr ### View Capacity Provider Details ```bash -aws lambda get-capacity-provider --capacity-provider-name lambda-capacity-provider +aws lambda get-capacity-provider --capacity-provider-name lambda-capacity-provider-cdk ``` This shows: @@ -143,7 +152,7 @@ This shows: ```bash aws ec2 describe-instances \ - --filters "Name=tag:aws:lambda:capacity-provider,Values=arn:aws:lambda:*:capacity-provider:lambda-capacity-provider" \ + --filters "Name=tag:aws:lambda:capacity-provider,Values=arn:aws:lambda:*:capacity-provider:lambda-capacity-provider-cdk" \ --query 'Reservations[*].Instances[*].[InstanceId,InstanceType,State.Name,LaunchTime,SubnetId,PrivateIpAddress]' \ --output table ``` @@ -184,7 +193,7 @@ This stack will deploy to your default AWS region. Before deploying, please veri ``` 1. Confirm the stack has been deleted by checking the AWS CloudFormation console or running: ```bash - aws cloudformation describe-stacks --stack-name lambda-managed-instances + aws cloudformation describe-stacks --stack-name lambda-managed-instances-cdk ``` ---- diff --git a/lambda-managed-instances-cdk/bin/app.ts b/lambda-managed-instances-cdk/bin/app.ts index 40463eac68..515d42b285 100644 --- a/lambda-managed-instances-cdk/bin/app.ts +++ b/lambda-managed-instances-cdk/bin/app.ts @@ -4,7 +4,7 @@ import { DemoStack } from '../lib/demo-stack'; const app = new App(); new DemoStack(app, 'LambdaManagedInstancesDemo', { - stackName: 'lambda-managed-instances', + stackName: 'lambda-managed-instances-cdk', env: { account: process.env.CDK_DEFAULT_ACCOUNT, region: process.env.CDK_DEFAULT_REGION diff --git a/lambda-managed-instances-cdk/lib/demo-stack.ts b/lambda-managed-instances-cdk/lib/demo-stack.ts index 697f122524..cc0e3459b9 100644 --- a/lambda-managed-instances-cdk/lib/demo-stack.ts +++ b/lambda-managed-instances-cdk/lib/demo-stack.ts @@ -1,21 +1,31 @@ -import { Stack, StackProps, CfnOutput } from 'aws-cdk-lib/core'; +import { Stack, StackProps, CfnOutput, RemovalPolicy } from 'aws-cdk-lib/core'; import { NodejsFunction, OutputFormat } from 'aws-cdk-lib/aws-lambda-nodejs'; import { Architecture, CapacityProvider, Runtime, LoggingFormat } from 'aws-cdk-lib/aws-lambda'; import { Construct } from 'constructs'; import { SecurityGroup, Vpc } from 'aws-cdk-lib/aws-ec2'; +import { LogGroup, RetentionDays } from 'aws-cdk-lib/aws-logs'; export class DemoStack extends Stack { constructor(scope: Construct, id: string, props?: StackProps) { super(scope, id, props); + const functionName = 'hello-world-managed-instances-cdk'; + + const logGroup = new LogGroup(this, 'DemoLogGroup', { + logGroupName: `/demo/lambda/${functionName}`, + retention: RetentionDays.TWO_WEEKS, + removalPolicy: RemovalPolicy.DESTROY, + }); + const helloWorldFunction = new NodejsFunction(this, 'HelloWorldFunction', { entry: 'lambda/hello-world.mts', handler: 'handler', runtime: Runtime.NODEJS_24_X, architecture: Architecture.ARM_64, - functionName: 'hello-world-managed-instances', + functionName, description: 'Simple Hello World Lambda function on Managed Instances', loggingFormat: LoggingFormat.JSON, + logGroup, bundling: { format: OutputFormat.ESM, mainFields: ['module', 'main'], @@ -26,7 +36,7 @@ export class DemoStack extends Stack { const securityGroup = new SecurityGroup(this, 'SecurityGroup', { vpc }); const capacityProvider = new CapacityProvider(this, 'LambdaCapacityProvider', { - capacityProviderName: 'lambda-capacity-provider', + capacityProviderName: 'lambda-capacity-provider-cdk', subnets: vpc.privateSubnets, securityGroups: [securityGroup], architectures: [Architecture.ARM_64], @@ -43,5 +53,10 @@ export class DemoStack extends Stack { value: helloWorldFunction.functionArn, description: 'Lambda function ARN', }); + + new CfnOutput(this, 'LogGroupName', { + value: logGroup.logGroupName, + description: 'CloudWatch Log Group name', + }); } } \ No newline at end of file diff --git a/lambda-managed-instances-cdk/package.json b/lambda-managed-instances-cdk/package.json index 494b508b31..af13445be3 100644 --- a/lambda-managed-instances-cdk/package.json +++ b/lambda-managed-instances-cdk/package.json @@ -10,14 +10,14 @@ }, "devDependencies": { "@types/aws-lambda": "^8.10.159", - "@types/node": "^25.0.0", - "aws-cdk": "2.1034.0", + "@types/node": "^25.0.2", + "aws-cdk": "2.1100.0", "esbuild": "^0.27.1", "ts-node": "^10.9.2", "typescript": "~5.9.3" }, "dependencies": { - "aws-cdk-lib": "2.232.1", + "aws-cdk-lib": "2.232.2", "constructs": "^10.4.4", "@aws-lambda-powertools/logger": "^2.30.0" } diff --git a/lambda-managed-instances-cdk/test-lambda.sh b/lambda-managed-instances-cdk/test-lambda.sh index da6b64ef4e..c876dd4f96 100755 --- a/lambda-managed-instances-cdk/test-lambda.sh +++ b/lambda-managed-instances-cdk/test-lambda.sh @@ -6,7 +6,7 @@ set -e # Configuration -FUNCTION_NAME="hello-world-managed-instances" +FUNCTION_NAME="hello-world-managed-instances-cdk" PROFILE=${1:-default} EVENT_FILE="events/hello-world.json" @@ -53,7 +53,7 @@ fi echo -e "${BLUE}Test 2: Recent CloudWatch logs${NC}" echo "Fetching recent logs from CloudWatch..." -LOG_GROUP="/aws/lambda/$FUNCTION_NAME" +LOG_GROUP="/demo/lambda/$FUNCTION_NAME" START_TIME=$(date -v-5M +%s)000 aws logs filter-log-events \ From d62484a8f0004d8b6b7fa8bd83b08898ea4d6c36 Mon Sep 17 00:00:00 2001 From: Dmitry Gulin Date: Wed, 21 Jan 2026 17:09:44 -0500 Subject: [PATCH 3/8] address code review comment --- lambda-managed-instances-cdk/test-lambda.sh | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lambda-managed-instances-cdk/test-lambda.sh b/lambda-managed-instances-cdk/test-lambda.sh index c876dd4f96..221391bd38 100755 --- a/lambda-managed-instances-cdk/test-lambda.sh +++ b/lambda-managed-instances-cdk/test-lambda.sh @@ -76,7 +76,8 @@ SUBNET_IDS=$(aws lambda get-capacity-provider --capacity-provider-name lambda-ca SECURITY_GROUP_ID=$(aws lambda get-capacity-provider --capacity-provider-name lambda-capacity-provider --query 'CapacityProvider.VpcConfig.SecurityGroupIds[0]' --output text --profile "$PROFILE") # List EC2 instances tagged with this capacity provider -CAPACITY_PROVIDER_ARN="arn:aws:lambda:us-west-2:220537809147:capacity-provider:lambda-capacity-provider" +# Get the capacity provider ARN dynamically +CAPACITY_PROVIDER_ARN=$(aws lambda get-capacity-provider --capacity-provider-name lambda-capacity-provider --query 'CapacityProvider.CapacityProviderArn' --output text --profile "$PROFILE") aws ec2 describe-instances \ --filters "Name=tag:aws:lambda:capacity-provider,Values=$CAPACITY_PROVIDER_ARN" \ --query 'Reservations[*].Instances[*].[InstanceId,InstanceType,State.Name,LaunchTime,SubnetId,PrivateIpAddress]' \ From 0268e87e07e9a8d06946ed65f12e00003b7d9dc6 Mon Sep 17 00:00:00 2001 From: Dmitry Gulin Date: Wed, 21 Jan 2026 17:09:44 -0500 Subject: [PATCH 4/8] address code review comment --- lambda-managed-instances-cdk/test-lambda.sh | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/lambda-managed-instances-cdk/test-lambda.sh b/lambda-managed-instances-cdk/test-lambda.sh index 221391bd38..1979fa63ae 100755 --- a/lambda-managed-instances-cdk/test-lambda.sh +++ b/lambda-managed-instances-cdk/test-lambda.sh @@ -68,16 +68,18 @@ echo -e "${BLUE}Test 3: Lambda Managed Instances (EC2 instances)${NC}" echo "Checking capacity provider and associated EC2 instances..." echo -e "${YELLOW}Capacity Provider Details:${NC}" -aws lambda get-capacity-provider --capacity-provider-name lambda-capacity-provider --query 'CapacityProvider.[CapacityProviderArn,State,InstanceRequirements.Architectures[0],CapacityProviderScalingConfig.ScalingMode]' --output table --profile "$PROFILE" +aws lambda get-capacity-provider --capacity-provider-name lambda-capacity-provider-cdk --query 'CapacityProvider.[CapacityProviderArn,State,InstanceRequirements.Architectures[0],CapacityProviderScalingConfig.ScalingMode]' --output table --profile "$PROFILE" echo -e "${YELLOW}EC2 Instances provisioned for Lambda Managed Instances:${NC}" # Get subnet IDs from capacity provider -SUBNET_IDS=$(aws lambda get-capacity-provider --capacity-provider-name lambda-capacity-provider --query 'CapacityProvider.VpcConfig.SubnetIds' --output text --profile "$PROFILE" | tr '\t' ',') -SECURITY_GROUP_ID=$(aws lambda get-capacity-provider --capacity-provider-name lambda-capacity-provider --query 'CapacityProvider.VpcConfig.SecurityGroupIds[0]' --output text --profile "$PROFILE") +SUBNET_IDS=$(aws lambda get-capacity-provider --capacity-provider-name lambda-capacity-provider-cdk --query 'CapacityProvider.VpcConfig.SubnetIds' --output text --profile "$PROFILE" | tr '\t' ',') +SECURITY_GROUP_ID=$(aws lambda get-capacity-provider --capacity-provider-name lambda-capacity-provider-cdk --query 'CapacityProvider.VpcConfig.SecurityGroupIds[0]' --output text --profile "$PROFILE") # List EC2 instances tagged with this capacity provider # Get the capacity provider ARN dynamically -CAPACITY_PROVIDER_ARN=$(aws lambda get-capacity-provider --capacity-provider-name lambda-capacity-provider --query 'CapacityProvider.CapacityProviderArn' --output text --profile "$PROFILE") +REGION=$(aws configure get region --profile "$PROFILE") +ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text --profile "$PROFILE") +CAPACITY_PROVIDER_ARN="arn:aws:lambda:${REGION}:${ACCOUNT_ID}:capacity-provider:lambda-capacity-provider-cdk" aws ec2 describe-instances \ --filters "Name=tag:aws:lambda:capacity-provider,Values=$CAPACITY_PROVIDER_ARN" \ --query 'Reservations[*].Instances[*].[InstanceId,InstanceType,State.Name,LaunchTime,SubnetId,PrivateIpAddress]' \ @@ -110,10 +112,10 @@ echo "4. Custom invocation:" echo " echo '{\"name\":\"Your Name\"}' | aws lambda invoke --function-name $FUNCTION_NAME --payload file:///dev/stdin --cli-binary-format raw-in-base64-out --profile $PROFILE output.json" echo "" echo "5. View capacity provider details:" -echo " aws lambda get-capacity-provider --capacity-provider-name lambda-capacity-provider --profile $PROFILE" +echo " aws lambda get-capacity-provider --capacity-provider-name lambda-capacity-provider-cdk --profile $PROFILE" echo "" echo "6. List EC2 instances for managed instances:" -echo " aws ec2 describe-instances --filters \"Name=tag:aws:lambda:capacity-provider,Values=arn:aws:lambda:*:capacity-provider:lambda-capacity-provider\" --profile $PROFILE" +echo " aws ec2 describe-instances --filters \"Name=tag:aws:lambda:capacity-provider,Values=arn:aws:lambda:*:capacity-provider:lambda-capacity-provider-cdk\" --profile $PROFILE" # Cleanup temporary files rm -f response.json \ No newline at end of file From 9cc9f593033a7b0d9b6006a16bfc2db7288b7d35 Mon Sep 17 00:00:00 2001 From: DmitryGulin Date: Thu, 29 Jan 2026 11:57:05 -0500 Subject: [PATCH 5/8] Apply suggestions from code review Co-authored-by: Ben <9841563+bfreiberg@users.noreply.github.com> --- lambda-managed-instances-cdk/README.md | 6 +++--- lambda-managed-instances-cdk/example-pattern.json | 10 +++++----- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/lambda-managed-instances-cdk/README.md b/lambda-managed-instances-cdk/README.md index e1322a395a..839d4f5431 100644 --- a/lambda-managed-instances-cdk/README.md +++ b/lambda-managed-instances-cdk/README.md @@ -1,4 +1,4 @@ -# Lambda Hello World on Lambda Managed Instances +# Hello World on AWS Lambda Managed Instances This pattern demonstrates how to deploy a simple Hello World Lambda function running on Lambda Managed Instances using AWS CDK. Lambda Managed Instances provide predictable performance and reduced cold starts for your Lambda functions. @@ -58,7 +58,7 @@ The Lambda function is a simple Hello World implementation that: - Uses AWS Lambda PowerTools for efficient event logging - Demonstrates minimal Lambda function structure using the Handler type -### CloudWatch Log Group +### Amazon CloudWatch Log Group The pattern includes a dedicated CloudWatch log group with: - **Custom log group name**: `/demo/lambda/hello-world-managed-instances-cdk` - **Retention period**: 2 weeks (14 days) to manage storage costs @@ -197,6 +197,6 @@ This stack will deploy to your default AWS region. Before deploying, please veri ``` ---- -Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved. +Copyright 2026 Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: MIT-0 \ No newline at end of file diff --git a/lambda-managed-instances-cdk/example-pattern.json b/lambda-managed-instances-cdk/example-pattern.json index 4b661d85bc..7cf109a758 100644 --- a/lambda-managed-instances-cdk/example-pattern.json +++ b/lambda-managed-instances-cdk/example-pattern.json @@ -1,13 +1,13 @@ { - "title": "Lambda Hello World on Lambda Managed Instances", - "description": "Deploy a simple Hello World Lambda function on Lambda Managed Instances using AWS CDK", + "title": "Hello World on AWS Lambda Managed Instances", + "description": "Deploy a simple Hello World AWS Lambda function on Lambda Managed Instances using AWS CDK", "language": "TypeScript", "level": "200", - "framework": "CDK", + "framework": "AWS CDK", "introBox": { "headline": "How it works", "text": [ - "This pattern demonstrates how to deploy a simple Hello World Lambda function running on Lambda Managed Instances using AWS CDK.", + "This pattern demonstrates how to deploy a simple Hello World AWS Lambda function running on Lambda Managed Instances using AWS CDK.", "Lambda Managed Instances provide predictable performance and reduced cold starts for your Lambda functions by pre-warming execution environments.", "The Hello World function accepts an event with a name parameter and returns a simple JSON response with a greeting message." ] @@ -23,7 +23,7 @@ "resources": { "bullets": [ { - "text": "Lambda Managed Instances documentation", + "text": "AWS Lambda Managed Instances documentation", "link": "https://docs.aws.amazon.com/lambda/latest/dg/lambda-managed-instances.html" }, { From 1d290b199f4714e115ed9102c4a59f408e4f8adf Mon Sep 17 00:00:00 2001 From: Dmitry Gulin Date: Thu, 29 Jan 2026 12:28:31 -0500 Subject: [PATCH 6/8] docs(core): update README.md and example-pattern.json as requested - Add detailed explanation of Lambda Managed Instances capabilities and benefits - Clarify AWS service branding and terminology throughout documentation - Remove redundant sections and consolidate infrastructure details - Update introductory description with more accurate service overview --- lambda-managed-instances-cdk/README.md | 37 ++++--------------- .../example-pattern.json | 4 +- 2 files changed, 9 insertions(+), 32 deletions(-) diff --git a/lambda-managed-instances-cdk/README.md b/lambda-managed-instances-cdk/README.md index 839d4f5431..b3cc4aa8f7 100644 --- a/lambda-managed-instances-cdk/README.md +++ b/lambda-managed-instances-cdk/README.md @@ -1,12 +1,12 @@ # Hello World on AWS Lambda Managed Instances -This pattern demonstrates how to deploy a simple Hello World Lambda function running on Lambda Managed Instances using AWS CDK. Lambda Managed Instances provide predictable performance and reduced cold starts for your Lambda functions. +This pattern demonstrates how to deploy a simple Hello World Lambda function running on AWS Lambda Managed Instances using AWS CDK. 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. Learn more about this pattern at Serverless Land Patterns: https://serverlessland.com/patterns/lambda-managed-instances-cdk 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**. These instances will incur charges immediately upon deployment, regardless of your Free Tier status. +**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. ## Requirements @@ -40,30 +40,7 @@ Important: this application uses various AWS services and there are costs associ ## How it works -This pattern demonstrates the deployment of a simple Lambda function on Lambda Managed Instances: - -### Lambda Managed Instances -[Lambda Managed Instances](https://docs.aws.amazon.com/lambda/latest/dg/lambda-managed-instances.html) provide: -- Predictable performance with pre-warmed execution environments -- Reduced cold start latency -- Consistent execution characteristics -- Better resource utilization for frequently invoked functions - -The underlying EC2 infrastructure can be inspected using AWS CLI commands to understand how managed instances work (see "Inspecting Lambda Managed Instances Infrastructure" section below). - -### Hello World Function -The Lambda function is a simple Hello World implementation that: -- Accepts an event with a name parameter -- Returns a JSON response with a greeting message -- Uses AWS Lambda PowerTools for efficient event logging -- Demonstrates minimal Lambda function structure using the Handler type - -### Amazon CloudWatch Log Group -The pattern includes a dedicated CloudWatch log group with: -- **Custom log group name**: `/demo/lambda/hello-world-managed-instances-cdk` -- **Retention period**: 2 weeks (14 days) to manage storage costs -- **Automatic cleanup**: Configured with `RemovalPolicy.DESTROY` to be deleted when the stack is destroyed -- **Direct integration**: The Lambda function is configured to use this specific log group +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 function accepts an event with a name parameter and returns a greeting message, with execution logs captured in a dedicated CloudWatch log group. ## Testing @@ -132,9 +109,9 @@ Monitor the function execution through: The stack outputs include the log group name for easy reference when setting up monitoring dashboards or log analysis tools. -## Inspecting Lambda Managed Instances Infrastructure +## Inspecting AWS Lambda Managed Instances Infrastructure -Lambda Managed Instances provision EC2 instances behind the scenes to provide predictable performance. You can inspect this infrastructure using AWS CLI commands: +AWS Lambda Managed Instances provision EC2 instances behind the scenes to run your Lambda functions. You can inspect this infrastructure using AWS CLI commands: ### View Capacity Provider Details @@ -163,7 +140,7 @@ This displays: - Launch times and subnet distribution - Private IP addresses within the VPC -**Note**: For a complete list of supported EC2 instance types for Lambda Managed Instances and their pricing, see the [AWS Lambda Pricing page](https://aws.amazon.com/lambda/pricing/). +**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/). ### Understanding Instance Behavior @@ -183,7 +160,7 @@ The included test script (`./test-lambda.sh`) automatically inspects both the ca ## Regional Availability -This stack will deploy to your default AWS region. Before deploying, please verify that 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 [Lambda Managed Instances documentation](https://docs.aws.amazon.com/lambda/latest/dg/lambda-managed-instances.html). +This stack will deploy to your default AWS region. 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). ## Cleanup diff --git a/lambda-managed-instances-cdk/example-pattern.json b/lambda-managed-instances-cdk/example-pattern.json index 7cf109a758..4529054ac9 100644 --- a/lambda-managed-instances-cdk/example-pattern.json +++ b/lambda-managed-instances-cdk/example-pattern.json @@ -7,8 +7,8 @@ "introBox": { "headline": "How it works", "text": [ - "This pattern demonstrates how to deploy a simple Hello World AWS Lambda function running on Lambda Managed Instances using AWS CDK.", - "Lambda Managed Instances provide predictable performance and reduced cold starts for your Lambda functions by pre-warming execution environments.", + "This pattern demonstrates how to deploy a simple Hello World AWS Lambda function running on AWS Lambda Managed Instances using AWS CDK.", + "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.", "The Hello World function accepts an event with a name parameter and returns a simple JSON response with a greeting message." ] }, From a2b934d99d4d8f2a8428681b6b174ce07ab084d5 Mon Sep 17 00:00:00 2001 From: Dmitry Gulin Date: Thu, 29 Jan 2026 13:21:46 -0500 Subject: [PATCH 7/8] update NPM packages --- lambda-managed-instances-cdk/package.json | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/lambda-managed-instances-cdk/package.json b/lambda-managed-instances-cdk/package.json index af13445be3..791a92970f 100644 --- a/lambda-managed-instances-cdk/package.json +++ b/lambda-managed-instances-cdk/package.json @@ -9,16 +9,16 @@ "cdk": "cdk" }, "devDependencies": { - "@types/aws-lambda": "^8.10.159", - "@types/node": "^25.0.2", - "aws-cdk": "2.1100.0", - "esbuild": "^0.27.1", + "@types/aws-lambda": "^8.10.160", + "@types/node": "^25.1.0", + "aws-cdk": "2.1104.0", + "esbuild": "^0.27.2", "ts-node": "^10.9.2", "typescript": "~5.9.3" }, "dependencies": { - "aws-cdk-lib": "2.232.2", - "constructs": "^10.4.4", - "@aws-lambda-powertools/logger": "^2.30.0" + "aws-cdk-lib": "2.236.0", + "constructs": "^10.4.5", + "@aws-lambda-powertools/logger": "^2.30.2" } } \ No newline at end of file From 73bffc30a5c639381d0242fe978cd3f6c361efec Mon Sep 17 00:00:00 2001 From: Ben <9841563+bfreiberg@users.noreply.github.com> Date: Sun, 1 Feb 2026 16:44:19 +0100 Subject: [PATCH 8/8] Add final pattern file --- .../lambda-managed-instances-cdk.json | 74 +++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 lambda-managed-instances-cdk/lambda-managed-instances-cdk.json diff --git a/lambda-managed-instances-cdk/lambda-managed-instances-cdk.json b/lambda-managed-instances-cdk/lambda-managed-instances-cdk.json new file mode 100644 index 0000000000..85d099af43 --- /dev/null +++ b/lambda-managed-instances-cdk/lambda-managed-instances-cdk.json @@ -0,0 +1,74 @@ +{ + "title": "Hello World on AWS Lambda Managed Instances", + "description": "Deploy a simple Hello World AWS Lambda function on Lambda Managed Instances using AWS CDK", + "language": "TypeScript", + "level": "200", + "framework": "AWS CDK", + "introBox": { + "headline": "How it works", + "text": [ + "This pattern demonstrates how to deploy a simple Hello World AWS Lambda function running on AWS Lambda Managed Instances using AWS CDK.", + "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.", + "The Hello World function accepts an event with a name parameter and returns a simple JSON response with a greeting message." + ] + }, + "gitHub": { + "template": { + "repoURL": "https://github.com/aws-samples/serverless-patterns/tree/main/lambda-managed-instances-cdk", + "templateURL": "serverless-patterns/lambda-managed-instances-cdk", + "projectFolder": "lambda-managed-instances-cdk", + "templateFile": "lib/demo-stack.ts" + } + }, + "resources": { + "bullets": [ + { + "text": "AWS Lambda Managed Instances documentation", + "link": "https://docs.aws.amazon.com/lambda/latest/dg/lambda-managed-instances.html" + }, + { + "text": "AWS Lambda Pricing (supported instance types)", + "link": "https://aws.amazon.com/lambda/pricing/" + }, + { + "text": "AWS Lambda Developer Guide", + "link": "https://docs.aws.amazon.com/lambda/latest/dg/" + }, + { + "text": "AWS CDK Developer Guide", + "link": "https://docs.aws.amazon.com/cdk/latest/guide/" + } + ] + }, + "deploy": { + "text": [ + "npm install", + "cdk deploy" + ] + }, + "testing": { + "text": [ + "See the GitHub repo for detailed testing instructions." + ] + }, + "cleanup": { + "text": [ + "Delete the stack: cdk destroy." + ] + }, + "authors": [ + { + "name": "Dmitry Gulin", + "bio": "Senior Delivery Consultant, AWS.", + "linkedin": "dmitry-gulin" + } + ], + "patternArch": { + "icon1": { + "x": 50, + "y": 50, + "service": "lambda", + "label": "AWS Lambda Managed Instance" + } + } +}