-
Notifications
You must be signed in to change notification settings - Fork 0
/
sqs-dynamodb.tf
115 lines (110 loc) · 2.72 KB
/
sqs-dynamodb.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
# Create Dynamodb table
resource "aws_dynamodb_table" "customer_table" {
name = "customer"
billing_mode = "PAY_PER_REQUEST"
hash_key = "customer_reference"
attribute {
name = "customer_reference"
type = "S"
}
}
# Lambda Function deploy from source
module "lambda_function_sqs-db" {
source = "terraform-aws-modules/lambda/aws"
function_name = "sqs-to-db"
description = "My awesome lambda function"
handler = "sqs-db.lambda_handler"
runtime = "python3.9"
publish = true
attach_policy = true
create_role = false
lambda_role = "${aws_iam_role.lambda_role.arn}"
source_path = "./lambda"
environment_variables = {
SQS_URL = "${aws_sqs_queue.csv_queue.url}"
}
allowed_triggers = {
AllowExecutionFromS3Bucket = {
service = "s3"
source_arn = module.s3_bucket.s3_bucket_arn
}
}
tags = {
Pattern = "terraform"
Module = "lambda_function"
Team = "DevOPS"
}
depends_on = [
aws_iam_role.lambda_role
]
}
# trigger lambda function when there is new message in sqs
resource "aws_lambda_event_source_mapping" "csv_to_json_mapping" {
event_source_arn = aws_sqs_queue.csv_queue.arn
function_name = module.lambda_function_sqs-db.lambda_function_name
batch_size = 10
}
# Attache policy to IAM
resource "aws_iam_role_policy_attachment" "lambda_sqs_policy" {
policy_arn = aws_iam_policy.lambda_policy_sqs.arn
role = aws_iam_role.lambda_role.name
}
# Create IAM role for Lambda function
resource "aws_iam_role" "lambda_role" {
name = "csv-to-dynamodb-lambda-role"
assume_role_policy = jsonencode({
Version = "2012-10-17"
Statement = [
{
Action = "sts:AssumeRole"
Effect = "Allow"
Principal = {
Service = "lambda.amazonaws.com"
}
}
]
})
}
# Create IAM policy for Lambda function
resource "aws_iam_policy" "lambda_policy_sqs" {
name = "json-to-dynamodb-lambda-policy"
policy = jsonencode({
Version: "2012-10-17",
Statement: [
{
Effect: "Allow",
Action: [
"dynamodb:PutItem"
],
Resource: aws_dynamodb_table.customer_table.arn
},
{
Effect: "Allow",
Action: [
"sqs:GetQueueUrl",
"sqs:ReceiveMessage",
"sqs:DeleteMessage",
"sqs:GetQueueAttributes"
],
Resource: "*"
},
{
Effect: "Allow",
Action: [
"lambda:InvokeFunction"
],
Resource: "*"
},
{
Effect: "Allow",
Action: [
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents"
],
Resource: "arn:aws:logs:*:*:*"
}
]
})
}
###