Saltar al contenido principal

Creación de Funciones Lambda

Métodos de Despliegue​

Visión General​

┌─────────────────────────────────────────────────────────────┐
│ MÉTODOS DE DESPLIEGUE │
├─────────────────────────────────────────────────────────────┤
│ │
│ 1. CONSOLE AWS │
│ ───────────── │
│ Interfaz web, ideal para pruebas/aprendizaje │
│ ✅ Sencillo ❌ No automatizable │
│ │
│ 2. AWS CLI │
│ ──────── │
│ Línea de comandos, scriptable │
│ ✅ Automatizable ⚠️ Más complejo │
│ │
│ 3. SAM (Serverless Application Model) │
│ ─────────────────────────────────── │
│ Framework AWS para serverless │
│ ✅ IaC ✅ Pruebas locales ✅ Mejores prácticas │
│ │
│ 4. CloudFormation / Terraform │
│ ────────────────────────────── │
│ Infraestructura como Código completa │
│ ✅ Producción ✅ Reproducible │
│ │
└─────────────────────────────────────────────────────────────┘

Creación vía AWS CLI​

Paso 1: Crear el Rol IAM​

# 1. Crear el archivo trust policy
cat > trust-policy.json << 'EOF'
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": "lambda.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
}
EOF

# 2. Crear el rol
aws iam create-role \
--role-name lambda-basic-role \
--assume-role-policy-document file://trust-policy.json

# 3. Adjuntar la política básica (logs)
aws iam attach-role-policy \
--role-name lambda-basic-role \
--policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole

Paso 2: Crear el Código​

# lambda_function.py
import json

def lambda_handler(event, context):
"""
Función Hello World simple
"""
# Obtener el nombre desde el evento
name = event.get('name', 'World')

# Crear el mensaje
message = f"Hello, {name}!"

# Log
print(f"Processing request for: {name}")

# Retornar la respuesta
return {
'statusCode': 200,
'headers': {
'Content-Type': 'application/json'
},
'body': json.dumps({
'message': message,
'input': event
})
}

Paso 3: Empaquetar y Desplegar​

# 1. Comprimir el código
zip function.zip lambda_function.py

# 2. Crear la función
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. Probar la función
aws lambda invoke \
--function-name hello-world \
--payload '{"name": "AWS"}' \
--cli-binary-format raw-in-base64-out \
response.json

# 4. Ver la respuesta
cat response.json

Variables de Entorno​

Configuración​

# Agregar variables de entorno
aws lambda update-function-configuration \
--function-name hello-world \
--environment 'Variables={
DB_HOST=mydb.example.com,
DB_NAME=production,
LOG_LEVEL=INFO
}'

Uso en el Código​

import os
import json

def lambda_handler(event, context):
# Leer las variables de entorno
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​

Arquitectura​

┌─────────────────────────────────────────────────────────────┐
│ API GATEWAY + LAMBDA │
├─────────────────────────────────────────────────────────────┤
│ │
│ ┌──────────────────────────────────────────────────────┐ │
│ │ │ │
│ │ Cliente │ │
│ │ │ │ │
│ │ │ GET /hello?name=AWS │ │
│ │ ▼ │ │
│ │ ┌─────────────────┐ │ │
│ │ │ API Gateway │ │ │
│ │ │ │ │ │
│ │ │ • Autenticación │ │
│ │ │ • Rate limiting │ │
│ │ │ • CORS │ │
│ │ └────────┬────────┘ │ │
│ │ │ │ │
│ │ │ Invoke │ │
│ │ ▼ │ │
│ │ ┌─────────────────┐ │ │
│ │ │ Lambda │ │ │
│ │ │ hello-world │ │ │
│ │ └────────┬────────┘ │ │
│ │ │ │ │
│ │ │ Response │ │
│ │ ▼ │ │
│ │ {"message": "Hello, AWS!"} │ │
│ │ │ │
│ └──────────────────────────────────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────┘

Crear la API​

# 1. Crear la API HTTP (v2, más simple)
aws apigatewayv2 create-api \
--name hello-api \
--protocol-type HTTP \
--target arn:aws:lambda:us-east-1:123456789012:function:hello-world

# 2. Agregar el permiso para API Gateway
aws lambda add-permission \
--function-name hello-world \
--statement-id apigateway-invoke \
--action lambda:InvokeFunction \
--principal apigateway.amazonaws.com

Código para API Gateway​

import json

def lambda_handler(event, context):
"""
Handler para API Gateway HTTP API
"""
# Extraer los parámetros
query_params = event.get('queryStringParameters', {}) or {}
name = query_params.get('name', 'World')

