survey-extraction/deployment/lambda.tf
2025-07-14 12:34:14 +00:00

57 lines
1.7 KiB
HCL

# Create an SQS queue that will trigger the Lambda
resource "aws_sqs_queue" "my_queue" {
name = "my-lambda-queue"
}
# IAM role that the Lambda function will assume to get permissions
resource "aws_iam_role" "lambda_exec_role" {
name = "lambda-exec-role"
assume_role_policy = jsonencode({
Version = "2012-10-17"
Statement = [
{
Action = "sts:AssumeRole"
Effect = "Allow"
Principal = {
Service = "lambda.amazonaws.com"
}
}
]
})
}
# Attach the basic execution policy (writes logs to CloudWatch) to the Lambda role
resource "aws_iam_role_policy_attachment" "lambda_basic_execution" {
role = aws_iam_role.lambda_exec_role.name
policy_arn = "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"
}
# Give Lambda permission to poll and process SQS messages
resource "aws_iam_role_policy_attachment" "sqs_access" {
role = aws_iam_role.lambda_exec_role.name
policy_arn = "arn:aws:iam::aws:policy/AWSLambdaSQSQueueExecutionRole"
}
# Create an ECR repository to store the Docker image for the Lambda function
resource "aws_ecr_repository" "lambda_repo" {
name = "lambda-hello-world"
}
# Define the Lambda function using a Docker image from ECR
resource "aws_lambda_function" "lambda_docker" {
function_name = "docker-hello-world"
role = aws_iam_role.lambda_exec_role.arn
package_type = "Image"
image_uri = "${aws_ecr_repository.lambda_repo.repository_url}:latest"
timeout = 10
}
# Connect the SQS queue to the Lambda so it gets triggered by incoming messages
resource "aws_lambda_event_source_mapping" "sqs_trigger" {
event_source_arn = aws_sqs_queue.my_queue.arn
function_name = aws_lambda_function.lambda_docker.arn
batch_size = 1
}