Help me een Terraform-module implementeren voor serverloze architectuur op AWS
description
Gebruikers zullen expertise opdoen in het ontwerpen van efficiënte serverloze architecturen met Terraform, die schaalbaarheid en kosteneffectiviteit garanderen terwijl ze voldoen aan AWS-best practices.
prompt
try_prompt
Ik heb hulp nodig bij het maken van een Terraform-module die specifiek is ontworpen voor het implementeren van serverloze toepassingen op AWS. Mijn toepassingsvereisten omvatten: {{ ... more
generate_helper
...
tags
ai_answers
provider: openai
model: gpt-4.1-nano
Natuurlijk! Hier zijn richtlijnen en best practices voor het maken van een Terraform-module voor een serverloze toepassing op AWS met een event-gedreven architectuur en API-eindpunten:
1. Structuur van de Module:
- Modulariseer resources: scheid resources zoals Lambda, API Gateway, DynamoDB en IAM-rollen.
- Gebruik variabelen en outputs voor flexibiliteit en herbruikbaarheid.
2. Resource-configuratie:
- Lambda:
- Gebruik de nieuwste runtime (bv. Python 3.9, Node.js 16).
- Stel memory en timeout in op basis van de verwachte belasting.
- Beperk toegangsrechten door minimale IAM-rollen te gebruiken.
- Voeg versiebeheer toe en gebruik aliasen voor deployment.
- API Gateway:
- Kies voor REST API of HTTP API afhankelijk van je behoeften (HTTP API is goedkoper en sneller, REST API biedt meer functies).
- Stel CORS correct in indien nodig.
- Gebruik stage-parameters voor environment-specific configuraties.
- DynamoDB:
- Kies de juiste partition- en sorteer-sleutels.
- Stel throughput in of gebruik on-demand capaciteit.
- Voeg indexen toe indien nodig.
3. Event Source Mapping:
- Voor event-gedreven architectuur:
- Gebruik bijvoorbeeld DynamoDB Streams, S3 events, SNS/SQS of EventBridge.
- Configureer event source mapping met juiste batch-grootte en retries.
- Zorg dat Lambda de juiste rechten heeft om de event source te lezen.
4. Integratie met AWS-diensten:
- IAM-rollen en policies:
- Gebruik least privilege principe.
- Maak aparte rollen voor Lambda, API Gateway en andere services.
- Voeg inline policies of managed policies toe afhankelijk van de behoefte.
- Lambda en API Gateway:
- Configureer API Gateway als trigger voor Lambda met een proxy-integratie voor eenvoud.
- Gebruik Lambda authorizers indien beveiliging vereist.
5. Best practices:
- Versioneer je Lambda-functies en gebruik aliases voor deploys.
- Automatisering:
- Voeg CloudWatch Logs en Metrics toe voor monitoring.
- Gebruik Terraform lifecycle hooks om resources correct te beheren.
- Beveiliging:
- Gebruik IAM best practices.
- Overweeg VPC-integratie voor dataveiligheid indien nodig.
6. Documentatie en modulariteit:
- Documenteer parameters en outputs.
- Maak herbruikbare modules voor verschillende onderdelen.
7. Voorbeeld structuur:
```hcl
module "serverloze_app" {
source = "./modules/serverloze_app"
name = "mijn_app"
# andere variabelen
}
```
Door deze richtlijnen te volgen, creëer je een schaalbare, veilige en onderhoudsvriendelijke serverloze infrastructuur op AWS met Terraform.
provider: deepseek
model: deepseek-chat
Zeker, hier een uitgebreide handleiding voor het maken van een Terraform-module voor serverloze AWS-toepassingen met event-gedreven architectuur:
## 1. Module Structuur en Best Practices
```hcl
# modules/serverless-app/variables.tf
variable "app_name" {
type = string
description = "Naam van de applicatie"
}
variable "environment" {
type = string
description = "Omgeving (dev/staging/prod)"
}
variable "lambda_runtime" {
type = string
default = "python3.9"
description = "Lambda runtime environment"
}
variable "api_endpoints" {
type = map(object({
method = string
authorization = string
integration_type = string
}))
description = "API Gateway endpoints configuratie"
}
```
## 2. DynamoDB Configuratie
```hcl
# modules/serverless-app/dynamodb.tf
resource "aws_dynamodb_table" "main" {
name = "${var.app_name}-${var.environment}"
billing_mode = "PAY_PER_REQUEST"
hash_key = "id"
attribute {
name = "id"
type = "S"
}
# Global Secondary Index voor query flexibiliteit
global_secondary_index {
name = "GSI1"
hash_key = "gsi1_pk"
range_key = "gsi1_sk"
projection_type = "ALL"
}
tags = {
Environment = var.environment
Application = var.app_name
}
# Point-in-time recovery voor data bescherming
point_in_time_recovery {
enabled = true
}
}
```
## 3. Lambda Functie met Best Practices
```hcl
# modules/serverless-app/lambda.tf
resource "aws_lambda_function" "api_handler" {
filename = "lambda_function.zip"
function_name = "${var.app_name}-${var.environment}-handler"
role = aws_iam_role.lambda_exec.arn
handler = "lambda_function.lambda_handler"
runtime = var.lambda_runtime
timeout = 30
memory_size = 128
environment {
variables = {
DYNAMODB_TABLE = aws_dynamodb_table.main.name
ENVIRONMENT = var.environment
}
}
# Tracing met AWS X-Ray
tracing_config {
mode = "Active"
}
tags = {
Environment = var.environment
Application = var.app_name
}
}
# IAM Role voor Lambda
resource "aws_iam_role" "lambda_exec" {
name = "${var.app_name}-${var.environment}-lambda-role"
assume_role_policy = jsonencode({
Version = "2012-10-17"
Statement = [
{
Action = "sts:AssumeRole"
Effect = "Allow"
Principal = {
Service = "lambda.amazonaws.com"
}
}
]
})
}
resource "aws_iam_role_policy_attachment" "lambda_basic_execution" {
role = aws_iam_role.lambda_exec.name
policy_arn = "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"
}
resource "aws_iam_role_policy" "dynamodb_access" {
name = "${var.app_name}-dynamodb-access"
role = aws_iam_role.lambda_exec.id
policy = jsonencode({
Version = "2012-10-17"
Statement = [
{
Effect = "Allow"
Action = [
"dynamodb:GetItem",
"dynamodb:PutItem",
"dynamodb:UpdateItem",
"dynamodb:DeleteItem",
"dynamodb:Query",
"dynamodb:Scan"
]
Resource = [
aws_dynamodb_table.main.arn,
"${aws_dynamodb_table.main.arn}/index/*"
]
}
]
})
}
```
## 4. API Gateway Configuratie
```hcl
# modules/serverless-app/api_gateway.tf
resource "aws_apigatewayv2_api" "main" {
name = "${var.app_name}-${var.environment}"
protocol_type = "HTTP"
cors_configuration {
allow_origins = ["*"]
allow_methods = ["GET", "POST", "PUT", "DELETE", "OPTIONS"]
allow_headers = ["*"]
}
}
resource "aws_apigatewayv2_stage" "default" {
api_id = aws_apigatewayv2_api.main.id
name = var.environment
auto_deploy = true
# Access logging
access_log_settings {
destination_arn = aws_cloudwatch_log_group.api_gw.arn
format = jsonencode({
requestId = "$context.requestId"
ip = "$context.identity.sourceIp"
requestTime = "$context.requestTime"
httpMethod = "$context.httpMethod"
routeKey = "$context.routeKey"
status = "$context.status"
responseLength = "$context.responseLength"
integrationError = "$context.integration.error"
})
}
}
# Lambda Integration
resource "aws_apigatewayv2_integration" "lambda" {
api_id = aws_apigatewayv2_api.main.id
integration_type = "AWS_PROXY"
integration_method = "POST"
integration_uri = aws_lambda_function.api_handler.invoke_arn
}
# Dynamische route creatie
resource "aws_apigatewayv2_route" "routes" {
for_each = var.api_endpoints
api_id = aws_apigatewayv2_api.main.id
route_key = "${each.value.method} ${each.key}"
target = "integrations/${aws_apigatewayv2_integration.lambda.id}"
authorization_type = each.value.authorization
}
# Lambda Permission
resource "aws_lambda_permission" "api_gw" {
statement_id = "AllowExecutionFromAPIGateway"
action = "lambda:InvokeFunction"
function_name = aws_lambda_function.api_handler.function_name
principal = "apigateway.amazonaws.com"
source_arn = "${aws_apigatewayv2_api.main.execution_arn}/*/*"
}
```
## 5. Event Source Mapping (Voorbeeld met DynamoDB Stream)
```hcl
# modules/serverless-app/event_mapping.tf
resource "aws_lambda_event_source_mapping" "dynamodb_stream" {
event_source_arn = aws_dynamodb_table.main.stream_arn
function_name = aws_lambda_function.stream_handler.arn
starting_position = "LATEST"
batch_size = 100
# Filter criteria voor specifieke events
filter_criteria {
filter {
pattern = jsonencode({
eventName = ["INSERT", "MODIFY"]
})
}
}
}
```
## 6. Monitoring en Logging
```hcl
# modules/serverless-app/monitoring.tf
resource "aws_cloudwatch_log_group" "lambda" {
name = "/aws/lambda/${aws_lambda_function.api_handler.function_name}"
retention_in_days = 14
}
resource "aws_cloudwatch_log_group" "api_gw" {
name = "/aws/apigateway/${aws_apigatewayv2_api.main.name}"
retention_in_days = 14
}
# CloudWatch Alarms
resource "aws_cloudwatch_metric_alarm" "lambda_errors" {
alarm_name = "${var.app_name}-${var.environment}-lambda-errors"
comparison_operator = "GreaterThanThreshold"
evaluation_periods = "1"
metric_name = "Errors"
namespace = "AWS/Lambda"
period = "300"
statistic = "Sum"
threshold = "0"
alarm_description = "Monitor Lambda functie errors"
alarm_actions = [] # Voeg SNS topic toe voor notificaties
dimensions = {
FunctionName = aws_lambda_function.api_handler.function_name
}
}
```
## 7. Gebruik van de Module
```hcl
# main.tf
module "serverless_app" {
source = "./modules/serverless-app"
app_name = "mijn-app"
environment = "dev"
lambda_runtime = "python3.9"
api_endpoints = {
"/users" = {
method = "GET"
authorization = "NONE"
integration_type = "AWS_PROXY"
}
"/users/{id}" = {
method = "GET"
authorization = "NONE"
integration_type = "AWS_PROXY"
}
"/users" = {
method = "POST"
authorization = "NONE"
integration_type = "AWS_PROXY"
}
}
}
output "api_url" {
value = module.serverless_app.api_url
}
```
## Belangrijkste Best Practices:
1. **Security**: Gebruik minimale IAM permissions, encryptie at-rest en in-transit
2. **Monitoring**: Implementeer CloudWatch logs, metrics en alarms
3. **Error Handling**: Configureer Dead Letter Queues voor async verwerking
4. **Performance**: Optimaliseer Lambda memory size en timeout settings
5. **Cost Optimization**: Gebruik PAY_PER_REQUEST voor DynamoDB, monitor Lambda invocations
6. **Infrastructure as Code**: Gebruik Terraform workspaces voor environment scheiding
Deze module biedt een solide basis voor een event-gedreven serverloze applicatie op AWS met goede schaalbaarheid en beheerbaarheid.

