-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlambda.tf
More file actions
86 lines (74 loc) · 2.18 KB
/
Copy pathlambda.tf
File metadata and controls
86 lines (74 loc) · 2.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
resource "aws_iam_role" "lambda_role" {
name = "lambda-role-${var.environment}"
assume_role_policy = jsonencode({
Version = "2012-10-17"
Statement = [
{
Action = "sts:AssumeRole"
Effect = "Allow"
Principal = {
Service = "lambda.amazonaws.com"
}
}
]
})
}
resource "aws_iam_policy" "lambda_s3_policy" {
name = "lambda-s3-policy-${var.environment}"
description = "allows lambda to read and write to s3"
policy = jsonencode({
Version = "2012-10-17"
Statement = [
{
Effect = "Allow"
Action = [
"s3:GetObject",
"s3:PutObject",
"s3:DeleteObject"
]
Resource = "arn:aws:s3:::${aws_s3_bucket.api_data.bucket}/*"
}
]
})
}
resource "aws_iam_role_policy_attachment" "lambda_s3_attachment" {
role = aws_iam_role.lambda_role.name
policy_arn = aws_iam_policy.lambda_s3_policy.arn
}
data "archive_file" "lambda_zip" {
type = "zip"
source_file = "lambda_function.py"
output_path = "lambda_function.zip"
}
resource "aws_lambda_function" "fetch_api_lambda" {
function_name = "fetch-api-lambda-${var.environment}"
role = aws_iam_role.lambda_role.arn
handler = "lambda_function.lambda_handler"
runtime = "python3.10"
filename = data.archive_file.lambda_zip.output_path
source_code_hash = filebase64sha256(data.archive_file.lambda_zip.output_path)
timeout = 30
memory_size = 128
environment {
variables = {
S3_BUCKET = aws_s3_bucket.api_data.bucket
}
}
}
resource "aws_cloudwatch_event_rule" "fetch_api_rule" {
name = "fetch-api-rule-${var.environment}"
description = "fetch api rule"
schedule_expression = "rate(10 minutes)"
}
resource "aws_cloudwatch_event_target" "fetch_api_target" {
rule = aws_cloudwatch_event_rule.fetch_api_rule.name
arn = aws_lambda_function.fetch_api_lambda.arn
target_id = "lambda"
}
resource "aws_lambda_permission" "fetch_api_permission" {
statement_id = "AllowExecutionFromCloudWatch"
action = "lambda:InvokeFunction"
function_name = aws_lambda_function.fetch_api_lambda.function_name
principal = "events.amazonaws.com"
source_arn = aws_cloudwatch_event_rule.fetch_api_rule.arn
}