Saltar al contenido principal

Lab: Creación y Prueba de Funciones Lambda

Objetivo del Lab​

Crear, configurar y probar funciones Lambda con diferentes triggers. Este laboratorio utiliza LocalStack para simular el entorno de AWS.

Parte 1: Función Hello World​

Ejercicio 1.1: Crear la Función​

Código a crear: hello_world.py

import json
from datetime import datetime

def lambda_handler(event, context):
"""
Fonction Hello World avec logging
"""
# Log de l'événement reçu
print(f"Event received: {json.dumps(event)}")
print(f"Context: {context.function_name}, {context.aws_request_id}")

# Extraire le nom
name = event.get('name', 'World')
timestamp = datetime.now().isoformat()

# Construire la réponse
response = {
'statusCode': 200,
'headers': {
'Content-Type': 'application/json'
},
'body': json.dumps({
'message': f'Hello, {name}!',
'timestamp': timestamp,
'function': context.function_name
})
}

print(f"Response: {json.dumps(response)}")
return response

Ejercicio 1.2: Despliegue LocalStack​

# 1. Démarrer LocalStack (si pas déjà fait)
docker-compose up -d

# 2. Créer le rôle IAM
aws --endpoint-url=http://localhost:4566 iam create-role \
--role-name lambda-role \
--assume-role-policy-document '{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Principal": {"Service": "lambda.amazonaws.com"},
"Action": "sts:AssumeRole"
}]
}'

# 3. Zipper le code
zip hello_world.zip hello_world.py

# 4. Créer la fonction
aws --endpoint-url=http://localhost:4566 lambda create-function \
--function-name hello-world \
--runtime python3.9 \
--role arn:aws:iam::000000000000:role/lambda-role \
--handler hello_world.lambda_handler \
--zip-file fileb://hello_world.zip

# 5. Tester
aws --endpoint-url=http://localhost:4566 lambda invoke \
--function-name hello-world \
--payload '{"name": "LocalStack"}' \
response.json

cat response.json

Preguntas​

  1. ¿Cuál es el contenido de response.json?
  2. Modifique el código para añadir un contador de invocaciones. ¿Dónde almacenaría este contador?
  3. ¿Qué sucede si pasa un payload inválido (no JSON)?
💡 Soluciones
  1. Contenido de response.json:
{
"statusCode": 200,
"headers": {"Content-Type": "application/json"},
"body": "{\"message\": \"Hello, LocalStack!\", \"timestamp\": \"...\", \"function\": \"hello-world\"}"
}
  1. Contador de invocaciones:

    • DynamoDB para persistencia
    • Variable global (se reinicia en cada cold start)
    • CloudWatch Metrics
  2. Payload inválido:

    • Error de análisis JSON
    • La función recibe la cadena bruta
    • Manejar con try/except

Parte 2: Función con Variables de Entorno​

Ejercicio 2.1: Configuración​

# config_demo.py
import json
import os

def lambda_handler(event, context):
"""
Démonstration des variables d'environnement
"""
# Lire les variables d'environnement
config = {
'environment': os.environ.get('ENVIRONMENT', 'development'),
'log_level': os.environ.get('LOG_LEVEL', 'INFO'),
'api_endpoint': os.environ.get('API_ENDPOINT', 'http://localhost'),
'max_retries': int(os.environ.get('MAX_RETRIES', '3'))
}

print(f"Configuration loaded: {json.dumps(config)}")

# Simuler un comportement différent selon l'environnement
if config['environment'] == 'production':
message = "Running in PRODUCTION mode"
else:
message = f"Running in {config['environment']} mode"

return {
'statusCode': 200,
'body': json.dumps({
'message': message,
'config': config
})
}

Ejercicio 2.2: Despliegue con Variables​

