Lab : Criação e Teste de Funções Lambda
Objetivo do Lab
Criar, configurar e testar funções Lambda com diferentes triggers. Este lab utiliza o LocalStack para simular o ambiente AWS.
Parte 1 : Função Hello World
Exercício 1.1 : Criar a Função
Código a criar: hello_world.py
import json
from datetime import datetime
def lambda_handler(event, context):
"""
Função Hello World com logging
"""
# Log do evento recebido
print(f"Event received: {json.dumps(event)}")
print(f"Context: {context.function_name}, {context.aws_request_id}")
# Extrair o nome
name = event.get('name', 'World')
timestamp = datetime.now().isoformat()
# Construir a resposta
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
Exercício 1.2 : Deploy LocalStack
# 1. Iniciar o LocalStack (se ainda não estiver rodando)
docker-compose up -d
# 2. Criar o papel 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. Compactar o código
zip hello_world.zip hello_world.py
# 4. Criar a função
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. Testar
aws --endpoint-url=http://localhost:4566 lambda invoke \
--function-name hello-world \
--payload '{"name": "LocalStack"}' \
response.json
cat response.json
Perguntas
- Qual é o conteúdo de
response.json? - Modifique o código para adicionar um contador de invocações. Onde você armazenaria esse contador?
- O que acontece se você passar um payload inválido (não JSON)?
💡 Soluções
- Conteúdo de response.json:
{
"statusCode": 200,
"headers": {"Content-Type": "application/json"},
"body": "{\"message\": \"Hello, LocalStack!\", \"timestamp\": \"...\", \"function\": \"hello-world\"}"
}
-
Contador de invocações:
- DynamoDB para persistência
- Variável global (reset a cada cold start)
- CloudWatch Metrics
-
Payload inválido:
- Erro de parsing JSON
- A função recebe a string bruta
- Tratar com try/except
Parte 2 : Função com Variáveis de Ambiente
Exercício 2.1 : Configuração
# config_demo.py
import json
import os
def lambda_handler(event, context):
"""
Demonstração de variáveis de ambiente
"""
# Ler as variáveis de ambiente
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)}")
# Simular comportamento diferente conforme o ambiente
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
})
}
Exercício 2.2 : Deploy com Variáveis
# Criar com variáveis de ambiente
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
}'
# Testar
aws --endpoint-url=http://localhost:4566 lambda invoke \
--function-name config-demo \
response.json
# Modificar uma variável
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
}'
Perguntas
Complete a tabela:
| Variável | Valor Dev | Valor Staging | Valor Prod |
|---|---|---|---|
| ENVIRONMENT | ? | ? | ? |
| LOG_LEVEL | ? | ? | ? |
| MAX_RETRIES | ? | ? | ? |
💡 Solução
| Variável | Valor Dev | Valor Staging | Valor Prod |
|---|---|---|---|
| ENVIRONMENT | development | staging | production |
| LOG_LEVEL | DEBUG | DEBUG | WARN |
| MAX_RETRIES | 3 | 5 | 3 |
Parte 3 : Trigger S3 (Simulado)
Exercício 3.1 : Processador de Arquivos
# s3_processor.py
import json
def lambda_handler(event, context):
"""
Processa eventos S3 (upload de arquivos)
"""
results = []
for record in event.get('Records', []):
# Extrair informações do 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")
# Simular o processamento
result = {
'bucket': bucket,
'key': key,
'size': size,
'event': event_type,
'status': 'processed'
}
# Lógica condicional baseada no tipo de arquivo
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
})
}
Exercício 3.2 : Simular um Evento S3
# Criar um arquivo de evento S3 simulado
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
# Deploy e teste
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
Perguntas
- Qual ação é atribuída a
photo.jpg? - Qual ação é atribuída a
report.csv? - Como você modificaria o código para tratar de forma diferente arquivos > 1 MB?
💡 Soluções
photo.jpg→ action:image_processingreport.csv→ action:csv_processing- Adicionar uma condição:
if size > 1_000_000: # > 1 MB
result['processing_mode'] = 'async' # Processamento assíncrono
else:
result['processing_mode'] = 'sync'
Parte 4 : Tratamento de Erros
Exercício 4.1 : Função com Erros
# error_handling.py
import json
class ValidationError(Exception):
"""Erro de validação personalizada"""
pass
def validate_input(event):
"""Valida os dados de entrada"""
if 'name' not in event:
raise ValidationError("O campo 'name' é obrigatório")
if len(event['name']) < 2:
raise ValidationError("O nome deve ter pelo menos 2 caracteres")
if 'age' in event and not isinstance(event['age'], int):
raise ValidationError("A idade deve ser um número inteiro")
return True
def lambda_handler(event, context):
"""
Função com tratamento completo de erros
"""
print(f"Input: {json.dumps(event)}")
try:
# Validar entrada
validate_input(event)
# Processamento
name = event['name']
age = event.get('age', 'não especificado')
return {
'statusCode': 200,
'body': json.dumps({
'message': f'Olá {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': 'Ocorreu um erro inesperado',
'status': 'failed'
})
}
Exercício 4.2 : Testes de Cenários
Teste com diferentes payloads e complete a tabela:
| Payload | Status Code | Tipo de Erro |
|---|---|---|
{"name": "Alice"} | ? | ? |
{} | ? | ? |
{"name": "A"} | ? | ? |
{"name": "Bob", "age": "vinte"} | ? | ? |
{"name": "Charlie", "age": 25} | ? | ? |
💡 Soluções
| Payload | Status Code | Tipo de Erro |
|---|---|---|
{"name": "Alice"} | 200 | Nenhum |
{} | 400 | ValidationError (name obrigatório) |
{"name": "A"} | 400 | ValidationError (mín. 2 caracteres) |
{"name": "Bob", "age": "vinte"} | 400 | ValidationError (idade int) |
{"name": "Charlie", "age": 25} | 200 | Nenhum |
Parte 5 : Análise de Performance
Exercício 5.1 : Medir Tempos de Execução
# performance_test.py
import json
import time
def lambda_handler(event, context):
"""
Função para medir performance
"""
start_time = time.time()
# Simular diferentes cargas de trabalho
workload = event.get('workload', 'light')
if workload == 'light':
# Trabalho leve
result = sum(range(1000))
elif workload == 'medium':
# Trabalho médio
result = sum(range(100000))
elif workload == 'heavy':
# Trabalho pesado
result = sum(range(10000000))
else:
result = 0
execution_time = (time.time() - start_time) * 1000 # em 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
})
}
Perguntas de Análise
- Execute com
workload: light,mediumeheavy. Anote os tempos. - O que acontece se o tempo de execução ultrapassar o timeout?
- Como você otimizaria uma função lenta?
Entregável Final
Documento a Produzir
- Código das 4 funções (hello, config, s3, errors)
- Resultados dos testes (payloads e respostas)
- Tabela de análise de erros
- Recomendações de otimização
Critérios de Avaliação
| Critério | Pontos |
|---|---|
| Funções criadas e testadas | /30 |
| Tratamento de erros | /20 |
| Variáveis de ambiente | /15 |
| Análise de eventos S3 | /15 |
| Qualidade do código | /10 |
| Documentação | /10 |
| Total | /100 |
Semana seguinte: MODULE 12 - Lambda Troubleshooting