-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.tf
117 lines (104 loc) · 2.84 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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
}
data "aws_service" "secretsmanager" {
service_id = "secretsmanager"
}
locals {
secretsmanager_endpoint = var.secrets_manager_vpc_endpoint != "" ? var.secrets_manager_vpc_endpoint : data.aws_service.secretsmanager.dns_name
}
resource "aws_iam_policy" "secretsmanager-read" {
name = "SecretManagerReadAccess"
description = "Access to get Secrets from Secrets Manager"
policy = <<EOF
{
"Version" : "2012-10-17",
"Statement" : [
{
"Action" : [
"secretsmanager:GetSecretValue",
"secretsmanager:ListSecrets"
],
"Effect" : "Allow",
"Resource" : "${var.secrets_path}"
}
]
}
EOF
}
resource "aws_iam_role" "lambda_role" {
name = "secretsmanager-to-swarm"
assume_role_policy = <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Action": "sts:AssumeRole",
"Principal": {
"Service": "lambda.amazonaws.com"
},
"Effect": "Allow",
"Sid": ""
}
]
}
EOF
managed_policy_arns = [
aws_iam_policy.secretsmanager-read.arn,
"arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole",
"arn:aws:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole"
]
}
resource "aws_lambda_function" "lambda_function" {
filename = "${path.module}/lambda/lambda.zip"
function_name = "secretsmanager-to-swarm"
handler = "app.handler"
role = aws_iam_role.lambda_role.arn
runtime = "python3.12"
source_code_hash = filebase64sha256("${path.module}/lambda/lambda.zip")
environment {
variables = {
docker_endpoint = var.docker_endpoint
secretsmanager_endpoint = local.secretsmanager_endpoint
}
}
vpc_config {
subnet_ids = var.subnet_ids
security_group_ids = [var.security_group_id]
}
}
resource "aws_cloudwatch_event_rule" "secretsmanager" {
name = "secretsmanager"
description = "Trigger when a secret has been created"
event_pattern = <<EOF
{
"source": ["aws.secretsmanager"],
"detail-type": ["AWS API Call via CloudTrail"],
"detail": {
"eventSource": ["secretsmanager.amazonaws.com"],
"eventName": ["CreateSecret", "PutSecretValue"],
"requestParameters": {
"tags": {
"docker": ["true"]
}
}
}
}
EOF
}
resource "aws_cloudwatch_event_target" "lambda" {
rule = aws_cloudwatch_event_rule.secretsmanager.name
arn = aws_lambda_function.lambda_function.arn
}
resource "aws_lambda_permission" "allow-event-bridge" {
action = "lambda:InvokeFunction"
function_name = aws_lambda_function.lambda_function.function_name
principal = "events.amazonaws.com"
source_arn = aws_cloudwatch_event_rule.secretsmanager.arn
statement_id = "AllowExecutionFromEventBridge"
}