Lab : Création et Test de Fonctions Lambda
Objectif du Lab
Créer, configurer et tester des fonctions Lambda avec différents triggers. Ce lab utilise LocalStack pour simuler l'environnement AWS.
Partie 1 : Fonction Hello World
Exercice 1.1 : Créer la Fonction
Code à créer : 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
Exercice 1.2 : Déploiement 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
Questions
- Quel est le contenu de
response.json? - Modifiez le code pour ajouter un compteur d'invocations. Où stockeriez-vous ce compteur ?
- Que se passe-t-il si vous passez un payload invalide (pas JSON) ?
💡 Solutions
- Contenu response.json :
{
"statusCode": 200,
"headers": {"Content-Type": "application/json"},
"body": "{\"message\": \"Hello, LocalStack!\", \"timestamp\": \"...\", \"function\": \"hello-world\"}"
}
-
Compteur d'invocations :
- DynamoDB pour persistance
- Variable globale (reset à chaque cold start)
- CloudWatch Metrics
-
Payload invalide :
- Erreur de parsing JSON
- La fonction reçoit la chaîne brute
- Gérer avec try/except
Partie 2 : Fonction avec Variables d'Environnement
Exercice 2.1 : Configuration
# 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
})
}
Exercice 2.2 : Déploiement avec 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
}'
Questions
Complétez le tableau :
| Variable | Valeur Dev | Valeur Staging | Valeur Prod |
|---|---|---|---|
| ENVIRONMENT | ? | ? | ? |
| LOG_LEVEL | ? | ? | ? |
| MAX_RETRIES | ? | ? | ? |
💡 Solution
| Variable | Valeur Dev | Valeur Staging | Valeur Prod |
|---|---|---|---|
| ENVIRONMENT | development | staging | production |
| LOG_LEVEL | DEBUG | DEBUG | WARN |
| MAX_RETRIES | 3 | 5 | 3 |
Partie 3 : Trigger S3 (Simulé)
Exercice 3.1 : Processeur de Fichiers
# 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
})
}
Exercice 3.2 : Simuler un Événement 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
Questions
- Quelle action est assignée à
photo.jpg? - Quelle action est assignée à
report.csv? - Comment modifieriez-vous le code pour traiter différemment les fichiers > 1 MB ?
💡 Solutions
photo.jpg→ action:image_processingreport.csv→ action:csv_processing- Ajouter une condition :
if size > 1_000_000: # > 1 MB
result['processing_mode'] = 'async' # Traitement asynchrone
else:
result['processing_mode'] = 'sync'
Partie 4 : Gestion des Erreurs
Exercice 4.1 : Fonction avec Erreurs
# 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'
})
}
Exercice 4.2 : Tests de Scénarios
Testez avec différents payloads et complétez le tableau :
| Payload | Status Code | Type d'Erreur |
|---|---|---|
{"name": "Alice"} | ? | ? |
{} | ? | ? |
{"name": "A"} | ? | ? |
{"name": "Bob", "age": "vingt"} | ? | ? |
{"name": "Charlie", "age": 25} | ? | ? |
💡 Solutions
| Payload | Status Code | Type d'Erreur |
|---|---|---|
{"name": "Alice"} | 200 | Aucune |
{} | 400 | ValidationError (name requis) |
{"name": "A"} | 400 | ValidationError (min 2 chars) |
{"name": "Bob", "age": "vingt"} | 400 | ValidationError (age int) |
{"name": "Charlie", "age": 25} | 200 | Aucune |
Partie 5 : Analyse de Performance
Exercice 5.1 : Mesurer les Temps d'Exécution
# 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
})
}
Questions d'Analyse
- Exécutez avec
workload: light,medium, etheavy. Notez les temps. - Que se passe-t-il si le temps d'exécution dépasse le timeout ?
- Comment optimiseriez-vous une fonction lente ?
Livrable Final
Document à Produire
- Code des 4 fonctions (hello, config, s3, errors)
- Résultats des tests (payloads et réponses)
- Tableau d'analyse des erreurs
- Recommandations d'optimisation
Critères d'Évaluation
| Critère | Points |
|---|---|
| Fonctions créées et testées | /30 |
| Gestion des erreurs | /20 |
| Variables d'environnement | /15 |
| Analyse des événements S3 | /15 |
| Qualité du code | /10 |
| Documentation | /10 |
| Total | /100 |
Semaine suivante : MODULE 12 - Lambda Dépannage