### Basic Lambda Function Handler - Node.js, Python, Java Source: https://context7.com/awsdocs/aws-lambda-developer-guide/llms.txt Demonstrates basic Lambda function handlers across Node.js, Python, and Java. These examples showcase event processing, context logging, AWS SDK integration (boto3 for Python, AWS SDK v2 for Java), and AWS X-Ray tracing. They are designed to be integrated with AWS services and follow standard Lambda function structure. ```javascript const AWSXRay = require('aws-xray-sdk-core'); const { LambdaClient, GetAccountSettingsCommand } = require('@aws-sdk/client-lambda'); // Create client outside of handler to reuse across invocations const lambda = AWSXRay.captureAWSv3Client(new LambdaClient()); exports.handler = async function(event, context) { // Process SQS records event.Records.forEach(record => { console.log(record.body); }); // Log environment variables and context console.log('## ENVIRONMENT VARIABLES: ' + JSON.stringify(process.env, null, 2)); console.log('## CONTEXT: ' + JSON.stringify(context, null, 2)); console.log('## EVENT: ' + JSON.stringify(event, null, 2)); // Call Lambda API const response = await lambda.send(new GetAccountSettingsCommand()); return response; }; ``` ```python import os import logging import jsonpickle import boto3 from aws_xray_sdk.core import xray_recorder from aws_xray_sdk.core import patch_all logger = logging.getLogger() logger.setLevel(logging.INFO) patch_all() # Initialize client outside handler for connection reuse client = boto3.client('lambda') client.get_account_settings() def lambda_handler(event, context): logger.info('## ENVIRONMENT VARIABLES\r' + jsonpickle.encode(dict(**os.environ))) logger.info('## EVENT\r' + jsonpickle.encode(event)) logger.info('## CONTEXT\r' + jsonpickle.encode(context)) response = client.get_account_settings() return response['AccountUsage'] ``` ```java package example; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.LambdaLogger; import com.amazonaws.services.lambda.runtime.RequestHandler; import java.util.Map; import software.amazon.awssdk.services.lambda.LambdaClient; import software.amazon.awssdk.services.lambda.model.GetAccountSettingsResponse; import software.amazon.awssdk.services.lambda.model.LambdaException; public class Handler implements RequestHandler, String> { private static final LambdaClient lambdaClient = LambdaClient.builder().build(); @Override public String handleRequest(Map event, Context context) { LambdaLogger logger = context.getLogger(); logger.log("Handler invoked"); GetAccountSettingsResponse response = null; try { response = lambdaClient.getAccountSettings(); } catch(LambdaException e) { logger.log(e.getMessage()); } return response != null ? "Total code size for your account is " + response.accountLimit().totalCodeSize() + " bytes" : "Error"; } } ``` -------------------------------- ### Manage EC2 Spot Instances with AWS Lambda (C#) Source: https://context7.com/awsdocs/aws-lambda-developer-guide/llms.txt Lambda function in C# to manage the lifecycle of EC2 spot instances, including requesting, monitoring, and terminating them. Requires AWS SDK for .NET and X-Ray integration. ```csharp using System; using System.Collections.Generic; using System.Threading.Tasks; using Amazon.EC2; using Amazon.EC2.Model; using Amazon.Lambda.Core; using Amazon.XRay.Recorder.Handlers.AwsSdk; [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))] namespace ec2spot { public class Function { private static AmazonEC2Client ec2Client; static Function() { AWSSDKHandler.RegisterXRayForAllServices(); ec2Client = new AmazonEC2Client(); } public async Task FunctionHandler(Dictionary input, ILambdaContext context) { string ami = "ami-09d9edae5eb90d556"; string sg = "default"; InstanceType type = InstanceType.T3aNano; string price = "0.003"; int count = 1; var requestSpotInstances = await RequestSpotInstance(ami, sg, type, price, count); var spotRequestId = requestSpotInstances.SpotInstanceRequests[0].SpotInstanceRequestId; string instanceId; while (true) { SpotInstanceRequest spotRequest = await GetSpotRequest(spotRequestId); if (spotRequest.State == SpotInstanceState.Active) { instanceId = spotRequest.InstanceId; break; } } var cancelRequest = CancelSpotRequest(spotRequestId); var terminateRequest = TerminateSpotInstance(instanceId); await Task.WhenAll(cancelRequest, terminateRequest); return spotRequestId; } public async Task RequestSpotInstance( string amiId, string securityGroupName, InstanceType instanceType, string spotPrice, int instanceCount) { var request = new RequestSpotInstancesRequest { SpotPrice = spotPrice, InstanceCount = instanceCount, LaunchSpecification = new LaunchSpecification { ImageId = amiId, InstanceType = instanceType, SecurityGroups = new List { securityGroupName } } }; return await ec2Client.RequestSpotInstancesAsync(request); } public async Task GetSpotRequest(string spotRequestId) { var request = new DescribeSpotInstanceRequestsRequest(); request.SpotInstanceRequestIds.Add(spotRequestId); var describeResponse = await ec2Client.DescribeSpotInstanceRequestsAsync(request); return describeResponse.SpotInstanceRequests[0]; } public async Task CancelSpotRequest(string spotRequestId) { var cancelRequest = new CancelSpotInstanceRequestsRequest(); cancelRequest.SpotInstanceRequestIds.Add(spotRequestId); await ec2Client.CancelSpotInstanceRequestsAsync(cancelRequest); } public async Task TerminateSpotInstance(string instanceId) { var terminateRequest = new TerminateInstancesRequest { InstanceIds = new List() { instanceId } }; try { await ec2Client.TerminateInstancesAsync(terminateRequest); } catch (AmazonEC2Exception ex) { if ("InvalidInstanceID.NotFound" != ex.ErrorCode) { throw; } } } } } ``` -------------------------------- ### CloudFormation Template with SAM for Lambda Deployment (YAML) Source: https://context7.com/awsdocs/aws-lambda-developer-guide/llms.txt Infrastructure-as-code template using AWS CloudFormation and SAM to define a Lambda function with specified runtimes, code URIs, IAM policies, and layers. Includes a separate definition for a Lambda Layer. ```yaml AWSTemplateFormatVersion: '2010-09-09' Transform: 'AWS::Serverless-2016-10-31' Description: An AWS Lambda application that calls the Lambda API. Resources: function: Type: AWS::Serverless::Function Properties: Handler: index.handler Runtime: nodejs20.x CodeUri: function/. Description: Call the AWS Lambda API Timeout: 10 Policies: - AWSLambdaBasicExecutionRole - AWSLambda_ReadOnlyAccess - AWSXrayWriteOnlyAccess Tracing: Active Layers: - !Ref libs libs: Type: AWS::Serverless::LayerVersion Properties: LayerName: blank-nodejs-lib Description: Dependencies for the blank sample app. ContentUri: lib/. CompatibleRuntimes: - nodejs20.x ``` -------------------------------- ### Configure Lambda Handler Class (YAML) Source: https://github.com/awsdocs/aws-lambda-developer-guide/blob/main/sample-apps/java-basic/README.md Example snippet from a CloudFormation template (template.yml or template-mvn.yaml) showing how to configure the Lambda function's handler. It specifies the CodeUri and the Handler class. ```yaml Properties: CodeUri: build/distributions/java-basic.zip Handler: example.HandlerList ``` -------------------------------- ### C# Lambda Handler with Async/Await and X-Ray Source: https://context7.com/awsdocs/aws-lambda-developer-guide/llms.txt A C# Lambda function handler implementing the async/await pattern for asynchronous operations. It integrates with the AWS SDK for .NET and AWS X-Ray for tracing, logging environment variables, context, and event details. ```csharp using System; using System.Threading.Tasks; using Amazon.Lambda; using Amazon.Lambda.Model; using Amazon.Lambda.Core; using Amazon.Lambda.SQSEvents; using Amazon.XRay.Recorder.Handlers.AwsSdk; [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))] namespace blankCsharp { public class Function { private AmazonLambdaClient lambdaClient; public Function() { AWSSDKHandler.RegisterXRayForAllServices(); lambdaClient = new AmazonLambdaClient(); } public async Task FunctionHandler(SQSEvent invocationEvent, ILambdaContext context) { GetAccountSettingsResponse accountSettings; try { var request = new GetAccountSettingsRequest(); accountSettings = await lambdaClient.GetAccountSettingsAsync(request); } catch (AmazonLambdaException ex) { throw ex; } LambdaLogger.Log("ENVIRONMENT VARIABLES: " + System.Text.Json.JsonSerializer.Serialize(System.Environment.GetEnvironmentVariables())); LambdaLogger.Log("CONTEXT: " + System.Text.Json.JsonSerializer.Serialize(context)); LambdaLogger.Log("EVENT: " + System.Text.Json.JsonSerializer.Serialize(invocationEvent)); return accountSettings.AccountUsage; } } } ``` -------------------------------- ### Bash: Deploy Lambda with AWS CLI CloudFormation Package and Deploy Source: https://context7.com/awsdocs/aws-lambda-developer-guide/llms.txt A bash script that automates the deployment of an AWS Lambda application using the AWS CLI. It first packages the CloudFormation template and uploads artifacts to an S3 bucket, then deploys the packaged template as a CloudFormation stack, enabling named IAM capabilities. ```bash #!/bin/bash set -eo pipefail # Read S3 bucket name for artifacts ARTIFACT_BUCKET=$(cat bucket-name.txt) # Package CloudFormation template and upload to S3 aws cloudformation package \ --template-file template.yml \ --s3-bucket $ARTIFACT_BUCKET \ --output-template-file out.yml # Deploy packaged template aws cloudformation deploy \ --template-file out.yml \ --stack-name blank-python \ --capabilities CAPABILITY_NAMED_IAM ``` -------------------------------- ### Install AWS Lambda Tools CLI Source: https://github.com/awsdocs/aws-lambda-developer-guide/blob/main/sample-apps/example-csharp/ExampleCS/src/ExampleCS/Readme.md Installs the Amazon.Lambda.Tools Global Tool for deploying Lambda functions from the command line. Ensures the latest version is used if already installed. ```bash dotnet tool install -g Amazon.Lambda.Tools dotnet tool update -g Amazon.Lambda.Tools ``` -------------------------------- ### Go Lambda Handler with Context and AWS SDK Source: https://context7.com/awsdocs/aws-lambda-developer-guide/llms.txt A Go Lambda function handler that demonstrates context management, utilizes the AWS SDK for Go v2 to call another Lambda function, and employs structured logging. It retrieves Lambda context information, execution deadline, and account usage details. ```go package main import ( "context" "encoding/json" "github.com/aws/aws-lambda-go/events" runtime "github.com/aws/aws-lambda-go/lambda" "github.com/aws/aws-lambda-go/lambdacontext" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/lambda" "log" "os" ) var client = lambda.New(session.New()) func callLambda() (string, error) { input := &lambda.GetAccountSettingsInput{} req, resp := client.GetAccountSettingsRequest(input) err := req.Send() output, _ := json.Marshal(resp.AccountUsage) return string(output), err } func handleRequest(ctx context.Context, event events.SQSEvent) (string, error) { eventJson, _ := json.MarshalIndent(event, "", " ") log.Printf("EVENT: %s", eventJson) log.Printf("REGION: %s", os.Getenv("AWS_REGION")) lc, _ := lambdacontext.FromContext(ctx) log.Printf("REQUEST ID: %s", lc.AwsRequestID) log.Printf("FUNCTION NAME: %s", lambdacontext.FunctionName) deadline, _ := ctx.Deadline() log.Printf("DEADLINE: %s", deadline) usage, err := callLambda() if err != nil { return "ERROR", err } return usage, nil } func main() { runtime.Start(handleRequest) } ``` -------------------------------- ### Ruby Lambda Handler with AWS SDK v3 and X-Ray Source: https://context7.com/awsdocs/aws-lambda-developer-guide/llms.txt A Ruby Lambda function handler utilizing AWS SDK v3 for Ruby and integrating with AWS X-Ray. It logs environment variables, the event payload, and Lambda context information before returning account usage details. ```ruby require 'logger' require 'json' require 'aws-sdk-lambda' require 'aws-xray-sdk/lambda' $client = Aws::Lambda::Client.new() $client.get_account_settings() def lambda_handler(event:, context:) logger = Logger.new($stdout) logger.info('## ENVIRONMENT VARIABLES') vars = Hash.new ENV.each do |variable| vars[variable[0]] = variable[1] end logger.info(vars.to_json) logger.info('## EVENT') logger.info(event.to_json) logger.info('## CONTEXT') logger.info(context) $client.get_account_settings().account_usage.to_h end ``` -------------------------------- ### CloudFormation: Deploy Lambda with Inline Code and Scheduled Trigger Source: https://context7.com/awsdocs/aws-lambda-developer-guide/llms.txt A CloudFormation template to deploy an AWS Lambda function with inline Node.js code, a scheduled event trigger, and the necessary IAM execution role. It configures memory, timeout, runtime, and tracing settings for the Lambda function. ```yaml AWSTemplateFormatVersion: '2010-09-09' Description: An AWS Lambda application that uses the AWS Lambda API. Resources: function: Type: AWS::Lambda::Function Properties: Code: ZipFile: | const AWS = require('aws-sdk') let region = process.env.AWS_REGION const lambda = new AWS.Lambda({region: region}) exports.handler = function(event, context) { console.log('Region: ' + region) console.log('Event: ' + JSON.stringify(event, null, 2)) return lambda.getAccountSettings().promise() } Handler: index.handler MemorySize: 128 Role: !GetAtt executionRole.Arn Runtime: nodejs16.x Timeout: 10 TracingConfig: Mode: Active scheduledEvent: Type: AWS::Events::Rule Properties: Description: Scheduled event ScheduleExpression: rate(2 minutes) State: ENABLED Targets: - Arn: !GetAtt function.Arn Id: Function invokePermission: Type: AWS::Lambda::Permission Properties: FunctionName: !Ref function Action: lambda:InvokeFunction Principal: events.amazonaws.com SourceArn: !GetAtt scheduledEvent.Arn executionRole: Type: AWS::IAM::Role Properties: ManagedPolicyArns: - arn:aws:iam::aws:policy/AWSXRayDaemonWriteAccess - arn:aws:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole Policies: - PolicyName: read-lambdasettings PolicyDocument: Version: 2012-10-17 Statement: - Effect: Allow Action: lambda:GetAccountSettings Resource: '*' AssumeRolePolicyDocument: Version: 2012-10-17 Statement: - Action: sts:AssumeRole Effect: Allow Principal: Service: lambda.amazonaws.com ``` -------------------------------- ### Python Lambda Function Using External Dependencies via Layer Source: https://context7.com/awsdocs/aws-lambda-developer-guide/llms.txt A Python Lambda function demonstrating the use of an external library ('requests') managed via a Lambda Layer. This approach helps reduce the deployment package size. The function fetches data from the GitHub API and returns the status code and response body. ```python import requests def lambda_handler(event, context): print(f"Version of requests library: {requests.__version__}") request = requests.get('https://api.github.com/') return { 'statusCode': request.status_code, 'body': request.text } ``` -------------------------------- ### Deploy Blank Node.js Lambda Function with AWS CLI Source: https://github.com/awsdocs/aws-lambda-developer-guide/blob/main/sample-apps/blank-nodejs/README.md Shell scripts for deploying a Node.js Lambda function. Includes steps for creating deployment artifact buckets, building Lambda layers for dependencies, and deploying the application using AWS CloudFormation. Assumes Node.js, npm, Bash, and AWS CLI are installed. ```bash git clone https://github.com/awsdocs/aws-lambda-developer-guide.git cd aws-lambda-developer-guide/sample-apps/blank-nodejs # Create a bucket for deployment artifacts ./1-create-bucket.sh # Build a Lambda layer with function runtime dependencies ./2-build-layer.sh # Deploy the application using AWS CloudFormation ./3-deploy.sh # Invoke the deployed Lambda function ./4-invoke.sh ``` -------------------------------- ### C# Lambda Handler for S3 Order Receipt Generation Source: https://context7.com/awsdocs/aws-lambda-developer-guide/llms.txt A C# Lambda function that processes order data, generates a plain text receipt, and uploads it to an S3 bucket. It utilizes asynchronous S3 operations and includes structured error handling for S3 exceptions. Requires the 'RECEIPT_BUCKET' environment variable to be set. ```csharp using System; using System.Text; using System.Threading.Tasks; using Amazon.Lambda.Core; using Amazon.S3; using Amazon.S3.Model; [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] namespace ExampleLambda; public class Order { public string OrderId { get; set; } = string.Empty; public double Amount { get; set; } public string Item { get; set; } = string.Empty; } public class OrderHandler { private static readonly AmazonS3Client s3Client = new(); public async Task HandleRequest(Order order, ILambdaContext context) { try { string? bucketName = Environment.GetEnvironmentVariable("RECEIPT_BUCKET"); if (string.IsNullOrWhiteSpace(bucketName)) { throw new ArgumentException("RECEIPT_BUCKET environment variable is not set"); } string receiptContent = $"OrderID: {order.OrderId}\nAmount: ${order.Amount:F2}\nItem: {order.Item}"; string key = $"receipts/{order.OrderId}.txt"; var putRequest = new PutObjectRequest { BucketName = bucketName, Key = key, ContentBody = receiptContent, ContentType = "text/plain" }; await s3Client.PutObjectAsync(putRequest); context.Logger.LogInformation($"Successfully processed order {order.OrderId} and stored receipt in S3 bucket {bucketName}"); return "Success"; } catch (AmazonS3Exception ex) { context.Logger.LogError($"Failed to process order: {ex.Message}"); throw; } } } ``` -------------------------------- ### Deploy Lambda Function using Gradle (Shell) Source: https://github.com/awsdocs/aws-lambda-developer-guide/blob/main/sample-apps/java-basic/README.md Shell script to deploy the Java Lambda function using AWS CloudFormation. This script utilizes Gradle as the build tool for packaging and deployment. ```shell java-basic$ ./2-deploy.sh BUILD SUCCESSFUL in 1s Successfully packaged artifacts and wrote output template to file out.yml. Waiting for changeset to be created.. Successfully created/updated stack - java-basic ``` -------------------------------- ### Bash: Invoke Lambda Continuously with AWS CLI and Payload Source: https://context7.com/awsdocs/aws-lambda-developer-guide/llms.txt A bash script designed for continuous testing of an AWS Lambda function. It retrieves the function's physical resource ID from a CloudFormation stack, then repeatedly invokes the Lambda function with a specified payload file and prints the output, pausing for 2 seconds between invocations. ```bash #!/bin/bash set -eo pipefail # Get function name from CloudFormation stack FUNCTION=$(aws cloudformation describe-stack-resource \ --stack-name blank-python \ --logical-resource-id function \ --query 'StackResourceDetail.PhysicalResourceId' \ --output text) # Continuously invoke function for testing while true; do aws lambda invoke \ --function-name $FUNCTION \ --payload fileb://event.json \ out.json cat out.json echo "" sleep 2 done ``` -------------------------------- ### IAM Policy: Basic Lambda Execution Permissions for CloudWatch Logs Source: https://context7.com/awsdocs/aws-lambda-developer-guide/llms.txt An IAM policy document in JSON format that grants a Lambda function the necessary permissions to create log groups, create log streams, and put log events to CloudWatch Logs. It specifies resources for log group creation and log stream events. ```json { "Version":"2012-10-17", "Statement":[ { "Effect":"Allow", "Action":"logs:CreateLogGroup", "Resource":"arn:aws:logs:us-east-2:123456789012:*" }, { "Effect":"Allow", "Action":[ "logs:CreateLogStream", "logs:PutLogEvents" ], "Resource":[ "arn:aws:logs:us-east-2:123456789012:log-group:[[logGroups]]:*" ] } ] } ``` -------------------------------- ### Create S3 Bucket for Lambda Artifacts (Shell) Source: https://github.com/awsdocs/aws-lambda-developer-guide/blob/main/sample-apps/java-basic/README.md Shell script to create an S3 bucket required for storing deployment artifacts for the Lambda function. This is a prerequisite step for deploying the application. ```shell java-basic$ ./1-create-bucket.sh make_bucket: lambda-artifacts-a5e4xmplb5b22e0d ``` -------------------------------- ### Cleanup Script for AWS Resources Source: https://github.com/awsdocs/aws-lambda-developer-guide/blob/main/sample-apps/java-events/README.md This shell script is used to clean up AWS resources created during the deployment of the Java Lambda function example. It should be run after testing. ```shell ./4-cleanup.sh ``` -------------------------------- ### Python Lambda for S3 PDF Encryption Source: https://context7.com/awsdocs/aws-lambda-developer-guide/llms.txt A Python Lambda function triggered by S3 object creation events. It downloads PDF files, encrypts them using the pypdf library, and uploads the encrypted version to a separate S3 bucket. Requires 'pypdf' and 'boto3' libraries. Note: Uses a hardcoded password for encryption; consider using AWS Secrets Manager for production. ```python from pypdf import PdfReader, PdfWriter import uuid import os from urllib.parse import unquote_plus import boto3 s3_client = boto3.client('s3') def lambda_handler(event, context): for record in event['Records']: bucket = record['s3']['bucket']['name'] key = unquote_plus(record['s3']['object']['key']) download_path = f'/tmp/{uuid.uuid4()}.pdf' upload_path = f'/tmp/converted-{uuid.uuid4()}.pdf' if key.lower().endswith('.pdf'): s3_client.download_file(bucket, key, download_path) encrypt_pdf(download_path, upload_path) encrypted_key = add_encrypted_suffix(key) s3_client.upload_file(upload_path, f'{bucket}-encrypted', encrypted_key) def encrypt_pdf(file_path, encrypted_file_path): reader = PdfReader(file_path) writer = PdfWriter() for page in reader.pages: writer.add_page(page) # Use AWS Secrets Manager for production passwords writer.encrypt("my-secret-password") with open(encrypted_file_path, "wb") as file: writer.write(file) def add_encrypted_suffix(original_key): filename, extension = original_key.rsplit('.', 1) return f'{filename}_encrypted.{extension}' ``` -------------------------------- ### Generate and Store S3 Order Receipts - Java Source: https://context7.com/awsdocs/aws-lambda-developer-guide/llms.txt A Java Lambda function that processes incoming Order events, formats a receipt string, and uploads it as a .txt file to a specified S3 bucket. It relies on the `RECEIPT_BUCKET` environment variable for the bucket name and uses the AWS SDK for Java v2. Errors during S3 operations are logged and re-thrown as runtime exceptions. ```java package example; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; import software.amazon.awssdk.core.sync.RequestBody; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.services.s3.model.PutObjectRequest; import software.amazon.awssdk.services.s3.model.S3Exception; import java.nio.charset.StandardCharsets; public class OrderHandler implements RequestHandler { private static final S3Client S3_CLIENT = S3Client.builder().build(); public record Order(String orderId, double amount, String item) {} @Override public String handleRequest(Order event, Context context) { try { String bucketName = System.getenv("RECEIPT_BUCKET"); if (bucketName == null || bucketName.isEmpty()) { throw new IllegalArgumentException("RECEIPT_BUCKET environment variable is not set"); } String receiptContent = String.format("OrderID: %s\nAmount: $%.2f\nItem: %s", event.orderId(), event.amount(), event.item()); String key = "receipts/" + event.orderId() + ".txt"; PutObjectRequest putObjectRequest = PutObjectRequest.builder() .bucket(bucketName) .key(key) .build(); S3_CLIENT.putObject(putObjectRequest, RequestBody.fromBytes(receiptContent.getBytes(StandardCharsets.UTF_8))); context.getLogger().log("Successfully processed order " + event.orderId() + " and stored receipt in S3 bucket " + bucketName); return "Success"; } catch (S3Exception e) { context.getLogger().log("Failed to process order: " + e.getMessage()); throw new RuntimeException(e); } } } ``` -------------------------------- ### Create S3 Bucket and IAM Role (Shell) Source: https://github.com/awsdocs/aws-lambda-developer-guide/blob/main/sample-apps/blank-csharp-with-layer/README.md This script creates an S3 bucket for deployment artifacts and an IAM role that Lambda functions can assume. It requires the AWS CLI to be installed and configured. ```shell ./1-create-bucket.sh make_bucket: lambda-artifacts-d7aec9f2022ef2b4 make_bucket: lambda-artifacts-d7aec9f2022ef2b4-dotnet-layer { "Role": { "Path": "/", "RoleName": "blank-csharp-role", "RoleId": "AROA6HOIFXAKKWARP5RSC", "Arn": "arn:aws:iam::978061735956:role/blank-csharp-role", "CreateDate": "2023-08-22T18:12:29+00:00", "AssumeRolePolicyDocument": { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "sts:AssumeRole" ], "Principal": { "Service": [ "lambda.amazonaws.com" ] } } ] } } } ``` -------------------------------- ### Generate and Store S3 Order Receipts - Go Source: https://context7.com/awsdocs/aws-lambda-developer-guide/llms.txt A Go Lambda function designed to process incoming JSON order events. It unmarshals the event data, constructs a receipt string, and uploads it to a designated S3 bucket using the `RECEIPT_BUCKET` environment variable. The function utilizes the AWS SDK for Go v2 and logs any errors encountered during JSON unmarshalling or S3 upload. ```go package main import ( "context" "encoding/json" "fmt" "log" "os" "strings" "github.com/aws/aws-lambda-go/lambda" "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/service/s3" ) type Order struct { OrderID string `json:"order_id"` Amount float64 `json:"amount"` Item string `json:"item"` } var s3Client *s3.Client func init() { cfg, err := config.LoadDefaultConfig(context.TODO()) if err != nil { log.Fatalf("unable to load SDK config, %v", err) } s3Client = s3.NewFromConfig(cfg) } func uploadReceiptToS3(ctx context.Context, bucketName, key, receiptContent string) error { _, err := s3Client.PutObject(ctx, &s3.PutObjectInput{ Bucket: &bucketName, Key: &key, Body: strings.NewReader(receiptContent), }) if err != nil { log.Printf("Failed to upload receipt to S3: %v", err) return err } return nil } func handleRequest(ctx context.Context, event json.RawMessage) error { var order Order if err := json.Unmarshal(event, &order); err != nil { log.Printf("Failed to unmarshal event: %v", err) return err } bucketName := os.Getenv("RECEIPT_BUCKET") if bucketName == "" { return fmt.Errorf("missing required environment variable RECEIPT_BUCKET") } receiptContent := fmt.Sprintf("OrderID: %s\nAmount: $%.2f\nItem: %s", order.OrderID, order.Amount, order.Item) key := "receipts/" + order.OrderID + ".txt" if err := uploadReceiptToS3(ctx, bucketName, key, receiptContent); err != nil { return err } log.Printf("Successfully processed order %s and stored receipt in S3 bucket %s", order.OrderID, bucketName) return nil } func main() { lambda.Start(handleRequest) } ``` -------------------------------- ### Basic Lambda Handler (Java) Source: https://github.com/awsdocs/aws-lambda-developer-guide/blob/main/sample-apps/java-basic/README.md A basic Java Lambda handler function that takes a Map as input and returns a String. This is the default handler for the sample application. ```java package example; import java.util.Map; public class Handler { public String handleRequest(Map input) { // your code goes here return "200 OK"; } } ``` -------------------------------- ### Deploy S3 Image Resizer Application (Shell) Source: https://github.com/awsdocs/aws-lambda-developer-guide/blob/main/sample-apps/s3-java/README.md Shell scripts to deploy the S3 image resizer application using AWS CloudFormation. These scripts handle bucket creation, layer building, and application deployment. They rely on the AWS CLI and a pre-configured environment. ```shell #!/bin/bash # Create a new bucket for deployment artifacts # This command assumes you have the AWS CLI installed and configured. # The bucket name is generated based on the project and a random UUID. s3-java$ ./1-create-bucket.sh # Build a Lambda layer that contains the function's runtime dependencies. # Packaging dependencies in a layer reduces the size of the deployment package. s3-java$ ./2-build-layer.sh # Deploy the application using AWS CloudFormation. # This script creates or updates the CloudFormation stack, deploying Lambda functions and IAM roles. s3-java$ ./3-deploy.sh # Deploy the application using Maven as the build tool. # This variant of the deploy script is used when Maven is preferred over Gradle. java-basic$ ./3-deploy.sh mvn ``` -------------------------------- ### Deploy Lambda Function using Maven (Shell) Source: https://github.com/awsdocs/aws-lambda-developer-guide/blob/main/sample-apps/java-basic/README.md Shell script to deploy the Java Lambda function using AWS CloudFormation, specifying Maven as the build tool. This allows for deployment using Maven's build lifecycle. ```shell java-basic$ ./2-deploy.sh mvn [INFO] Scanning for projects... [INFO] -----------------------< com.example:java-basic >----------------------- [INFO] Building java-basic-function 1.0-SNAPSHOT [INFO] --------------------------------[ jar ]--------------------------------- ... ``` -------------------------------- ### Cleanup Lambda Application (Shell) Source: https://github.com/awsdocs/aws-lambda-developer-guide/blob/main/sample-apps/java-basic/README.md Shell script to delete the AWS resources associated with the Lambda application, including the CloudFormation stack and related resources. This is used for cleaning up after deployment. ```shell java-basic$ ./4-cleanup.sh ``` -------------------------------- ### Java Handler for API Gateway REST API Event Source: https://github.com/awsdocs/aws-lambda-developer-guide/blob/main/sample-apps/java-events/README.md Example of a Java handler class designed for API Gateway REST APIs. It takes an APIGatewayProxyRequestEvent as input and returns an APIGatewayProxyResponseEvent. ```java package example; import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent; import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; public class HandlerApiGateway implements RequestHandler { @Override public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent event, Context context) { APIGatewayProxyResponseEvent response = new APIGatewayProxyResponseEvent(); response.setStatusCode(200); response.setBody("Hello from API Gateway REST!"); return response; } } ``` -------------------------------- ### Invoke Lambda Function (Shell) Source: https://github.com/awsdocs/aws-lambda-developer-guide/blob/main/sample-apps/java-events/README.md Shell script to invoke the deployed Java Lambda function. It demonstrates how to send requests and view the function's response, including an example of an API Gateway HTTP API event. ```shell #!/bin/bash # Script to invoke the Lambda function and display results. # Press Ctrl+C to exit after a few invocations. FUNCTION_NAME="java-events" while true; do aws lambda invoke --function-name "$FUNCTION_NAME" --payload '{ "httpMethod": "GET", "path": "/", "requestContext": { "http": { "method": "GET", "path": "/" } } }' output.json cat output.json sleep 1 done ``` -------------------------------- ### Lambda Handler with Integer Input (Java) Source: https://github.com/awsdocs/aws-lambda-developer-guide/blob/main/sample-apps/java-basic/README.md A Java Lambda handler function designed to accept an Integer as input. This demonstrates handling different primitive data types as function arguments. ```java package example; public class HandlerInteger { public String handleRequest(Integer input) { // your code goes here return "200 OK"; } } ``` -------------------------------- ### Test S3 Image Resizer Function (Shell) Source: https://github.com/awsdocs/aws-lambda-developer-guide/blob/main/sample-apps/s3-java/README.md Shell scripts to test the S3 image resizer Lambda function. These scripts upload a sample image to an S3 bucket, invoke the Lambda function, and verify the resized image output. They also provide instructions for monitoring with AWS X-Ray. ```shell # Upload an image file to the application bucket. # This command prepares the input image for the Lambda function. s3-java$ ./4-upload.sh # Invoke the Lambda function directly. # This sends a request to the Lambda function to process the uploaded image. s3-java$ ./5-invoke.sh ``` -------------------------------- ### Java Handler for API Gateway V2 Proxy Event Source: https://github.com/awsdocs/aws-lambda-developer-guide/blob/main/sample-apps/java-events/README.md Example of a Java handler class that accepts an APIGatewayV2ProxyRequestEvent and returns an APIGatewayV2ProxyResponseEvent. This is suitable for AWS Lambda functions triggered by API Gateway HTTP APIs. ```java package example; import com.amazonaws.services.lambda.runtime.events.APIGatewayV2ProxyRequestEvent; import com.amazonaws.services.lambda.runtime.events.APIGatewayV2ProxyResponseEvent; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; public class Handler implements RequestHandler { @Override public APIGatewayV2ProxyResponseEvent handleRequest(APIGatewayV2ProxyRequestEvent event, Context context) { APIGatewayV2ProxyResponseEvent response = new APIGatewayV2ProxyResponseEvent(); response.setStatusCode(200); response.setBody("Hello from Lambda!"); return response; } } ``` -------------------------------- ### Lambda Handler with String Input (Java) Source: https://github.com/awsdocs/aws-lambda-developer-guide/blob/main/sample-apps/java-basic/README.md A Java Lambda handler function that expects a String as its input parameter. This is a common handler type for text-based inputs. ```java package example; public class HandlerString { public String handleRequest(String input) { // your code goes here return "200 OK"; } } ``` -------------------------------- ### Lambda Handler with Stream Input/Output (Java) Source: https://github.com/awsdocs/aws-lambda-developer-guide/blob/main/sample-apps/java-basic/README.md A Java Lambda handler function that uses InputStream and OutputStream for input and output. This is suitable for handling binary data or large payloads efficiently. ```java package example; import java.io.InputStream; import java.io.OutputStream; public class HandlerStream { public void handleRequest(InputStream input, OutputStream output) { // your code goes here } } ``` -------------------------------- ### Lambda Handler with List Input (Java) Source: https://github.com/awsdocs/aws-lambda-developer-guide/blob/main/sample-apps/java-basic/README.md A Java Lambda handler function that accepts a List of Integers as input. This handler is used when the function needs to process a collection of numbers. ```java package example; import java.util.List; public class HandlerList { public String handleRequest(List input) { // your code goes here return "200 OK"; } } ``` -------------------------------- ### Invoke Lambda Function (Shell) Source: https://github.com/awsdocs/aws-lambda-developer-guide/blob/main/sample-apps/java-basic/README.md Shell script to invoke the deployed Java Lambda function. The output indicates the status code and executed version of the function. Supports passing arguments for different handlers. ```shell ./3-invoke.sh { "StatusCode": 200, "ExecutedVersion": "$LATEST" } "200 OK" ``` ```shell ./3-invoke.sh list { "StatusCode": 200, "ExecutedVersion": "$LATEST" } 9979 ``` -------------------------------- ### Invoke Lambda Function with Handler Type Source: https://github.com/awsdocs/aws-lambda-developer-guide/blob/main/sample-apps/java-events/README.md This snippet shows how to use a shell script to invoke an AWS Lambda function with a specific handler type. It includes an example of invoking the 'lex' handler and the expected response. ```shell ./3-invoke.sh lex { "StatusCode": 200, "ExecutedVersion": "$LATEST" } "200 OK" ``` -------------------------------- ### Cleanup S3 Image Resizer Application (Shell) Source: https://github.com/awsdocs/aws-lambda-developer-guide/blob/main/sample-apps/s3-java/README.md A shell script to clean up and delete the deployed S3 image resizer application resources. This script removes the CloudFormation stack and associated resources, ensuring a clean environment after testing. ```shell # Delete the application and its associated AWS resources. # This script removes the CloudFormation stack created during deployment. blank$ ./6-cleanup.sh ``` -------------------------------- ### Lambda Handler for Division (Java) Source: https://github.com/awsdocs/aws-lambda-developer-guide/blob/main/sample-apps/java-basic/README.md A Java Lambda handler function that takes a List containing two integers as input and performs division. It's designed for specific arithmetic operations. ```java package example; import java.util.List; public class HandlerDivide { public String handleRequest(List input) { // your code goes here return "200 OK"; } } ``` -------------------------------- ### Lambda Handler with Custom Object Input (Java) Source: https://github.com/awsdocs/aws-lambda-developer-guide/blob/main/sample-apps/java-basic/README.md A Java Lambda handler function that takes a custom object type as input. This demonstrates how to define and use custom data structures for Lambda function events. ```java package example; public class HandlerWeatherData { // Assume WeatherData is a custom class defined elsewhere public String handleRequest(WeatherData input) { // your code goes here return "200 OK"; } } ``` -------------------------------- ### Configure Lambda Handler in AWS SAM Template Source: https://github.com/awsdocs/aws-lambda-developer-guide/blob/main/sample-apps/java-events/README.md This snippet demonstrates how to set the 'Handler' property in an AWS SAM template (template.yml or template-mvn.yaml) to specify a custom Java handler class for an AWS Lambda function. It shows an example of configuring the handler for Amazon Lex events. ```yaml Properties: CodeUri: build/distributions/java-events.zip Handler: example.HandlerLex ``` -------------------------------- ### Deploy Lambda Function via CLI Source: https://github.com/awsdocs/aws-lambda-developer-guide/blob/main/sample-apps/example-csharp/ExampleCS/src/ExampleCS/Readme.md Deploys a Lambda function to AWS using the .NET Lambda CLI tool. Requires navigating to the project's source directory before execution. ```bash cd "ExampleCS/src/ExampleCS" dotnet lambda deploy-function ``` -------------------------------- ### Execute Unit Tests for Lambda Project Source: https://github.com/awsdocs/aws-lambda-developer-guide/blob/main/sample-apps/example-csharp/ExampleCS/src/ExampleCS/Readme.md Runs unit tests for the Lambda project using the .NET test command. Assumes the test project is located in the specified directory. ```bash cd "ExampleCS/test/ExampleCS.Tests" dotnet test ``` -------------------------------- ### Deploy Sample Application using Gradle or Maven (Shell) Source: https://github.com/awsdocs/aws-lambda-developer-guide/blob/main/sample-apps/java-events/README.md Shell scripts to build and deploy the Java Lambda application. It supports deployment using either Gradle or Maven, creating necessary AWS resources via CloudFormation. ```shell #!/bin/bash # Script to create an S3 bucket for deployment artifacts # Usage: ./1-create-bucket.sh BUCKET_NAME="lambda-artifacts-$(openssl rand -hex 12)" aws s3api create-bucket --bucket "$BUCKET_NAME" echo "Created bucket: $BUCKET_NAME" # Script to build and deploy the Lambda application using Gradle or Maven # Usage: ./2-deploy.sh [mvn] BUILD_TOOL="gradle" if [ "$1" = "mvn" ]; then BUILD_TOOL="mvn" fi if [ "$BUILD_TOOL" = "gradle" ]; then ./gradlew build else mvn package fi aws cloudformation deploy --template-file template.yml --stack-name java-events --capabilities CAPABILITY_IAM ``` -------------------------------- ### Deploy C# Lambda Function (Shell) Source: https://github.com/awsdocs/aws-lambda-developer-guide/blob/main/sample-apps/blank-csharp-with-layer/README.md This script deploys the C# Lambda function using the .NET Amazon Lambda Tools. It packages the code and creates a new Lambda function in AWS. It relies on a pre-configured `aws-lambda-tools-defaults.json` file. ```shell ./3-deploy.sh Amazon Lambda Tools for .NET Core applications (5.8.0) ... Created publish archive ... Creating new Lambda function blank-csharp New Lambda function created ``` -------------------------------- ### Build and Upload Lambda Layer (Shell) Source: https://github.com/awsdocs/aws-lambda-developer-guide/blob/main/sample-apps/blank-csharp-with-layer/README.md This script builds a Lambda layer containing the C# function's runtime dependencies and uploads it to an S3 bucket. It requires .NET Core SDK and AWS extensions for .NET CLI. ```shell ./2-build-layer.sh ``` -------------------------------- ### Create S3 Bucket for Artifacts (Shell) Source: https://github.com/awsdocs/aws-lambda-developer-guide/blob/main/sample-apps/java-events/README.md Shell script to create an S3 bucket required for storing deployment artifacts for the AWS Lambda application. It uses a randomly generated name to ensure uniqueness. ```shell #!/bin/bash BUCKET_NAME="lambda-artifacts-$(openssl rand -hex 12)" aws s3api create-bucket --bucket "$BUCKET_NAME" echo "Created bucket: $BUCKET_NAME" ``` -------------------------------- ### Java Handler for Lex Event Source: https://github.com/awsdocs/aws-lambda-developer-guide/blob/main/sample-apps/java-events/README.md This handler processes events from Amazon Lex, a service for building conversational interfaces. It takes a LexEvent object as input. ```java package example; import com.amazonaws.services.lambda.runtime.events.LexEvent; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; public class HandlerLex implements RequestHandler { // Assuming Void return for simplicity, adjust as needed @Override public Void handleRequest(LexEvent event, Context context) { // Process Lex event context.getLogger().log("Processing Lex event."); return null; } } ``` -------------------------------- ### Java Handler for CloudFront Event Source: https://github.com/awsdocs/aws-lambda-developer-guide/blob/main/sample-apps/java-events/README.md This Java handler is designed to process CloudFront events. It accepts a CloudFrontEvent object as input. The specific return type depends on the CloudFront Function or Lambda@Edge configuration. ```java package example; import com.amazonaws.services.lambda.runtime.events.CloudFrontEvent; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; public class HandlerCloudFront implements RequestHandler { // Assuming Void return for simplicity, adjust as needed @Override public Void handleRequest(CloudFrontEvent event, Context context) { // Process CloudFront event context.getLogger().log("Processing CloudFront event."); return null; } } ``` -------------------------------- ### Invoke C# Lambda Function (Shell) Source: https://github.com/awsdocs/aws-lambda-developer-guide/blob/main/sample-apps/blank-csharp-with-layer/README.md This script invokes the deployed C# Lambda function and displays the execution status and results. It's used to test the function after deployment. ```shell ./4-invoke.sh { "StatusCode": 200, "ExecutedVersion": "$LATEST" } {"FunctionCount":13,"TotalCodeSize":598094248} ``` -------------------------------- ### Java Handler for S3 Event Source: https://github.com/awsdocs/aws-lambda-developer-guide/blob/main/sample-apps/java-events/README.md A Java handler for processing events triggered by Amazon S3, such as object creation or deletion. It takes an S3Event object as input. ```java package example; import com.amazonaws.services.lambda.runtime.events.S3Event; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; public class HandlerS3 implements RequestHandler { // Assuming Void return for simplicity, adjust as needed @Override public Void handleRequest(S3Event event, Context context) { // Process S3 event context.getLogger().log("Processing S3 event."); return null; } } ``` -------------------------------- ### Java Handler for CloudWatch Logs Event Source: https://github.com/awsdocs/aws-lambda-developer-guide/blob/main/sample-apps/java-events/README.md This handler processes incoming log events from Amazon CloudWatch Logs. It takes a CloudWatchLogsEvent as input, allowing for log processing or transformation. ```java package example; import com.amazonaws.services.lambda.runtime.events.CloudWatchLogsEvent; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; public class HandlerCWLogs implements RequestHandler { // Assuming Void return for simplicity, adjust as needed @Override public Void handleRequest(CloudWatchLogsEvent event, Context context) { // Process CloudWatch Logs event context.getLogger().log("Processing CloudWatch Logs event."); return null; } } ``` -------------------------------- ### Cleanup Deployed Resources (Shell) Source: https://github.com/awsdocs/aws-lambda-developer-guide/blob/main/sample-apps/blank-csharp-with-layer/README.md This script removes the deployed Lambda function and associated resources from AWS. It's used to clean up the environment after testing. ```shell ./5-cleanup.sh ``` -------------------------------- ### Java Handler for SQS Event Source: https://github.com/awsdocs/aws-lambda-developer-guide/blob/main/sample-apps/java-events/README.md A Java handler for processing messages from Amazon Simple Queue Service (SQS) queues. It takes an SQSEvent object as input. ```java package example; import com.amazonaws.services.lambda.runtime.events.SQSEvent; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; public class HandlerSQS implements RequestHandler { // Assuming Void return for simplicity, adjust as needed @Override public Void handleRequest(SQSEvent event, Context context) { // Process SQS event context.getLogger().log("Processing SQS event."); return null; } } ``` -------------------------------- ### Java Handler for CloudWatch Scheduled Event Source: https://github.com/awsdocs/aws-lambda-developer-guide/blob/main/sample-apps/java-events/README.md A Java handler for scheduled events from Amazon CloudWatch Events (now EventBridge). It takes a ScheduledEventEvent as input, useful for cron-like job scheduling. ```java package example; import com.amazonaws.services.lambda.runtime.events.ScheduledEvent; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; public class HandlerCWEvents implements RequestHandler { // Assuming Void return for simplicity, adjust as needed @Override public Void handleRequest(ScheduledEvent event, Context context) { // Process scheduled event context.getLogger().log("Processing scheduled event."); return null; } } ``` -------------------------------- ### Java Handler for CodeCommit Event Source: https://github.com/awsdocs/aws-lambda-developer-guide/blob/main/sample-apps/java-events/README.md A Java handler for processing AWS CodeCommit events. It takes a CodeCommitEvent object as input, allowing you to react to code repository changes. ```java package example; import com.amazonaws.services.lambda.runtime.events.CodeCommitEvent; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; public class HandlerCodeCommit implements RequestHandler { // Assuming Void return for simplicity, adjust as needed @Override public Void handleRequest(CodeCommitEvent event, Context context) { // Process CodeCommit event context.getLogger().log("Processing CodeCommit event."); return null; } } ``` -------------------------------- ### Java Handler for SNS Event Source: https://github.com/awsdocs/aws-lambda-developer-guide/blob/main/sample-apps/java-events/README.md This handler processes messages published to Amazon Simple Notification Service (SNS) topics. It accepts an SNSEvent object as input. ```java package example; import com.amazonaws.services.lambda.runtime.events.SNSEvent; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; public class HandlerSNS implements RequestHandler { // Assuming Void return for simplicity, adjust as needed @Override public Void handleRequest(SNSEvent event, Context context) { // Process SNS event context.getLogger().log("Processing SNS event."); return null; } } ```