# Créer avec variables d'environnement
aws --endpoint-url=http://localhost:4566 lambda create-function \
--function-name config-demo \
--runtime python3.9 \
--role arn:aws:iam::000000000000:role/lambda-role \
--handler config_demo.lambda_handler \
--zip-file fileb://config_demo.zip \
--environment 'Variables={
ENVIRONMENT=staging,
LOG_LEVEL=DEBUG,
API_ENDPOINT=https://api.example.com,
MAX_RETRIES=5
}'

# Tester
aws --endpoint-url=http://localhost:4566 lambda invoke \
--function-name config-demo \
response.json

# Modifier une variable
aws --endpoint-url=http://localhost:4566 lambda update-function-configuration \
--function-name config-demo \
--environment 'Variables={
ENVIRONMENT=production,
LOG_LEVEL=WARN,
API_ENDPOINT=https://api.example.com,
MAX_RETRIES=3
}'

Preguntas​

Complete la tabla:

VariableValor DevValor StagingValor Prod
ENVIRONMENT???
LOG_LEVEL???
MAX_RETRIES???
💡 Solución
VariableValor DevValor StagingValor Prod
ENVIRONMENTdevelopmentstagingproduction
LOG_LEVELDEBUGDEBUGWARN
MAX_RETRIES353

Parte 3: Trigger S3 (Simulado)​

Ejercicio 3.1: Procesador de Archivos​

# s3_processor.py
import json

def lambda_handler(event, context):
"""
Traite les événements S3 (upload de fichiers)
"""
results = []

for record in event.get('Records', []):
# Extraire les informations S3
s3_info = record.get('s3', {})
bucket = s3_info.get('bucket', {}).get('name', 'unknown')
key = s3_info.get('object', {}).get('key', 'unknown')
size = s3_info.get('object', {}).get('size', 0)
event_type = record.get('eventName', 'unknown')

print(f"Processing: s3://{bucket}/{key}")
print(f"Event: {event_type}, Size: {size} bytes")

# Simuler le traitement
result = {
'bucket': bucket,
'key': key,
'size': size,
'event': event_type,
'status': 'processed'
}

# Logique conditionnelle basée sur le type de fichier
if key.endswith('.jpg') or key.endswith('.png'):
result['action'] = 'image_processing'
elif key.endswith('.json'):
result['action'] = 'data_import'
elif key.endswith('.csv'):
result['action'] = 'csv_processing'
else:
result['action'] = 'archive'

results.append(result)
print(f"Result: {json.dumps(result)}")

return {
'statusCode': 200,
'body': json.dumps({
'processed': len(results),
'results': results
})
}

Ejercicio 3.2: Simular un Evento S3​

# Créer un fichier d'événement S3 simulé
cat > s3_event.json << 'EOF'
{
"Records": [
{
"eventName": "ObjectCreated:Put",
"s3": {
"bucket": {"name": "my-uploads"},
"object": {
"key": "images/photo.jpg",
"size": 1024000
}
}
},
{
"eventName": "ObjectCreated:Put",
"s3": {
"bucket": {"name": "my-uploads"},
"object": {
"key": "data/report.csv",
"size": 5000
}
}
}
]
}
EOF

# Déployer et tester
zip s3_processor.zip s3_processor.py

aws --endpoint-url=http://localhost:4566 lambda create-function \
--function-name s3-processor \
--runtime python3.9 \
--role arn:aws:iam::000000000000:role/lambda-role \
--handler s3_processor.lambda_handler \
--zip-file fileb://s3_processor.zip

aws --endpoint-url=http://localhost:4566 lambda invoke \
--function-name s3-processor \
--payload file://s3_event.json \
response.json

cat response.json | python -m json.tool

Preguntas​

  1. ¿Qué acción se asigna a photo.jpg?
  2. ¿Qué acción se asigna a report.csv?
  3. ¿Cómo modificaría el código para tratar de forma diferente los archivos > 1 MB?
💡 Soluciones
  1. photo.jpg → action: image_processing
  2. report.csv → action: csv_processing
  3. Añadir una condición:
