-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathmonitoring.tf
More file actions
426 lines (371 loc) · 14.3 KB
/
monitoring.tf
File metadata and controls
426 lines (371 loc) · 14.3 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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
# ----------------------------------------------------------
# CloudWatch Monitoring and Alerting
# ----------------------------------------------------------
# Local configuration for SNS resources
locals {
sns_topics = var.enable_monitoring && var.create_sns_topic ? {
ecr_monitoring = {
name = var.sns_topic_name != null ? var.sns_topic_name : "${var.name}-ecr-monitoring"
display_name = "ECR Monitoring Alerts for ${var.name}"
tag_name = var.sns_topic_name != null ? var.sns_topic_name : "${var.name}-ecr-monitoring"
}
} : {}
# Create subscription mappings for for_each
sns_subscriptions = var.enable_monitoring && var.create_sns_topic ? {
for idx, email in var.sns_topic_subscribers : "subscription-${idx}" => {
topic_key = "ecr_monitoring"
protocol = "email"
endpoint = email
}
} : {}
# Updated SNS topic ARN local
sns_topic_arn = var.enable_monitoring ? (
var.create_sns_topic ? try(aws_sns_topic.ecr_monitoring["ecr_monitoring"].arn, null) :
(var.sns_topic_name != null ? "arn:aws:sns:${data.aws_region.current.id}:${data.aws_caller_identity.current.account_id}:${var.sns_topic_name}" : null)
) : null
}
# SNS Topic for CloudWatch alarm notifications
resource "aws_sns_topic" "ecr_monitoring" {
for_each = local.sns_topics
name = each.value.name
display_name = each.value.display_name
tags = merge(
local.final_tags,
{
Name = each.value.tag_name
}
)
}
# SNS Topic subscriptions
resource "aws_sns_topic_subscription" "ecr_monitoring_email" {
for_each = local.sns_subscriptions
topic_arn = aws_sns_topic.ecr_monitoring[each.value.topic_key].arn
protocol = each.value.protocol
endpoint = each.value.endpoint
}
# Local configuration for CloudWatch alarms
locals {
cloudwatch_alarms = var.enable_monitoring ? {
storage_usage = {
alarm_name = "${var.name}-ecr-storage-usage"
comparison_operator = "GreaterThanThreshold"
evaluation_periods = "2"
metric_name = "RepositorySizeInBytes"
namespace = "AWS/ECR"
period = "300"
statistic = "Average"
threshold = var.monitoring_threshold_storage * 1024 * 1024 * 1024 # Convert GB to bytes
alarm_description = "This metric monitors ECR repository storage usage for ${var.name}"
tag_name = "${var.name}-ecr-storage-usage-alarm"
enabled = true
dimensions = {
RepositoryName = local.repository_name
}
}
api_call_volume = {
alarm_name = "${var.name}-ecr-api-calls"
comparison_operator = "GreaterThanThreshold"
evaluation_periods = "2"
metric_name = "ApiCallCount"
namespace = "AWS/ECR"
period = "60"
statistic = "Sum"
threshold = var.monitoring_threshold_api_calls
alarm_description = "This metric monitors ECR API call volume for ${var.name}"
tag_name = "${var.name}-ecr-api-calls-alarm"
enabled = true
dimensions = {
RepositoryName = local.repository_name
}
}
image_push_count = {
alarm_name = "${var.name}-ecr-image-push"
comparison_operator = "GreaterThanThreshold"
evaluation_periods = "2"
metric_name = "ImagePushCount"
namespace = "AWS/ECR"
period = "300"
statistic = "Sum"
threshold = var.monitoring_threshold_image_push
alarm_description = "This metric monitors ECR image push frequency for ${var.name}"
tag_name = "${var.name}-ecr-image-push-alarm"
enabled = true
dimensions = {
RepositoryName = local.repository_name
}
}
image_pull_count = {
alarm_name = "${var.name}-ecr-image-pull"
comparison_operator = "GreaterThanThreshold"
evaluation_periods = "2"
metric_name = "ImagePullCount"
namespace = "AWS/ECR"
period = "300"
statistic = "Sum"
threshold = var.monitoring_threshold_image_pull
alarm_description = "This metric monitors ECR image pull frequency for ${var.name}"
tag_name = "${var.name}-ecr-image-pull-alarm"
enabled = true
dimensions = {
RepositoryName = local.repository_name
}
}
security_findings = {
alarm_name = "${var.name}-ecr-security-findings"
comparison_operator = "GreaterThanThreshold"
evaluation_periods = "1"
metric_name = "HighSeverityVulnerabilityCount"
namespace = "AWS/ECR"
period = "300"
statistic = "Maximum"
threshold = var.monitoring_threshold_security_findings
alarm_description = "This metric monitors ECR security findings for ${var.name}"
tag_name = "${var.name}-ecr-security-findings-alarm"
enabled = var.enable_registry_scanning
dimensions = {
RepositoryName = local.repository_name
}
}
} : {}
}
# CloudWatch Alarms using for_each pattern
resource "aws_cloudwatch_metric_alarm" "monitoring" {
for_each = { for k, v in local.cloudwatch_alarms : k => v if v.enabled }
alarm_name = each.value.alarm_name
comparison_operator = each.value.comparison_operator
evaluation_periods = each.value.evaluation_periods
metric_name = each.value.metric_name
namespace = each.value.namespace
period = each.value.period
statistic = each.value.statistic
threshold = each.value.threshold
alarm_description = each.value.alarm_description
alarm_actions = local.sns_topic_arn != null ? [local.sns_topic_arn] : []
ok_actions = local.sns_topic_arn != null ? [local.sns_topic_arn] : []
dimensions = each.value.dimensions
tags = merge(
local.final_tags,
{
Name = each.value.tag_name
}
)
depends_on = [
aws_ecr_repository.repo,
aws_ecr_repository.repo_protected
]
}
# ----------------------------------------------------------
# Pull Request Rules Event Handling
# ----------------------------------------------------------
# Local values for pull request rules event handling
locals {
# Generate CloudWatch Event Rules for pull request rules
pull_request_rule_events = local.pull_request_rules_enabled ? [
for rule in local.enabled_pull_request_rules : {
name = rule.name
type = rule.type
event_pattern = jsonencode({
source = ["aws.ecr"]
detail-type = ["ECR Image Action"]
detail = {
action-type = ["PUSH"]
repository-name = [local.repository_name]
}
})
notification_topic_arn = try(rule.actions.notification_topic_arn, null)
webhook_url = try(rule.actions.webhook_url, null)
} if try(rule.actions.notification_topic_arn, null) != null || try(rule.actions.webhook_url, null) != null
] : []
# Filtered events for SNS notifications with original indices
pull_request_rule_events_sns = local.pull_request_rules_enabled ? [
for i, event in local.pull_request_rule_events : {
event = event
original_index = i
}
if event.notification_topic_arn != null
] : []
# Filtered events for webhook notifications with original indices
pull_request_rule_events_webhook = local.pull_request_rules_enabled ? [
for i, event in local.pull_request_rule_events : {
event = event
original_index = i
}
if event.webhook_url != null
] : []
}
# SNS Topic for pull request rule notifications (if not provided)
resource "aws_sns_topic" "pull_request_rules" {
count = local.pull_request_rules_enabled && length([
for rule in local.enabled_pull_request_rules : rule
if try(rule.actions.notification_topic_arn, null) == null && try(rule.actions.webhook_url, null) == null
]) > 0 ? 1 : 0
name = "${var.name}-ecr-pull-request-rules"
tags = merge(
local.final_tags,
{
Name = "${var.name}-ecr-pull-request-rules"
Type = "PullRequestRules"
}
)
}
# CloudWatch Event Rule for pull request rules
resource "aws_cloudwatch_event_rule" "pull_request_rules" {
for_each = { for i, event in local.pull_request_rule_events : "${i}-${event.name}" => event }
name = "${var.name}-ecr-pr-rule-${each.value.name}"
description = "Pull request rule event for ${each.value.name}"
event_pattern = each.value.event_pattern
tags = merge(
local.final_tags,
{
Name = "${var.name}-ecr-pr-rule-${each.value.name}"
Type = "PullRequestRule"
RuleType = each.value.type
}
)
}
# CloudWatch Event Target for SNS notifications
resource "aws_cloudwatch_event_target" "pull_request_rules_sns" {
for_each = { for i, item in local.pull_request_rule_events_sns : "sns-${i}" => item }
rule = aws_cloudwatch_event_rule.pull_request_rules["${each.value.original_index}-${each.value.event.name}"].name
target_id = "SendToSNS"
arn = each.value.event.notification_topic_arn
input_transformer {
input_paths = {
repository = "$.detail.repository-name"
tag = "$.detail.image-tag"
action = "$.detail.action-type"
time = "$.time"
}
input_template = jsonencode({
repository = "<repository>"
tag = "<tag>"
action = "<action>"
time = "<time>"
message = "ECR pull request rule triggered for repository <repository>, tag <tag>"
})
}
}
# CloudWatch Event Target for webhook notifications
resource "aws_cloudwatch_event_target" "pull_request_rules_webhook" {
for_each = { for i, item in local.pull_request_rule_events_webhook : "webhook-${i}" => item }
rule = aws_cloudwatch_event_rule.pull_request_rules["${each.value.original_index}-${each.value.event.name}"].name
target_id = "SendToWebhook"
arn = aws_lambda_function.pull_request_rules_webhook[each.key].arn
input_transformer {
input_paths = {
repository = "$.detail.repository-name"
tag = "$.detail.image-tag"
action = "$.detail.action-type"
time = "$.time"
}
input_template = jsonencode({
repository = "<repository>"
tag = "<tag>"
action = "<action>"
time = "<time>"
webhook_url = each.value.event.webhook_url
})
}
}
# Lambda function for webhook notifications
resource "aws_lambda_function" "pull_request_rules_webhook" {
for_each = { for i, item in local.pull_request_rule_events_webhook : "webhook-${i}" => item }
filename = data.archive_file.pull_request_rules_webhook[each.key].output_path
function_name = "${var.name}-ecr-pr-webhook-${each.value.event.name}"
role = aws_iam_role.pull_request_rules_webhook[each.key].arn
handler = "index.handler"
runtime = "python3.12"
timeout = 30
environment {
variables = {
WEBHOOK_URL = each.value.event.webhook_url
}
}
tags = merge(
local.final_tags,
{
Name = "${var.name}-ecr-pr-webhook-${each.value.event.name}"
Type = "PullRequestRuleWebhook"
}
)
}
# Lambda function code for webhook notifications
data "archive_file" "pull_request_rules_webhook" {
for_each = { for i, item in local.pull_request_rule_events_webhook : "webhook-${i}" => item }
type = "zip"
output_path = "/tmp/pull_request_rules_webhook_${each.value.event.name}.zip"
source {
content = <<-EOF
import json
import urllib3
import os
def handler(event, context):
webhook_url = os.environ['WEBHOOK_URL']
# Extract event details
detail = event.get('detail', {})
repository = detail.get('repository-name', '')
tag = detail.get('image-tag', '')
action = detail.get('action-type', '')
# Create webhook payload
payload = {
'repository': repository,
'tag': tag,
'action': action,
'time': event.get('time', ''),
'message': f'ECR pull request rule triggered for repository {repository}, tag {tag}'
}
# Send webhook
http = urllib3.PoolManager()
response = http.request(
'POST',
webhook_url,
body=json.dumps(payload),
headers={'Content-Type': 'application/json'}
)
return {
'statusCode': 200,
'body': json.dumps('Webhook sent successfully')
}
EOF
filename = "index.py"
}
}
# IAM role for Lambda webhook function
resource "aws_iam_role" "pull_request_rules_webhook" {
for_each = { for i, item in local.pull_request_rule_events_webhook : "webhook-${i}" => item }
name = "${var.name}-ecr-pr-webhook-role-${each.value.event.name}"
assume_role_policy = jsonencode({
Version = "2012-10-17"
Statement = [
{
Action = "sts:AssumeRole"
Effect = "Allow"
Principal = {
Service = "lambda.amazonaws.com"
}
}
]
})
tags = merge(
local.final_tags,
{
Name = "${var.name}-ecr-pr-webhook-role-${each.value.event.name}"
Type = "PullRequestRuleWebhookRole"
}
)
}
# IAM policy attachment for Lambda webhook function
resource "aws_iam_role_policy_attachment" "pull_request_rules_webhook" {
for_each = { for i, item in local.pull_request_rule_events_webhook : "webhook-${i}" => item }
role = aws_iam_role.pull_request_rules_webhook[each.key].name
policy_arn = "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"
}
# Lambda permission for CloudWatch Events
resource "aws_lambda_permission" "pull_request_rules_webhook" {
for_each = { for i, item in local.pull_request_rule_events_webhook : "webhook-${i}" => item }
statement_id = "AllowExecutionFromCloudWatch"
action = "lambda:InvokeFunction"
function_name = aws_lambda_function.pull_request_rules_webhook[each.key].function_name
principal = "events.amazonaws.com"
source_arn = aws_cloudwatch_event_rule.pull_request_rules["${each.value.original_index}-${each.value.event.name}"].arn
}