# Extraer el 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​

Configuración​

# Agregar permiso para 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

# Configurar el trigger en el 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"}
]
}
}
}
]
}'

Código para S3​

import json
import boto3

s3 = boto3.client('s3')

def lambda_handler(event, context):
"""
Procesa los archivos subidos en S3
"""
for record in event['Records']:
# Extraer la información del archivo
bucket = record['s3']['bucket']['name']
key = record['s3']['object']['key']
size = record['s3']['object']['size']

print(f"Nuevo archivo: s3://{bucket}/{key} ({size} bytes)")

# Descargar el archivo
response = s3.get_object(Bucket=bucket, Key=key)
content = response['Body'].read()

# Procesar el archivo (ejemplo: redimensionar imagen)
# processed = process_image(content)

# Guardar el resultado
# s3.put_object(Bucket=bucket, Key=f"processed/{key}", Body=processed)

print(f"Procesamiento terminado para {key}")

return {
'statusCode': 200,
'body': json.dumps('Procesamiento terminado')
}

Dependencias (Layers)​

Concepto​

┌─────────────────────────────────────────────────────────────┐
│ LAMBDA LAYERS │
├─────────────────────────────────────────────────────────────┤
│ │
│ Los Layers permiten compartir código/dependencias │
│ entre varias funciones │
│ │
│ SIN Layers : │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
│ │ Function A │ │ Function B │ │ Function C │ │
│ │ + numpy │ │ + numpy │ │ + numpy │ │
│ │ + pandas │ │ + pandas │ │ + requests │ │
│ │ (50 MB) │ │ (50 MB) │ │ (30 MB) │ │
│ └──────────────┘ └──────────────┘ └──────────────┘ │
│ │
│ CON Layers : │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
│ │ Function A │ │ Function B │ │ Function C │ │
│ │ (solo código)│ │ (solo código)│ │ (solo código)│ │
│ │ (1 KB) │ │ (1 KB) │ │ (1 KB) │ │
│ └──────┬───────┘ └──────┬───────┘ └──────┬───────┘ │
│ │ │ │ │
│ └─────────────────┼─────────────────┘ │
│ │ │
│ ┌───────▼───────┐ │
│ │ Layer: libs │ │
│ │ numpy, pandas │ │
│ │ (50 MB) │ │
│ └───────────────┘ │
│ │
└─────────────────────────────────────────────────────────────┘

Crear un Layer​

# 1. Crear la estructura
mkdir -p python/lib/python3.11/site-packages

# 2. Instalar las dependencias
pip install requests -t python/lib/python3.11/site-packages/

# 3. Comprimir
zip -r layer.zip python/

# 4. Publicar el layer
aws lambda publish-layer-version \
--layer-name my-dependencies \
--zip-file fileb://layer.zip \
--compatible-runtimes python3.11

# 5. Adjuntar a una función
aws lambda update-function-configuration \
--function-name hello-world \
--layers arn:aws:lambda:us-east-1:123456789012:layer:my-dependencies:1

Buenas Prácticas​

┌─────────────────────────────────────────────────────────────┐
│ BUENAS PRÁCTICAS LAMBDA │
├─────────────────────────────────────────────────────────────┤
│ │
│ ✅ HACER │
│ ──────── │
│ • Mantener las funciones pequeñas y enfocadas │
│ • Usar variables de entorno │
│ • Reutilizar conexiones (fuera del handler) │
│ • Registrar logs con print() o logging │
│ • Manejar errores correctamente │
│ • Definir un timeout apropiado │
│ │
│ ❌ EVITAR │
│ ───────── │
│ • Funciones monolíticas │
│ • Hardcodear configuraciones │
│ • Crear conexiones dentro del handler │
│ • Ignorar errores │
│ • Timeout demasiado largo (desperdicio si hay error) │
│ │
│ CÓDIGO OPTIMIZADO: │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ │ │
│ │ import boto3 │ │
│ │ import os │ │
│ │ │ │
│ │ # Conexiones FUERA del handler (reutilizadas) │ │
│ │ dynamodb = boto3.resource('dynamodb') │ │
│ │ table = dynamodb.Table(os.environ['TABLE_NAME']) │ │
│ │ │ │
│ │ def lambda_handler(event, context): │ │
│ │ # Handler ligero, conexión reutilizada │ │
│ │ return table.get_item(Key={'id': event['id']})│ │
│ │ │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────┘

Resumen​

PasoComando
Crear rolaws iam create-role
Crear funciónaws lambda create-function
Probaraws lambda invoke
Actualizaraws lambda update-function-code
Agregar triggeraws lambda add-permission

Próxima sección: Lab Lambda