diff --git a/lambda-managed-instances-cdk/.gitignore b/lambda-managed-instances-cdk/.gitignore new file mode 100644 index 000000000..70e5f6e7a --- /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 000000000..327e660d0 --- /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 000000000..e1322a395 --- /dev/null +++ b/lambda-managed-instances-cdk/README.md @@ -0,0 +1,202 @@ +# 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 + +### 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. + +### AWS CLI Testing + +1. **Basic function invocation**: + ```bash + aws lambda invoke \ + --function-name hello-world-managed-instances-cdk \ + --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-cdk \ + --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 /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-cdk` +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 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: + +### View Capacity Provider Details + +```bash +aws lambda get-capacity-provider --capacity-provider-name lambda-capacity-provider-cdk +``` + +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-cdk" \ + --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-cdk + ``` + +---- +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 000000000..515d42b28 --- /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-cdk', + 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 000000000..5045f9c6a --- /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 000000000..3d0c51d83 --- /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 000000000..4b661d85b --- /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 000000000..aa5c8c529 --- /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 000000000..cc0e3459b --- /dev/null +++ b/lambda-managed-instances-cdk/lib/demo-stack.ts @@ -0,0 +1,62 @@ +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, + description: 'Simple Hello World Lambda function on Managed Instances', + loggingFormat: LoggingFormat.JSON, + logGroup, + 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-cdk', + 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', + }); + + 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 new file mode 100644 index 000000000..af13445be --- /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.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.2", + "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 000000000..c876dd4f9 --- /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-cdk" +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="/demo/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 000000000..3a136ad6c --- /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