-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.tf
More file actions
100 lines (88 loc) · 2.46 KB
/
main.tf
File metadata and controls
100 lines (88 loc) · 2.46 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
}
provider "aws" {
region = "us-east-1" # Replace with your preferred region
}
# Lambda Layer
data "archive_file" "lambda_layer_zip" {
type = "zip"
source_dir = "${path.module}/build/my-lambda-layer" # Path to your Python dependencies directory
output_path = "${path.module}/build/lambda_layer.zip"
}
# Layer bucket
resource "aws_s3_bucket" "lambda_layer_bucket" {
bucket = "my-lambda-layer-bucket"
}
# Layer ZIP upload
resource "aws_s3_object" "lambda_layer" {
bucket = aws_s3_bucket.lambda_layer_bucket.id
key = "lambda_layer.zip"
source = data.archive_file.lambda_layer_zip.output_path
depends_on = [data.archive_file.lambda_layer_zip] # Triggered only if the zip file is created
}
# Lambda Layer from S3
resource "aws_lambda_layer_version" "dependencies" {
s3_bucket = aws_s3_bucket.lambda_layer_bucket.id
s3_key = aws_s3_object.lambda_layer.key
layer_name = "my-lambda-layer"
compatible_runtimes = ["python3.12"]
depends_on = [aws_s3_object.lambda_layer] # Triggered only if the zip file is uploaded to the bucket
}
# Lambda Function
data "archive_file" "lambda_function" {
type = "zip"
source_file = "${path.module}/src/lambda_function.py"
output_path = "${path.module}/build/lambda_function.zip"
}
resource "aws_lambda_function" "my_lambda" {
filename = data.archive_file.lambda_function.output_path
function_name = "my-lambda-function"
role = aws_iam_role.lambda_role.arn # See IAM Role below
handler = "lambda_function.handler"
runtime = "python3.12"
layers = [aws_lambda_layer_version.dependencies.arn]
}
# IAM Role for Lambda
resource "aws_iam_role" "lambda_role" {
name = "lambda_basic_execution"
assume_role_policy = <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Action": "sts:AssumeRole",
"Principal": {
"Service": "lambda.amazonaws.com"
},
"Effect": "Allow"
}
]
}
EOF
}
resource "aws_iam_role_policy" "lambda_logs_policy" {
name = "lambda_logs_policy"
role = aws_iam_role.lambda_role.id
policy = <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Action": [
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents"
],
"Resource": "arn:aws:logs:*:*:*",
"Effect": "Allow"
}
]
}
EOF
}