-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.tf
527 lines (484 loc) · 16.6 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
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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
terraform {
required_providers {
google = {
source = "hashicorp/google"
}
}
}
provider "google" {
project = var.project_id
region = var.region
}
#IAM
resource "google_project_service" "iam_api" {
service = "iam.googleapis.com"
disable_on_destroy = false
}
#Cloud Run
resource "google_project_service" "run_api" {
service = "run.googleapis.com"
disable_on_destroy = false
}
#Cloud Scheduler
resource "google_project_service" "cloud_scheduler" {
service = "cloudscheduler.googleapis.com"
disable_on_destroy = false
}
resource "google_project_service" "cloud_build" {
service = "cloudbuild.googleapis.com"
disable_on_destroy = false
}
resource "google_project_service" "cloud_functions" {
service = "cloudfunctions.googleapis.com"
disable_on_destroy = false
}
#Alerts
resource "google_project_service" "monitoring_api" {
service = "monitoring.googleapis.com"
disable_on_destroy = false
}
resource "google_service_account" "sgtm_service_account" {
account_id = "server-side-gtm"
display_name = "Serverside Google Tagmanager"
depends_on = [ google_project_service.iam_api ]
}
resource "google_project_iam_member" "sgtm_add_roles" {
for_each = toset([
"roles/run.invoker",
"roles/cloudfunctions.invoker",
"roles/cloudfunctions.serviceAgent"
])
project = var.project_id
role = each.value
member = "serviceAccount:${google_service_account.sgtm_service_account.email}"
depends_on = [ google_service_account.sgtm_service_account ]
}
resource "google_cloud_run_v2_service" "gtm_preview" {
name = var.service_name_preview
location = var.region
ingress = "INGRESS_TRAFFIC_ALL"
labels = {
stack = "sgtm",
provider = "mohrstade"
}
template {
annotations = {
"run.googleapis.com/startup-cpu-boost" = var.cpu_boost
}
service_account = google_service_account.sgtm_service_account.email
scaling {
min_instance_count = 0
max_instance_count = 1
}
containers {
image = "gcr.io/cloud-tagging-10302018/gtm-cloud-image:stable"
env {
name = "CONTAINER_CONFIG"
value = var.container_config
}
env {
name = "GOOGLE_CLOUD_PROJECT"
value = var.project_id
}
env {
name = "RUN_AS_PREVIEW_SERVER"
value = true
}
startup_probe {
http_get {
path = "/healthy"
}
initial_delay_seconds = 0
period_seconds = 10
failure_threshold = 3
timeout_seconds = 4
}
liveness_probe {
http_get {
path = "/healthy"
}
initial_delay_seconds = 240
period_seconds = 10
failure_threshold = 10
timeout_seconds = 4
}
}
}
depends_on = [ google_project_iam_member.sgtm_add_roles, google_project_service.run_api ]
}
resource "google_cloud_run_v2_service" "gtm_production" {
name = var.service_name_production
location = var.region
ingress = "INGRESS_TRAFFIC_ALL"
labels = {
stack = "sgtm",
provider = "mohrstade"
}
template {
annotations = {
"run.googleapis.com/startup-cpu-boost" = var.cpu_boost
}
service_account = google_service_account.sgtm_service_account.email
scaling {
min_instance_count = var.min_instance_count
max_instance_count = var.max_instance_count
}
containers {
image = "gcr.io/cloud-tagging-10302018/gtm-cloud-image:stable"
env {
name = "CONTAINER_CONFIG"
value = var.container_config
}
env {
name = "GOOGLE_CLOUD_PROJECT"
value = var.project_id
}
env {
name = "PREVIEW_SERVER_URL"
value = google_cloud_run_v2_service.gtm_preview.uri
}
startup_probe {
http_get {
path = "/healthy"
}
initial_delay_seconds = 0
period_seconds = 10
failure_threshold = 3
timeout_seconds = 4
}
liveness_probe {
http_get {
path = "/healthy"
}
initial_delay_seconds = 240
period_seconds = 10
failure_threshold = 10
timeout_seconds = 4
}
}
}
depends_on = [ google_cloud_run_v2_service.gtm_preview ]
}
resource "google_logging_project_exclusion" "cloud-run-log-exclusion" {
name = "cloud-run-log-exclusion"
description = "Exclude Cloud Run logs which are not severe."
filter = var.cloud_run_exclusion_filter
depends_on = [ google_cloud_run_v2_service.gtm_production ]
}
resource "google_cloud_run_service_iam_member" "prod_run_all_users" {
service = google_cloud_run_v2_service.gtm_production.name
location = google_cloud_run_v2_service.gtm_production.location
role = "roles/run.invoker"
member = "allUsers"
depends_on = [ google_cloud_run_v2_service.gtm_production ]
}
resource "google_cloud_run_service_iam_member" "debug_run_all_users" {
service = google_cloud_run_v2_service.gtm_preview.name
location = google_cloud_run_v2_service.gtm_preview.location
role = "roles/run.invoker"
member = "allUsers"
depends_on = [ google_cloud_run_v2_service.gtm_preview ]
}
resource "google_monitoring_notification_channel" "sgtm_notification_channels" {
count = length(var.notification_users)
display_name = var.notification_users[count.index].name
type = "email"
labels = {
email_address = var.notification_users[count.index].email
}
force_delete = false
depends_on = [ google_project_service.monitoring_api ]
}
resource "google_monitoring_uptime_check_config" "sgtm_uptime_check" {
display_name = "sgtm_uptime_check"
timeout = "10s"
period = "60s"
http_check {
path = "/healthy"
port = 443
use_ssl = true
}
monitored_resource {
type = "cloud_run_revision"
labels = {
project_id = var.project_id
service_name = google_cloud_run_v2_service.gtm_production.name
location = var.region
}
}
depends_on = [ google_cloud_run_v2_service.gtm_production ]
}
resource "google_monitoring_alert_policy" "sgtm_alert_policy" {
display_name = "SGTM Alert Policy"
combiner = "OR"
documentation {
content = <<EOT
Uptime Alert - Serverside Google Tag Manager
There was an error for the Cloud Run services running the serverside Google Tag Manager backend in project: "${var.project_id}".
Check the Uptime Checks in Monitoring on GCP for more information.
EOT
mime_type = "text/markdown"
}
conditions {
display_name = "Failure of uptime check : ${google_monitoring_uptime_check_config.sgtm_uptime_check.uptime_check_id}"
condition_threshold {
filter = <<EOT
metric.type="monitoring.googleapis.com/uptime_check/check_passed" AND metric.label.check_id="${google_monitoring_uptime_check_config.sgtm_uptime_check.uptime_check_id}" AND resource.type="cloud_run_revision"
EOT
duration = "60s"
comparison = "COMPARISON_GT"
threshold_value = "1"
trigger {
count = "1"
}
aggregations {
alignment_period = "1200s"
cross_series_reducer = "REDUCE_COUNT_FALSE"
group_by_fields = [
"resource.label.project_id",
"resource.label.service_name",
"resource.label.revision_name",
"resource.label.location",
"resource.label.configuration_name"
]
per_series_aligner = "ALIGN_NEXT_OLDER"
}
}
}
notification_channels = [ for channel in google_monitoring_notification_channel.sgtm_notification_channels : channel.id ]
depends_on = [ google_monitoring_notification_channel.sgtm_notification_channels, google_monitoring_uptime_check_config.sgtm_uptime_check ]
}
resource "google_monitoring_alert_policy" "sgtm_update_alert_policy" {
display_name = "SGTM Update Notice"
combiner = "OR"
documentation {
content = <<EOT
SGTM Update Notice
The Cloud Run SGTM in "${var.project_id}" was updated to the latest version.
Check Cloud Function logs for details.
EOT
mime_type = "text/markdown"
}
conditions {
display_name = "SGTM"
condition_matched_log {
filter = var.cloud_function_update_filter
}
}
alert_strategy {
notification_rate_limit {
period = "300s"
}
}
notification_channels = [ for channel in google_monitoring_notification_channel.sgtm_notification_channels : channel.id ]
depends_on = [ google_monitoring_notification_channel.sgtm_notification_channels ]
}
resource "google_monitoring_alert_policy" "sgtm_cpu_utilization_alert_policy" {
display_name = "SGTM High CPU Utilization Alert"
combiner = "OR"
conditions {
display_name = "SGTM CPU Utilization > 60% for Production"
condition_threshold {
filter = <<-EOT
metric.type="run.googleapis.com/container/cpu/utilizations" AND
resource.type="cloud_run_revision" AND
resource.label.service_name="${var.service_name_production}"
EOT
comparison = "COMPARISON_GT"
threshold_value = 0.6
duration = "300s"
aggregations {
alignment_period = "300s"
per_series_aligner = "ALIGN_PERCENTILE_99"
}
}
}
notification_channels = [ for channel in google_monitoring_notification_channel.sgtm_notification_channels : channel.id ]
depends_on = [ google_monitoring_notification_channel.sgtm_notification_channels ]
}
resource "google_monitoring_alert_policy" "sgtm_instance_count_alert_policy" {
display_name = "SGTM High Instance Count Alert"
combiner = "OR"
conditions {
display_name = "SGTM Instance Count Exceeds 80% of Maximum"
condition_threshold {
filter = <<-EOT
metric.type="run.googleapis.com/container/instance_count" AND
resource.type="cloud_run_revision" AND
resource.label.service_name="${var.service_name_production}"
EOT
aggregations {
alignment_period = "300s"
per_series_aligner = "ALIGN_MEAN"
}
comparison = "COMPARISON_GT"
threshold_value = var.alert_instance_count
duration = "300s"
}
}
notification_channels = [ for channel in google_monitoring_notification_channel.sgtm_notification_channels : channel.id ]
depends_on = [ google_monitoring_notification_channel.sgtm_notification_channels ]
}
resource "google_monitoring_alert_policy" "sgtm_request_latency_alert" {
display_name = "SGTM High Request Latency Alert"
combiner = "OR"
conditions {
display_name = "SGTM Request Latency Exceeds 2 Seconds"
condition_threshold {
filter = <<-EOT
metric.type="run.googleapis.com/request_latencies" AND
resource.type="cloud_run_revision" AND
resource.label.service_name="${var.service_name_production}"
EOT
aggregations {
alignment_period = "300s"
per_series_aligner = "ALIGN_PERCENTILE_99"
}
comparison = "COMPARISON_GT"
threshold_value = 2000
duration = "300s"
}
}
notification_channels = [ for channel in google_monitoring_notification_channel.sgtm_notification_channels : channel.id ]
depends_on = [ google_monitoring_notification_channel.sgtm_notification_channels ]
}
resource "google_logging_metric" "sgtm_http_error_responses_metric" {
name = "http_error_responses"
description = "Count of HTTP error responses for specific paths"
filter = <<EOT
resource.type="http_load_balancer"
httpRequest.status>=400
httpRequest.requestUrl=~("gtm.js" OR "/gtag/" OR "/g/collect")
EOT
metric_descriptor {
metric_kind = "DELTA"
value_type = "INT64"
labels {
key = "status_code"
value_type = "INT64"
description = "The HTTP status code of the response."
}
}
label_extractors = {
"status_code" = "EXTRACT(httpRequest.status)"
}
}
resource "google_monitoring_alert_policy" "sgtm_error_logs_alert" {
display_name = "SGTM High HTTP Error Rate Alert"
combiner = "OR"
conditions {
display_name = "Error Rate Exceeds Threshold"
condition_threshold {
filter = <<-EOT
metric.type="logging.googleapis.com/user/http_error_responses" AND
resource.type="l7_lb_rule"
EOT
aggregations {
alignment_period = "300s"
per_series_aligner = "ALIGN_RATE"
}
comparison = "COMPARISON_GT"
threshold_value = 5.0
duration = "0s"
}
}
notification_channels = [ for channel in google_monitoring_notification_channel.sgtm_notification_channels : channel.id ]
depends_on = [ google_monitoring_notification_channel.sgtm_notification_channels ]
}
# download cloud function files from github
resource "null_resource" "index_js" {
triggers = {
always_run = "${timestamp()}"
}
provisioner "local-exec" {
command = "curl -L https://raw.githubusercontent.com/liscor/sgtm_cloud_run_updater/main/index.js --output ${path.module}/cf_function/index.js"
}
}
resource "null_resource" "package_json" {
triggers = {
always_run = "${timestamp()}"
}
provisioner "local-exec" {
command = "curl -L https://raw.githubusercontent.com/liscor/sgtm_cloud_run_updater/main/package.json --output ${path.module}/cf_function/package.json"
}
}
data "archive_file" "function_zip" {
type = "zip"
output_path = "${path.module}/cf_function/function.zip"
source_dir = "${path.module}/cf_function"
excludes = ["${path.module}/cf_function/function.zip"]
depends_on = [null_resource.index_js,null_resource.package_json]
}
resource "google_storage_bucket" "bucket" {
name = var.google_storage_bucket_name
location = "EU"
}
# Upload the Cloud Function source file
resource "google_storage_bucket_object" "source_files" {
name = "sgtm_cloud_run_updater"
bucket = google_storage_bucket.bucket.name
source = "cf_function/function.zip"
depends_on = [ google_storage_bucket.bucket, data.archive_file.function_zip ]
}
# Create Cloud Function for updating
resource "google_cloudfunctions_function" "sgtm_updater" {
name = "sgtm_cloud_run_updater"
description = "Cloud Function to update the Cloud Run sgtm if necessary."
service_account_email = google_service_account.sgtm_service_account.email
runtime = "nodejs20"
region = var.region
available_memory_mb = 256
source_archive_bucket = google_storage_bucket.bucket.name
source_archive_object = google_storage_bucket_object.source_files.name
trigger_http = true
entry_point = "check_cloud_run"
depends_on = [ google_storage_bucket_object.source_files ]
}
# Triggers the sgtm cloud updater for gtm-production once a day
resource "google_cloud_scheduler_job" "run_sgtm_updater_production" {
name = "run_sgtm_updater_production"
description = "Execute the SGTM Cloud Function on a daily basis to check for updates and deploy these as well."
region = var.region
schedule = var.update_interval
time_zone = "Europe/Berlin"
attempt_deadline = "320s"
retry_config {
retry_count = 1
}
http_target {
http_method = "POST"
uri = google_cloudfunctions_function.sgtm_updater.https_trigger_url
body = base64encode("{\"project_id\":\"${var.project_id}\",\"region\":\"${var.region}\",\"service_name\":\"${google_cloud_run_v2_service.gtm_production.name}\"}")
headers = {
"Content-Type" = "application/json"
}
oidc_token {
service_account_email = google_service_account.sgtm_service_account.email
}
}
depends_on = [ google_cloudfunctions_function.sgtm_updater,google_cloud_run_v2_service.gtm_production ]
}
# Triggers the sgtm cloud updater for gtm-debug once a day
resource "google_cloud_scheduler_job" "run_sgtm_updater_debug" {
name = "run_sgtm_updater_debug"
description = "Execute the SGTM Cloud Function on a daily basis to check for updates and deploy these as well."
region = var.region
schedule = var.update_interval
time_zone = "Europe/Berlin"
attempt_deadline = "320s"
retry_config {
retry_count = 1
}
http_target {
http_method = "POST"
uri = google_cloudfunctions_function.sgtm_updater.https_trigger_url
body = base64encode("{\"project_id\":\"${var.project_id}\",\"region\":\"${var.region}\",\"service_name\":\"${google_cloud_run_v2_service.gtm_preview.name}\"}")
headers = {
"Content-Type" = "application/json"
}
oidc_token {
service_account_email = google_service_account.sgtm_service_account.email
}
}
depends_on = [ google_cloudfunctions_function.sgtm_updater,google_cloud_run_v2_service.gtm_preview ]
}