Pular para o conteúdo principal

Criação de Funções Lambda

Métodos de Deploy​

Visão Geral​

┌─────────────────────────────────────────────────────────────┐
│ MÉTODOS DE DEPLOY │
├─────────────────────────────────────────────────────────────┤
│ │
│ 1. CONSOLE AWS │
│ ───────────── │
│ Interface web, ideal para testes/aprendizado │
│ ✅ Simples ❌ Não automatizável │
│ │
│ 2. AWS CLI │
│ ──────── │
│ Linha de comando, scriptável │
│ ✅ Automatizável ⚠️ Mais complexo │
│ │
│ 3. SAM (Serverless Application Model) │
│ ─────────────────────────────────── │
│ Framework AWS para serverless │
│ ✅ IaC ✅ Teste local ✅ Melhor prática │
│ │
│ 4. CloudFormation / Terraform │
│ ────────────────────────────── │
│ Infrastructure as Code completa │
│ ✅ Produção ✅ Reprodutível │
│ │
└─────────────────────────────────────────────────────────────┘

Criação via AWS CLI​

Etapa 1: Criar o Papel IAM​

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

# 2. Criar o papel
aws iam create-role \
--role-name lambda-basic-role \
--assume-role-policy-document file://trust-policy.json

# 3. Anexar a 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

Etapa 2: Criar o Código​

# lambda_function.py
import json

def lambda_handler(event, context):
"""
Função Hello World simples
"""
# Recuperar o nome do evento
name = event.get('name', 'World')

# Criar a mensagem
message = f"Hello, {name}!"

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

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

Etapa 3: Empacotar e Fazer o Deploy​

# 1. Compactar o código
zip function.zip lambda_function.py

# 2. Criar a função
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. Testar a função
aws lambda invoke \
--function-name hello-world \
--payload '{"name": "AWS"}' \
--cli-binary-format raw-in-base64-out \
response.json

# 4. Ver a resposta
cat response.json

Variáveis de Ambiente​

Configuração​

# Adicionar variáveis de ambiente
aws lambda update-function-configuration \
--function-name hello-world \
--environment 'Variables={
DB_HOST=mydb.example.com,
DB_NAME=production,
LOG_LEVEL=INFO
}'

Uso no Código​

import os
import json

def lambda_handler(event, context):
# Ler as variáveis de ambiente
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​

Arquitetura​

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

Criar a API​

# 1. Criar a API HTTP (v2, mais simples)
aws apigatewayv2 create-api \
--name hello-api \
--protocol-type HTTP \
--target arn:aws:lambda:us-east-1:123456789012:function:hello-world

# 2. Adicionar permissão 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
"""
# Extrair os parâmetros
query_params = event.get('queryStringParameters', {}) or {}
name = query_params.get('name', 'World')

# Extrair o 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​

Configuração​

# Adicionar permissão 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 o trigger no 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):
"""
Processa arquivos enviados para o S3
"""
for record in event['Records']:
# Extrair informações do arquivo
bucket = record['s3']['bucket']['name']
key = record['s3']['object']['key']
size = record['s3']['object']['size']

print(f"Novo arquivo: s3://{bucket}/{key} ({size} bytes)")

# Baixar o arquivo
response = s3.get_object(Bucket=bucket, Key=key)
content = response['Body'].read()

# Processar o arquivo (exemplo: redimensionar imagem)
# processed = process_image(content)

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

print(f"Processamento finalizado para {key}")

return {
'statusCode': 200,
'body': json.dumps('Processamento finalizado')
}

Dependências (Layers)​

Conceito​

┌─────────────────────────────────────────────────────────────┐
│ LAMBDA LAYERS │
├─────────────────────────────────────────────────────────────┤
│ │
│ Os Layers permitem compartilhar código/dependências │
│ entre várias funções │
│ │
│ SEM Layers: │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
│ │ Function A │ │ Function B │ │ Function C │ │
│ │ + numpy │ │ + numpy │ │ + numpy │ │
│ │ + pandas │ │ + pandas │ │ + requests │ │
│ │ (50 MB) │ │ (50 MB) │ │ (30 MB) │ │
│ └──────────────┘ └──────────────┘ └──────────────┘ │
│ │
│ COM Layers: │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
│ │ Function A │ │ Function B │ │ Function C │ │
│ │ (apenas código)│ │ (apenas código)│ │ (apenas código)│ │
│ │ (1 KB) │ │ (1 KB) │ │ (1 KB) │ │
│ └──────┬───────┘ └──────┬───────┘ └──────┬───────┘ │
│ │ │ │ │
│ └─────────────────┼─────────────────┘ │
│ │ │
│ ┌───────▼───────┐ │
│ │ Layer: libs │ │
│ │ numpy, pandas │ │
│ │ (50 MB) │ │
│ └───────────────┘ │
│ │
└─────────────────────────────────────────────────────────────┘

Criar um Layer​

# 1. Criar a estrutura
mkdir -p python/lib/python3.11/site-packages

# 2. Instalar as dependências
pip install requests -t python/lib/python3.11/site-packages/

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

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

# 5. Anexar a uma função
aws lambda update-function-configuration \
--function-name hello-world \
--layers arn:aws:lambda:us-east-1:123456789012:layer:my-dependencies:1

Boas Práticas​

┌─────────────────────────────────────────────────────────────┐
│ BOAS PRÁTICAS LAMBDA │
├─────────────────────────────────────────────────────────────┤
│ │
│ ✅ FAZER │
│ ──────── │
│ • Mantenha as funções pequenas e focadas │
│ • Use variáveis de ambiente │
│ • Reutilize conexões (fora do handler) │
│ • Faça logs com print() ou logging │
│ • Trate erros de forma adequada │
│ • Defina um timeout apropriado │
│ │
│ ❌ EVITAR │
│ ───────── │
│ • Funções monolíticas │
│ • Hardcode de configurações │
│ • Criar conexões dentro do handler │
│ • Ignorar erros │
│ • Timeout muito longo (desperdício em caso de erro) │
│ │
│ CÓDIGO OTIMIZADO: │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ │ │
│ │ import boto3 │ │
│ │ import os │ │
│ │ │ │
│ │ # Conexões FORA do handler (reutilizadas) │ │
│ │ dynamodb = boto3.resource('dynamodb') │ │
│ │ table = dynamodb.Table(os.environ['TABLE_NAME']) │ │
│ │ │ │
│ │ def lambda_handler(event, context): │ │
│ │ # Handler leve, conexão reutilizada │ │
│ │ return table.get_item(Key={'id': event['id']}) │ │
│ │ │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────┘

Resumo​

EtapaComando
Criar papelaws iam create-role
Criar funçãoaws lambda create-function
Testaraws lambda invoke
Atualizaraws lambda update-function-code
Adicionar triggeraws lambda add-permission

Próxima seção: Lab Lambda