Création de Fonctions Lambda
Méthodes de Déploiement
Vue d'Ensemble
┌─────────────────────────────────────────────────────────────┐
│ MÉTHODES DE DÉPLOIEMENT │
├─────────────────────────────────────────────────────────────┤
│ │
│ 1. CONSOLE AWS │
│ ───────────── │
│ Interface web, idéal pour tests/apprentissage │
│ ✅ Simple ❌ Pas automatisable │
│ │
│ 2. AWS CLI │
│ ──────── │
│ Ligne de commande, scriptable │
│ ✅ Automatisable ⚠️ Plus complexe │
│ │
│ 3. SAM (Serverless Application Model) │
│ ─────────────────────────────────── │
│ Framework AWS pour serverless │
│ ✅ IaC ✅ Local testing ✅ Best practice │
│ │
│ 4. CloudFormation / Terraform │
│ ────────────────────────────── │
│ Infrastructure as Code complet │
│ ✅ Production ✅ Reproductible │
│ │
└─────────────────────────────────────────────────────────────┘
Création via AWS CLI
Étape 1 : Créer le Rôle IAM
# 1. Créer le fichier trust policy
cat > trust-policy.json << 'EOF'
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": "lambda.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
}
EOF
# 2. Créer le rôle
aws iam create-role \
--role-name lambda-basic-role \
--assume-role-policy-document file://trust-policy.json
# 3. Attacher la politique de base (logs)
aws iam attach-role-policy \
--role-name lambda-basic-role \
--policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
Étape 2 : Créer le Code
# lambda_function.py
import json
def lambda_handler(event, context):
"""
Fonction Hello World simple
"""
# Récupérer le nom depuis l'événement
name = event.get('name', 'World')
# Créer le message
message = f"Hello, {name}!"
# Log
print(f"Processing request for: {name}")
# Retourner la réponse
return {
'statusCode': 200,
'headers': {
'Content-Type': 'application/json'
},
'body': json.dumps({
'message': message,
'input': event
})
}
Étape 3 : Packager et Déployer
# 1. Zipper le code
zip function.zip lambda_function.py
# 2. Créer la fonction
aws lambda create-function \
--function-name hello-world \
--runtime python3.11 \
--role arn:aws:iam::123456789012:role/lambda-basic-role \
--handler lambda_function.lambda_handler \
--zip-file fileb://function.zip \
--timeout 30 \
--memory-size 256
# 3. Tester la fonction
aws lambda invoke \
--function-name hello-world \
--payload '{"name": "AWS"}' \
--cli-binary-format raw-in-base64-out \
response.json
# 4. Voir la réponse
cat response.json
Variables d'Environnement
Configuration
# Ajouter des variables d'environnement
aws lambda update-function-configuration \
--function-name hello-world \
--environment 'Variables={
DB_HOST=mydb.example.com,
DB_NAME=production,
LOG_LEVEL=INFO
}'
Utilisation dans le Code
import os
import json
def lambda_handler(event, context):
# Lire les variables d'environnement
db_host = os.environ.get('DB_HOST', 'localhost')
db_name = os.environ.get('DB_NAME', 'default')
log_level = os.environ.get('LOG_LEVEL', 'DEBUG')
print(f"[{log_level}] Connecting to {db_host}/{db_name}")
return {
'statusCode': 200,
'body': json.dumps({
'db_host': db_host,
'db_name': db_name
})
}
Trigger API Gateway
Architecture
┌─────────────────────────────────────────────────────────────┐
│ API GATEWAY + LAMBDA │
├─────────────────────────────────────────────────────────────┤
│ │
│ ┌──────────────────────────────────────────────────────┐ │
│ │ │ │
│ │ Client │ │
│ │ │ │ │
│ │ │ GET /hello?name=AWS │ │
│ │ ▼ │ │
│ │ ┌─────────────────┐ │ │
│ │ │ API Gateway │ │ │
│ │ │ │ │ │
│ │ │ • Authentification │ │
│ │ │ • Rate limiting │ │
│ │ │ • CORS │ │
│ │ └────────┬────────┘ │ │
│ │ │ │ │
│ │ │ Invoke │ │
│ │ ▼ │ │
│ │ ┌─────────────────┐ │ │
│ │ │ Lambda │ │ │
│ │ │ hello-world │ │ │
│ │ └────────┬────────┘ │ │
│ │ │ │ │
│ │ │ Response │ │
│ │ ▼ │ │
│ │ {"message": "Hello, AWS!"} │ │
│ │ │ │
│ └──────────────────────────────────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────┘
Créer l'API
# 1. Créer l'API HTTP (v2, plus simple)
aws apigatewayv2 create-api \
--name hello-api \
--protocol-type HTTP \
--target arn:aws:lambda:us-east-1:123456789012:function:hello-world
# 2. Ajouter la permission pour API Gateway
aws lambda add-permission \
--function-name hello-world \
--statement-id apigateway-invoke \
--action lambda:InvokeFunction \
--principal apigateway.amazonaws.com
Code pour API Gateway
import json
def lambda_handler(event, context):
"""
Handler pour API Gateway HTTP API
"""
# Extraire les paramètres
query_params = event.get('queryStringParameters', {}) or {}
name = query_params.get('name', 'World')
# Extraire le path
path = event.get('rawPath', '/')
method = event.get('requestContext', {}).get('http', {}).get('method', 'GET')
print(f"{method} {path} - name={name}")
return {
'statusCode': 200,
'headers': {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*' # CORS
},
'body': json.dumps({
'message': f'Hello, {name}!',
'path': path,
'method': method
})
}
Trigger S3
Configuration
# Ajouter permission pour S3
aws lambda add-permission \
--function-name process-upload \
--statement-id s3-trigger \
--action lambda:InvokeFunction \
--principal s3.amazonaws.com \
--source-arn arn:aws:s3:::my-bucket \
--source-account 123456789012
# Configurer le trigger sur le bucket
aws s3api put-bucket-notification-configuration \
--bucket my-bucket \
--notification-configuration '{
"LambdaFunctionConfigurations": [
{
"LambdaFunctionArn": "arn:aws:lambda:us-east-1:123456789012:function:process-upload",
"Events": ["s3:ObjectCreated:*"],
"Filter": {
"Key": {
"FilterRules": [
{"Name": "suffix", "Value": ".jpg"}
]
}
}
}
]
}'
Code pour S3
import json
import boto3
s3 = boto3.client('s3')
def lambda_handler(event, context):
"""
Traite les fichiers uploadés dans S3
"""
for record in event['Records']:
# Extraire les infos du fichier
bucket = record['s3']['bucket']['name']
key = record['s3']['object']['key']
size = record['s3']['object']['size']
print(f"Nouveau fichier: s3://{bucket}/{key} ({size} bytes)")
# Télécharger le fichier
response = s3.get_object(Bucket=bucket, Key=key)
content = response['Body'].read()
# Traiter le fichier (exemple: redimensionner image)
# processed = process_image(content)
# Sauvegarder le résultat
# s3.put_object(Bucket=bucket, Key=f"processed/{key}", Body=processed)
print(f"Traitement terminé pour {key}")
return {
'statusCode': 200,
'body': json.dumps('Traitement terminé')
}
Dépendances (Layers)
Concept
┌─────────────────────────────────────────────────────────────┐
│ LAMBDA LAYERS │
├─────────────────────────────────────────────────────────────┤
│ │
│ Les Layers permettent de partager du code/dépendances │
│ entre plusieurs fonctions │
│ │
│ SANS Layers : │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
│ │ Function A │ │ Function B │ │ Function C │ │
│ │ + numpy │ │ + numpy │ │ + numpy │ │
│ │ + pandas │ │ + pandas │ │ + requests │ │
│ │ (50 MB) │ │ (50 MB) │ │ (30 MB) │ │
│ └──────────────┘ └──────────────┘ └──────────────┘ │
│ │
│ AVEC Layers : │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
│ │ Function A │ │ Function B │ │ Function C │ │
│ │ (code only) │ │ (code only) │ │ (code only) │ │
│ │ (1 KB) │ │ (1 KB) │ │ (1 KB) │ │
│ └──────┬───────┘ └──────┬───────┘ └──────┬───────┘ │
│ │ │ │ │
│ └─────────────────┼─────────────────┘ │
│ │ │
│ ┌───────▼───────┐ │
│ │ Layer: libs │ │
│ │ numpy, pandas │ │
│ │ (50 MB) │ │
│ └───────────────┘ │
│ │
└─────────────────────────────────────────────────────────────┘
Créer un Layer
# 1. Créer la structure
mkdir -p python/lib/python3.11/site-packages
# 2. Installer les dépendances
pip install requests -t python/lib/python3.11/site-packages/
# 3. Zipper
zip -r layer.zip python/
# 4. Publier le layer
aws lambda publish-layer-version \
--layer-name my-dependencies \
--zip-file fileb://layer.zip \
--compatible-runtimes python3.11
# 5. Attacher à une fonction
aws lambda update-function-configuration \
--function-name hello-world \
--layers arn:aws:lambda:us-east-1:123456789012:layer:my-dependencies:1
Bonnes Pratiques
┌─────────────────────────────────────────────────────────────┐
│ BONNES PRATIQUES LAMBDA │
├─────────────────────────────────────────────────────────────┤
│ │
│ ✅ FAIRE │
│ ──────── │
│ • Garder les fonctions petites et focalisées │
│ • Utiliser des variables d'environnement │
│ • Réutiliser les connexions (hors du handler) │
│ • Logger avec print() ou logging │
│ • Gérer les erreurs proprement │
│ • Définir un timeout approprié │
│ │
│ ❌ ÉVITER │
│ ───────── │
│ • Fonctions monolithiques │
│ • Hardcoder les configurations │
│ • Créer des connexions dans le handler │
│ • Ignorer les erreurs │
│ • Timeout trop long (gaspillage si erreur) │
│ │
│ CODE OPTIMISÉ : │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ │ │
│ │ import boto3 │ │
│ │ import os │ │
│ │ │ │
│ │ # Connexions HORS du handler (réutilisées) │ │
│ │ dynamodb = boto3.resource('dynamodb') │ │
│ │ table = dynamodb.Table(os.environ['TABLE_NAME']) │ │
│ │ │ │
│ │ def lambda_handler(event, context): │ │
│ │ # Handler léger, connexion réutilisée │ │
│ │ return table.get_item(Key={'id': event['id']})│ │
│ │ │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────┘
Résumé
| Étape | Commande |
|---|---|
| Créer rôle | aws iam create-role |
| Créer fonction | aws lambda create-function |
| Tester | aws lambda invoke |
| Mettre à jour | aws lambda update-function-code |
| Ajouter trigger | aws lambda add-permission |
Prochaine section : Lab Lambda