Skip to content

avansledright/aws-lambda-pydantic-example

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

AWS Lambda with PyDantic Layer - Terraform Deployment

This Terraform configuration deploys an AWS Lambda Layer containing the PyDantic library for ARM64 architecture, along with a Lambda function that demonstrates PyDantic functionality.

Prerequisites

  • Terraform >= 1.0
  • AWS CLI configured with appropriate credentials
  • Python 3.12 and pip installed locally
  • AWS account with permissions to create Lambda functions, IAM roles, and CloudWatch logs

Project Structure

.
├── main.tf                      # Main Terraform configuration
├── variables.tf                 # Input variables
├── outputs.tf                   # Output values
├── layer/
│   └── requirements.txt         # Python dependencies for Lambda Layer
└── lambda/
    └── lambda_function.py       # Lambda function code

What This Deploys

  1. Lambda Layer (pydantic-layer):

    • Contains PyDantic 2.9.2 library
    • Built for ARM64 architecture
    • Compatible with Python 3.11 and 3.12 runtimes
  2. Lambda Function (pydantic-test-function):

    • Uses Python 3.12 runtime on ARM64
    • Validates user data using PyDantic models
    • Demonstrates PyDantic's validation capabilities
  3. Supporting Resources:

    • IAM role for Lambda execution
    • CloudWatch log group for function logs

Deployment Steps

1. Initialize Terraform

terraform init

2. Review the Plan

terraform plan

3. Deploy

terraform apply

Type yes when prompted to confirm deployment.

4. Note the Outputs

After successful deployment, Terraform will output:

  • Lambda function name and ARN
  • Lambda layer ARN
  • Test command for invoking the function

Testing the Lambda Function

Using AWS CLI (from Terraform output)

aws lambda invoke \
  --function-name pydantic-test-function \
  --payload '{"name": "John Doe", "email": "john@example.com", "age": 30}' \
  response.json && cat response.json

Test Cases

Valid Input (Success):

aws lambda invoke \
  --function-name pydantic-test-function \
  --payload '{"name": "Jane Smith", "email": "jane@example.com", "age": 25, "city": "New York"}' \
  response.json && cat response.json

Expected response:

{
  "statusCode": 200,
  "body": "{\"message\": \"PyDantic validation successful!\", ...}"
}

Invalid Email (Validation Error):

aws lambda invoke \
  --function-name pydantic-test-function \
  --payload '{"name": "John Doe", "email": "invalid-email", "age": 30}' \
  response.json && cat response.json

Expected response:

{
  "statusCode": 400,
  "body": "{\"message\": \"PyDantic validation failed\", \"errors\": [...]}"
}

Invalid Age (Validation Error):

aws lambda invoke \
  --function-name pydantic-test-function \
  --payload '{"name": "John Doe", "email": "john@example.com", "age": -5}' \
  response.json && cat response.json

PyDantic Model Details

The Lambda function uses the following PyDantic model:

class User(BaseModel):
    name: str           # Required, 1-100 characters
    email: EmailStr     # Required, valid email format
    age: int            # Required, 0-150
    city: Optional[str] # Optional field

Cleanup

To remove all deployed resources:

terraform destroy

Type yes when prompted to confirm deletion.

Customization

Change AWS Region

Edit variables.tf or pass the variable:

terraform apply -var="aws_region=us-west-2"

Update PyDantic Version

Edit layer/requirements.txt and run terraform apply again.

Modify Lambda Configuration

Edit the aws_lambda_function resource in main.tf to adjust:

  • Memory size
  • Timeout
  • Environment variables
  • Runtime version

Troubleshooting

Layer Build Issues

If the layer build fails, ensure:

  • Python 3.12 is installed
  • pip is available in PATH
  • You have internet connectivity to download packages

Lambda Invocation Errors

Check CloudWatch Logs:

aws logs tail /aws/lambda/pydantic-test-function --follow

Architecture Mismatch

Ensure you're building for ARM64 architecture. The pip install command includes --platform manylinux2014_aarch64.

Notes

  • The Lambda function runs on ARM64 (Graviton2) for cost efficiency
  • PyDantic version is pinned to 2.9.2 for stability
  • CloudWatch logs are retained for 7 days
  • The layer can be reused by other Lambda functions

License

This is example code for demonstration purposes.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published