# Lambda Function (used in Lab 06: Integrated AI Solution) # Orchestrates multiple AI services for document processing. locals { enabled = var.enabled function_name = var.function_name != null ? var.function_name : "${var.namespace}-${var.lab}-${var.stage}-${var.name}" # Source-code resolution: # 1. If var.s3_bucket + var.s3_key are set, deploy from S3. # 2. Else if var.filename is set, deploy from that local zip. # 3. Else, zip the bundled ./src/ directory at plan time so the component # plans cleanly without requiring the caller to ship code. use_archive = var.filename == null && var.s3_bucket == null resolved_filename = local.use_archive ? data.archive_file.this[0].output_path : var.filename # source_code_hash resolution: auto-zip and local-zip paths can hash the # file directly; the S3 path can't (no local file), so it relies on the # caller passing var.source_code_hash to detect changes. resolved_source_code_hash = ( local.use_archive ? data.archive_file.this[0].output_base64sha256 : var.filename != null ? filebase64sha256(var.filename) : var.source_code_hash ) # If the caller didn't supply a role, we create a basic execution role # (CloudWatch Logs only). Lab 06 wires in the AI-services role from the # iam-role component via !terraform.output for full permissions. create_default_role = local.enabled && var.role_arn == null resolved_role_arn = var.role_arn != null ? var.role_arn : try(aws_iam_role.lambda_default[0].arn, null) } # Auto-zip the bundled handler when no external source is provided. data "archive_file" "this" { count = local.enabled && local.use_archive ? 1 : 0 type = "zip" source_dir = "${path.module}/src" output_path = "${path.module}/build/${local.function_name}.zip" } # Default basic-execution role for plan-clean usage without external wiring. resource "aws_iam_role" "lambda_default" { count = local.create_default_role ? 1 : 0 name = "${local.function_name}-exec" assume_role_policy = jsonencode({ Version = "2012-10-17" Statement = [{ Effect = "Allow" Principal = { Service = "lambda.amazonaws.com" } Action = "sts:AssumeRole" }] }) tags = merge(var.tags, { Name = "${local.function_name}-exec" Lab = var.lab }) } resource "aws_iam_role_policy_attachment" "lambda_default_basic" { count = local.create_default_role ? 1 : 0 role = aws_iam_role.lambda_default[0].name policy_arn = "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole" } # Lambda function resource "aws_lambda_function" "this" { count = local.enabled ? 1 : 0 function_name = local.function_name description = var.description role = local.resolved_role_arn handler = var.handler runtime = var.runtime timeout = var.timeout memory_size = var.memory_size filename = local.resolved_filename source_code_hash = local.resolved_source_code_hash s3_bucket = var.s3_bucket s3_key = var.s3_key environment { variables = merge( var.environment_variables, { LOG_LEVEL = var.log_level }, var.output_bucket != null ? { OUTPUT_BUCKET = var.output_bucket } : {}, ) } tags = merge(var.tags, { Name = local.function_name Lab = var.lab }) # The log group exists before the function and is deleted after it, so a # late invocation cannot create an unmanaged group with the same name # (which would make the next apply fail with ResourceAlreadyExistsException). depends_on = [ aws_iam_role_policy_attachment.lambda_default_basic, aws_cloudwatch_log_group.this, ] lifecycle { # Catch the common Lab-06 misconfiguration: turning on the S3 trigger # without wiring an IAM role that can actually read trigger objects. # The default execution role only has CloudWatch Logs permissions - # Lambda would be invoked but `s3:GetObject` would fail every call. precondition { condition = !(var.s3_trigger_enabled && var.role_arn == null) error_message = "s3_trigger_enabled = true requires role_arn to be supplied (the default execution role lacks s3:GetObject). Wire to the iam-role component output via !terraform.output role_arn." } } } # CloudWatch Log Group resource "aws_cloudwatch_log_group" "this" { count = local.enabled ? 1 : 0 name = "/aws/lambda/${local.function_name}" retention_in_days = var.log_retention_days tags = merge(var.tags, { Name = "/aws/lambda/${local.function_name}" Lab = var.lab }) } # S3 trigger permission resource "aws_lambda_permission" "s3" { count = local.enabled && var.s3_trigger_enabled ? 1 : 0 statement_id = "AllowS3Invoke" action = "lambda:InvokeFunction" function_name = aws_lambda_function.this[0].function_name principal = "s3.amazonaws.com" source_arn = var.s3_trigger_bucket_arn } # S3 bucket notification (if bucket ID is provided). # # IMPORTANT: AWS allows only ONE notification configuration per bucket. This # resource REPLACES any existing notifications. Within Lab 06 that's fine - # the s3-bucket component doesn't configure notifications, so this is the # sole writer. Be careful if you ever attach this Lambda to a bucket that # other Terraform stacks / console actions are managing notifications for. resource "aws_s3_bucket_notification" "this" { count = local.enabled && var.s3_trigger_enabled && var.s3_trigger_bucket_id != null ? 1 : 0 bucket = var.s3_trigger_bucket_id lambda_function { lambda_function_arn = aws_lambda_function.this[0].arn events = var.s3_trigger_events filter_prefix = var.s3_trigger_prefix filter_suffix = var.s3_trigger_suffix } depends_on = [aws_lambda_permission.s3] } # EventBridge rule (optional scheduled trigger) resource "aws_cloudwatch_event_rule" "schedule" { count = local.enabled && var.schedule_expression != null ? 1 : 0 name = "${local.function_name}-schedule" description = "Schedule for ${local.function_name}" schedule_expression = var.schedule_expression tags = merge(var.tags, { Name = "${local.function_name}-schedule" Lab = var.lab }) } resource "aws_cloudwatch_event_target" "schedule" { count = local.enabled && var.schedule_expression != null ? 1 : 0 rule = aws_cloudwatch_event_rule.schedule[0].name target_id = "lambda" arn = aws_lambda_function.this[0].arn # Ensure the invoke permission exists before EventBridge can fire the rule. # Without this, a rule that triggers before the permission attaches will # silently drop the invocation. depends_on = [aws_lambda_permission.eventbridge] } resource "aws_lambda_permission" "eventbridge" { count = local.enabled && var.schedule_expression != null ? 1 : 0 statement_id = "AllowEventBridgeInvoke" action = "lambda:InvokeFunction" function_name = aws_lambda_function.this[0].function_name principal = "events.amazonaws.com" source_arn = aws_cloudwatch_event_rule.schedule[0].arn }