if size > 1_000_000:  # > 1 MB
result['processing_mode'] = 'async' # Tratamiento asíncrono
else:
result['processing_mode'] = 'sync'

Parte 4: Manejo de Errores​

Ejercicio 4.1: Función con Errores​

# error_handling.py
import json

class ValidationError(Exception):
"""Erreur de validation personnalisée"""
pass

def validate_input(event):
"""Valide les données d'entrée"""
if 'name' not in event:
raise ValidationError("Le champ 'name' est requis")
if len(event['name']) < 2:
raise ValidationError("Le nom doit avoir au moins 2 caractères")
if 'age' in event and not isinstance(event['age'], int):
raise ValidationError("L'âge doit être un nombre entier")
return True

def lambda_handler(event, context):
"""
Fonction avec gestion d'erreurs complète
"""
print(f"Input: {json.dumps(event)}")

try:
# Valider l'entrée
validate_input(event)

# Traitement
name = event['name']
age = event.get('age', 'non spécifié')

return {
'statusCode': 200,
'body': json.dumps({
'message': f'Bonjour {name}!',
'age': age,
'status': 'success'
})
}

except ValidationError as e:
print(f"Validation error: {str(e)}")
return {
'statusCode': 400,
'body': json.dumps({
'error': 'Validation Error',
'message': str(e),
'status': 'failed'
})
}

except Exception as e:
print(f"Unexpected error: {str(e)}")
return {
'statusCode': 500,
'body': json.dumps({
'error': 'Internal Server Error',
'message': 'Une erreur inattendue s\'est produite',
'status': 'failed'
})
}

Ejercicio 4.2: Pruebas de Escenarios​

Pruebe con diferentes payloads y complete la tabla:

PayloadStatus CodeTipo de Error
{"name": "Alice"}??
{}??
{"name": "A"}??
{"name": "Bob", "age": "vingt"}??
{"name": "Charlie", "age": 25}??
💡 Soluciones
PayloadStatus CodeTipo de Error
{"name": "Alice"}200Ninguno
{}400ValidationError (name requerido)
{"name": "A"}400ValidationError (mínimo 2 caracteres)
{"name": "Bob", "age": "vingt"}400ValidationError (age int)
{"name": "Charlie", "age": 25}200Ninguno

Parte 5: Análisis de Rendimiento​

Ejercicio 5.1: Medir Tiempos de Ejecución​

# performance_test.py
import json
import time

def lambda_handler(event, context):
"""
Fonction pour mesurer les performances
"""
start_time = time.time()

# Simuler différentes charges de travail
workload = event.get('workload', 'light')

if workload == 'light':
# Travail léger
result = sum(range(1000))

elif workload == 'medium':
# Travail moyen
result = sum(range(100000))

elif workload == 'heavy':
# Travail lourd
result = sum(range(10000000))

else:
result = 0

execution_time = (time.time() - start_time) * 1000 # en ms
remaining_time = context.get_remaining_time_in_millis()

return {
'statusCode': 200,
'body': json.dumps({
'workload': workload,
'result': result,
'execution_time_ms': round(execution_time, 2),
'remaining_time_ms': remaining_time,
'memory_limit_mb': context.memory_limit_in_mb
})
}

Preguntas de Análisis​

  1. Ejecute con workload: light, medium y heavy. Anote los tiempos.
  2. ¿Qué sucede si el tiempo de ejecución supera el timeout?
  3. ¿Cómo optimizaría una función lenta?

Entregable Final​

Documento a Producir​

  1. Código de las 4 funciones (hello, config, s3, errors)
  2. Resultados de las pruebas (payloads y respuestas)
  3. Tabla de análisis de errores
  4. Recomendaciones de optimización

Criterios de Evaluación​

CriterioPuntos
Funciones creadas y probadas/30
Manejo de errores/20
Variables de entorno/15
Análisis de eventos S3/15
Calidad del código/10
Documentación/10
Total/100

Semana siguiente: MODULE 12 - Lambda Troubleshooting