Skip to content

Commit 3210a58

Browse files
committed
adding s3 trigger event
1 parent e60dd16 commit 3210a58

3 files changed

Lines changed: 71 additions & 2 deletions

File tree

infra/main.tf

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,3 +38,53 @@ resource "aws_lambda_function" "hello_lambda" {
3838
}
3939

4040
}
41+
42+
resource "aws_s3_bucket" "lambda_trigger_bucket" {
43+
bucket = var.s3_bucket_name
44+
}
45+
46+
resource "aws_s3_bucket_notification" "lambda_bucket_notification" {
47+
bucket = aws_s3_bucket.lambda_trigger_bucket.id
48+
49+
lambda_function {
50+
lambda_function_arn = aws_lambda_function.hello_lambda.arn
51+
events = ["s3:ObjectCreated:*"]
52+
filter_prefix = "uploads/"
53+
filter_suffix = ".txt"
54+
}
55+
}
56+
57+
resource "aws_lambda_permission" "allow_s3_bucket_notification" {
58+
statement_id = "AllowExecutionFromS3Bucket"
59+
action = "lambda:InvokeFunction"
60+
function_name = aws_lambda_function.hello_lambda.function_name
61+
principal = "s3.amazonaws.com"
62+
source_arn = aws_s3_bucket.lambda_trigger_bucket.arn
63+
}
64+
65+
resource "aws_iam_role_policy" "s3_access_policy" {
66+
name = "lambda_s3_access_policy"
67+
role = aws_iam_role.lambda_exec_role.id
68+
69+
policy = jsonencode({
70+
Version = "2012-10-17"
71+
Statement = [
72+
{
73+
Action = [
74+
"s3:GetObject",
75+
"s3:PutObject",
76+
"s3:DeleteObject"
77+
]
78+
Effect = "Allow"
79+
Resource = "${aws_s3_bucket.lambda_trigger_bucket.arn}/*"
80+
},
81+
{
82+
Action = [
83+
"s3:ListBucket"
84+
]
85+
Effect = "Allow"
86+
Resource = aws_s3_bucket.lambda_trigger_bucket.arn
87+
}
88+
]
89+
})
90+
}

infra/variables.tf

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,3 +3,9 @@ variable "aws_region" {
33
type = string
44
default = "us-east-2"
55
}
6+
7+
variable "s3_bucket_name" {
8+
description = "Name of the S3 bucket to trigger the Lambda function"
9+
type = string
10+
default = "hello-lambda-trigger-bucket-unique-name" # IMPORTANT: Change this to a globally unique name
11+
}

lambda_function.py

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,19 @@
1+
import json
12

23
def lambda_handler(event, context):
4+
print("Received S3 event:", json.dumps(event))
5+
6+
for record in event['Records']:
7+
bucket_name = record['s3']['bucket']['name']
8+
object_key = record['s3']['object']['key']
9+
event_name = record['eventName']
10+
11+
print(f"Event Name: {event_name}")
12+
print(f"Bucket Name: {bucket_name}")
13+
print(f"Object Key: {object_key}")
14+
15+
# You can add more processing here, e.g., download the object, analyze it, etc.
16+
317
return {
4-
'statusCode': 200,
5-
'body': 'Hello from Lambda!'
18+
'body': json.dumps('Successfully processed S3 event!')
619
}

0 commit comments

Comments
 (0)