-
Notifications
You must be signed in to change notification settings - Fork 1
/
lambda.tf
96 lines (85 loc) · 2.51 KB
/
lambda.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
96
# Archiving code for lambda
data "archive_file" "lambda_function_zip" {
type = "zip"
source_dir = "${path.module}/functions/key-rotatation-lambda"
output_path = "${path.module}/key-rotatation-lambda.zip"
}
# Lambda function
resource "aws_lambda_function" "lambda_function" {
function_name = "key-rotatation-lambda"
role = aws_iam_role.lambda_exec.arn
handler = "main.handler"
runtime = "python3.11"
filename = "${path.module}/key-rotatation-lambda.zip"
depends_on = [data.archive_file.lambda_function_zip]
source_code_hash = data.archive_file.lambda_function_zip.output_base64sha256
environment {
variables = {
SET_EXPIRY = "90"
KEY_USER_NAME = "key_user_name"
}
}
}
# IAM role to be used by lambda function
resource "aws_iam_role" "lambda_exec" {
name = "lambda-execution-role"
assume_role_policy = jsonencode({
Version = "2012-10-17",
Statement = [
{
Action = "sts:AssumeRole",
Effect = "Allow",
Principal = {
Service = "lambda.amazonaws.com",
},
},
],
})
}
# IAM policy for lambda to send email via AWS SES
resource "aws_iam_policy" "lambda_ses" {
name = "send-email-policy"
description = "IAM policy for the Lambda function"
policy = jsonencode(
{
"Version" : "2012-10-17",
"Statement" : [
{
"Effect" : "Allow",
"Action" : [
"ses:SendEmail",
"ses:SendRawEmail",
"iam:ListAccessKeys"
],
"Resource" : "*"
},
]
}
)
}
# Policy attachment
resource "aws_iam_policy_attachment" "lambda_attach" {
name = "lambda-attach-ses"
policy_arn = aws_iam_policy.lambda_ses.arn
roles = [aws_iam_role.lambda_exec.name]
}
# Trigger for cloud function
# Event rule
resource "aws_cloudwatch_event_rule" "cron_lambdas" {
name = "cronjob"
description = "to triggr lambda daily 8 am"
schedule_expression = "cron(0 * * ? *)"
}
# Event target
resource "aws_cloudwatch_event_target" "cron_lambdas" {
rule = aws_cloudwatch_event_rule.cron_lambdas.name
arn = aws_lambda_function.lambda_function.arn
}
# Invoke lambda permission
resource "aws_lambda_permission" "cron_lambdas" {
statement_id = "key-rotation-lambda-allow"
action = "lambda:InvokeFunction"
principal = "events.amazonaws.com"
function_name = aws_lambda_function.lambda_function.arn
source_arn = aws_cloudwatch_event_rule.cron_lambdas.arn
}