-
Notifications
You must be signed in to change notification settings - Fork 1
/
lambda.tf
88 lines (79 loc) · 2.28 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
# zip python code files
data "archive_file" "lambda_stop_package" {
type = "zip"
source_file = "stop_code.py"
output_path = "stop_code.zip"
}
data "archive_file" "lambda_start_package" {
type = "zip"
source_file = "start_code.py"
output_path = "start_code.zip"
}
# Create lambda function's role
resource "aws_iam_role" "lambda_start_stop_EC2_role" {
name = "lambda_start_stop_EC2_role"
assume_role_policy = jsonencode({
Version = "2012-10-17",
Statement = [
{
Action = "sts:AssumeRole",
Effect = "Allow",
Principal = {
Service = "lambda.amazonaws.com"
}
}
]
})
}
# Create policy to give lambda function permissive access to EC2
resource "aws_iam_policy" "lambda_start_stop_EC2" {
name = "lambda_start_stop_EC2"
description = "allows lambda to stop & start instances"
policy = jsonencode({
Version : "2012-10-17",
Statement : [
{
Effect : "Allow",
Action : [
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents"
],
Resource : "arn:aws:logs:*:*:*"
},
{
Effect : "Allow",
Action : [
"ec2:Start*",
"ec2:Stop*"
],
Resource : "*"
},
]
})
}
# Attach policy to lambda's role
resource "aws_iam_role_policy_attachment" "lambda_policy_attachment" {
policy_arn = aws_iam_policy.lambda_start_stop_EC2.arn
role = aws_iam_role.lambda_start_stop_EC2_role.name
}
# Create stop lambda function
resource "aws_lambda_function" "stop_EC2" {
function_name = "stop_EC2"
filename = "stop_code.zip"
role = aws_iam_role.lambda_start_stop_EC2_role.arn
handler = "stop_code.lambda_handler"
source_code_hash = data.archive_file.lambda_stop_package.output_base64sha256
runtime = "python3.9"
timeout = 10
}
# Create start lambda function
resource "aws_lambda_function" "start_EC2" {
function_name = "start_EC2"
filename = "start_code.zip"
role = aws_iam_role.lambda_start_stop_EC2_role.arn
handler = "start_code.lambda_handler"
source_code_hash = data.archive_file.lambda_start_package.output_base64sha256
runtime = "python3.9"
timeout = 10
}