-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.tf
95 lines (82 loc) · 2.65 KB
/
main.tf
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
83
84
85
86
87
88
89
90
91
92
93
94
95
variable "create_resources" {
type = bool
default = true
description = "if true, this config will create the desired resources in this file. Set to false for dry-sourcing the module"
}
# roles
resource "aws_iam_role" "lambda_execution" {
name = "iam_for_kunstkomputer_lambda"
count = var.create_resources ? 1 : 0
assume_role_policy = <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Action": "sts:AssumeRole",
"Principal": {
"Service": "lambda.amazonaws.com"
},
"Effect": "Allow",
"Sid": ""
}
]
}
EOF
}
# lambda auto-creates loggroup not managed by tf
data "aws_iam_policy_document" "lambda_execution_role_policy" {
statement {
actions = [
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents"
]
resources = [
"arn:aws:logs:*:*:*"
]
}
}
resource "aws_iam_role_policy" "lambda_execution_role" {
role = aws_iam_role.lambda_execution[count.index].id
policy = data.aws_iam_policy_document.lambda_execution_role_policy.json
count = var.create_resources ? 1 : 0
}
data "archive_file" "lambda_zip" {
type = "zip"
source_dir = "${path.module}/src"
output_path = "${path.module}/deployment_package.zip"
}
# function
resource "aws_lambda_function" "kunstkomputer_lambda" {
filename = "${path.module}/deployment_package.zip"
function_name = "python_hello_world"
role = aws_iam_role.lambda_execution[count.index].arn
handler = "main.lambda_handler"
layers = []
source_code_hash = data.archive_file.lambda_zip.output_base64sha256
runtime = "python3.9"
count = var.create_resources ? 1 : 0
}
# cron trigger
resource "aws_cloudwatch_event_rule" "cron_trigger" {
name = "cron_trigger_for_kunstkomputer_lambda"
description = "Fires every minute"
schedule_expression = "cron(* * * * ? *)"
count = var.create_resources ? 1 : 0
}
resource "aws_cloudwatch_event_target" "trigger_kunstkomputer_lambda" {
rule = aws_cloudwatch_event_rule.cron_trigger[count.index].name
arn = aws_lambda_function.kunstkomputer_lambda[count.index].arn
count = var.create_resources ? 1 : 0
}
resource "aws_lambda_permission" "trigger_execution_permission" {
statement_id = "AllowExecutionFromCloudWatch"
action = "lambda:InvokeFunction"
function_name = aws_lambda_function.kunstkomputer_lambda[count.index].function_name
principal = "events.amazonaws.com"
source_arn = aws_cloudwatch_event_rule.cron_trigger[count.index].arn
count = var.create_resources ? 1 : 0
}
output "deployed_region" {
value = data.aws_region.current.name
}