Hands-On Lab925 words

Mastering AWS Lambda: Development, Configuration, and Integration

Develop code for AWS Lambda

Mastering AWS Lambda: Development, Configuration, and Integration

This hands-on lab guides you through the process of developing, configuring, and deploying an AWS Lambda function. You will learn to manage environment variables, tune performance, and integrate with other AWS services while following the AWS Certified Developer - Associate (DVA-C02) curriculum.

[!WARNING] Remember to run the teardown commands at the end of this lab to avoid ongoing charges to your AWS account.


Prerequisites

To successfully complete this lab, you need:

  • An AWS Account with administrative access.
  • AWS CLI installed and configured (aws configure).
  • Python 3.9+ installed locally for code packaging.
  • Basic familiarity with the Linux/macOS terminal or Windows PowerShell.

Learning Objectives

By the end of this lab, you will be able to:

  1. Create an IAM Execution Role with the principle of least privilege.
  2. Develop and deploy a Lambda function using the AWS CLI and Management Console.
  3. Configure environment variables and memory settings for optimal performance.
  4. Implement an event-driven integration using Amazon S3 as a trigger.
  5. Monitor execution logs and troubleshoot common runtime errors.

Architecture Overview

In this lab, we build a serverless image-processing metadata extractor. When a file is uploaded to S3, Lambda triggers, reads the metadata, and logs the results to CloudWatch.

Loading Diagram...

Step-by-Step Instructions

Step 1: Create the IAM Execution Role

Lambda functions require an execution role to grant permissions to access other AWS services (like S3 and CloudWatch).

bash
# 1. Create the Trust Policy file echo '{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Service": "lambda.amazonaws.com" }, "Action": "sts:AssumeRole" } ] }' > trust-policy.json # 2. Create the IAM Role aws iam create-role --role-name brainybee-lambda-role --assume-role-policy-document file://trust-policy.json # 3. Attach the Basic Execution Policy (for Logging) aws iam attach-role-policy --role-name brainybee-lambda-role --policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
Console alternative

Navigate to

IAM > Roles > Create Role

. Select

AWS Service

, choose

Lambda

, and search for

AWSLambdaBasicExecutionRole

to attach. Name it

brainybee-lambda-role

.

Step 2: Prepare the Lambda Function Code

Create a Python script named lambda_function.py that simulates processing an S3 event.

python
import os import json def lambda_handler(event, context): # Accessing Environment Variables log_level = os.environ.get('LOG_LEVEL', 'INFO') print(f"Log Level: {log_level}") print(f"Received event: {json.dumps(event)}") # Business logic placeholder return { 'statusCode': 200, 'body': json.dumps('Metadata processed successfully!') }
bash
# Package the function zip function.zip lambda_function.py

Step 3: Create and Configure the Lambda Function

Now, we deploy the ZIP file to AWS, specifying runtime, handler, and memory limits.

bash
aws lambda create-function --function-name brainybee-processor-func \ --zip-file fileb://function.zip --handler lambda_function.lambda_handler --runtime python3.9 \ --role arn:aws:iam::<YOUR_ACCOUNT_ID>:role/brainybee-lambda-role \ --memory-size 128 --timeout 10

[!TIP] Use aws sts get-caller-identity --query Account --output text to quickly find your Account ID.

Step 4: Configure Environment Variables

Environment variables allow you to change function behavior without updating the code.

bash
aws lambda update-function-configuration --function-name brainybee-processor-func \ --environment "Variables={LOG_LEVEL=DEBUG,APP_ENV=development}"
Console alternative

Open your function in the

Lambda Console

. Go to

Configuration > Environment variables

and click

Edit

. Add key-value pairs for

LOG_LEVEL

and

APP_ENV

.

Checkpoints

Verification TaskCommand / ActionExpected Result
Verify Roleaws iam get-role --role-name brainybee-lambda-roleJSON output with Role ARN
Invoke Functionaws lambda invoke --function-name brainybee-processor-func out.jsonStatus code 200 in terminal
Check LogsView CloudWatch Logs /aws/lambda/brainybee-processor-funcLog entry showing "Log Level: DEBUG"

Concept Review: Performance Tuning

Lambda performance is primarily controlled by the Memory setting. Increasing memory also increases the proportional CPU power and network bandwidth.

\begin{tikzpicture} \draw[->] (0,0) -- (6,0) node[right] {Memory (MB)}; \draw[->] (0,0) -- (0,4) node[above] {Execution Time (ms)}; \draw[thick, blue] (0.5,3.5) .. controls (1.5,1) and (4,0.5) .. (5.5,0.4); \node[blue] at (4,2) {Inverse Relationship}; \draw[dashed] (1,0) -- (1,2.5); \draw[dashed] (4,0) -- (4,0.6); \node at (1,-0.3) {\small 128MB}; \node at (4,-0.3) {\small 1024MB}; \end{tikzpicture}

Troubleshooting

ErrorLikely CauseFix
An error occurred (AccessDeniedException)IAM role lacks permissions or trust policy is wrong.Check trust-policy.json and attached policies.
Task timed out after 10.01 secondsLogic is too slow or memory is too low.Increase --timeout or --memory-size.
ModuleNotFoundErrorHandler path is incorrect or ZIP structure is wrong.Ensure lambda_function.py is at the root of the ZIP.

Clean-Up / Teardown

Run these commands to remove all resources created in this lab.

bash
# 1. Delete the Lambda Function aws lambda delete-function --function-name brainybee-processor-func # 2. Detach IAM Policies aws iam detach-role-policy --role-name brainybee-lambda-role --policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole # 3. Delete the IAM Role aws iam delete-role --role-name brainybee-lambda-role # 4. Remove local files rm function.zip lambda_function.py trust-policy.json out.json

Stretch Challenge

Goal: Implement a Dead Letter Queue (DLQ).

  1. Create an Amazon SQS queue named lambda-dlq.
  2. Update the Lambda configuration to send failed asynchronous invocations to this SQS queue using the --dead-letter-config parameter.
  3. Modify your code to intentionally throw an exception and verify the message arrives in the queue.

Cost Estimate

  • AWS Lambda: 1 Million free requests per month (Free Tier). This lab costs $0.00.
  • CloudWatch Logs: $0.50/GB ingested. This lab (a few KB) costs $0.00.
  • IAM/S3 Trigger: No additional cost for basic configuration.

Ready to study AWS Certified Developer - Associate (DVA-C02)?

Practice tests, flashcards, and all study notes — free, no sign-up needed.

Start Studying — Free