CodexBloom - Programming Q&A Platform

Terraform AWS Lambda Function Not Triggering due to IAM Role Permissions Issue

👀 Views: 433 đŸ’Ŧ Answers: 1 📅 Created: 2025-07-17
terraform aws lambda iam HCL

I'm having trouble with my AWS Lambda function not triggering as expected when an S3 event occurs. I've set up the S3 bucket notification and linked it to the Lambda function, but it seems the function is not executing when the event happens. I've checked the CloudWatch logs, and there's no indication that the Lambda is even being invoked. Here's a snippet of my Terraform configuration for the Lambda and S3 bucket: ```hcl resource "aws_s3_bucket" "my_bucket" { bucket = "my-unique-bucket-name" } resource "aws_lambda_function" "my_lambda" { function_name = "MyLambdaFunction" runtime = "nodejs14.x" handler = "index.handler" role = aws_iam_role.my_lambda_role.arn source_code_hash = filebase64sha256("./function.zip") } resource "aws_lambda_permission" "allow_s3" { statement_id = "AllowExecutionFromS3" action = "lambda:InvokeFunction" function_name = aws_lambda_function.my_lambda.function_name principal = "s3.amazonaws.com" source_arn = aws_s3_bucket.my_bucket.arn } resource "aws_s3_bucket_notification" "bucket_notification" { bucket = aws_s3_bucket.my_bucket.id lambda_function { lambda_function_arn = aws_lambda_function.my_lambda.arn events = ["s3:ObjectCreated:*"] } } ``` I suspect it could be a permissions issue with the IAM role assigned to the Lambda function. The IAM role looks like this: ```hcl resource "aws_iam_role" "my_lambda_role" { name = "my_lambda_role" assume_role_policy = jsonencode({ Version = "2012-10-17" Statement = [{ Action = "sts:AssumeRole" Principal = { Service = "lambda.amazonaws.com" } Effect = "Allow" Sid = "" }] }) } resource "aws_iam_policy_attachment" "lambda_policy_attachment" { name = "lambda_policy_attachment" roles = [aws_iam_role.my_lambda_role.name] policies = [aws_iam_policy.lambda_policy.id] } resource "aws_iam_policy" "lambda_policy" { name = "lambda_policy" description = "Policy for Lambda to access S3" policy = jsonencode({ Version = "2012-10-17" Statement = [{ Effect = "Allow" Action = ["s3:GetObject"] Resource = ["${aws_s3_bucket.my_bucket.arn}/*"] }] ] }) } ``` I've validated that the S3 bucket is correctly configured to send event notifications, and the Lambda function is deployed successfully without any errors. However, it seems like the IAM policies might not be correctly allowing the invocation from S3. I tried adding a broader permission by allowing the `s3:*` actions, but that did not resolve the issue. I'm using Terraform v1.3.5 and the AWS provider v4.0.0. Is there something specific I might be missing that prevents the Lambda function from being triggered by the S3 event? Any help would be greatly appreciated!