forked from runatlantis/terraform-gce-atlantis
-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.tf
512 lines (443 loc) · 15 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
locals {
# The default port that Atlantis runs on is 4141, we default to this.
atlantis_port = lookup(var.env_vars, "ATLANTIS_PORT", 4141)
# Atlantis' home directory is "/home/atlantis", we default to this.
atlantis_data_dir = lookup(var.env_vars, "ATLANTIS_DATA_DIR", "/home/atlantis")
atlantis_port_name = "atlantis"
atlantis_network_traffic_tags = ["atlantis-${random_string.random.result}"]
atlantis_labels = merge(
var.labels,
module.container.container_vm.labels,
{ "vm" = module.container.container_vm.name },
{ "app" = "atlantis" }
)
}
resource "random_string" "random" {
length = 6
special = false
lower = true
upper = false
}
data "google_compute_image" "cos" {
count = var.machine_image == null ? 1 : 0
family = "cos-stable"
project = "cos-cloud"
}
data "google_netblock_ip_ranges" "this" {
for_each = toset([
"health-checkers",
"legacy-health-checkers",
])
range_type = each.key
}
data "cloudinit_config" "config" {
gzip = false
base64_encode = false
part {
filename = "atlantis-chown-disk.service"
content_type = "text/cloud-config"
content = yamlencode({
write_files = [
{
path = "/etc/systemd/system/atlantis-chown-disk.service"
permissions = "0644"
owner = "root"
content = <<EOF
[Unit]
Description=Change ownership of the mount path to the Atlantis uid
Wants=konlet-startup.service
After=konlet-startup.service
[Service]
ExecStart=/bin/chown 100 /mnt/disks/gce-containers-mounts/gce-persistent-disks/atlantis-disk-0
Restart=on-failure
RestartSec=30
StandardOutput=journal+console
[Install]
WantedBy=multi-user.target
EOF
}
]
})
}
part {
filename = "runcmda"
content_type = "text/cloud-config"
merge_type = "list(append)+dict(no_replace, recurse_list)+str()"
content = yamlencode({
runcmd = [
"systemctl daemon-reload",
"systemctl start --no-block atlantis-chown-disk.service"
]
})
}
}
module "container" {
source = "terraform-google-modules/container-vm/google"
version = "~> 3.2"
cos_image_name = var.machine_image != null ? element(split("/", var.machine_image), length(split("/", var.machine_image)) - 1) : null
container = {
image = var.image
securityContext = {
privileged = false
}
tty = true
env = [for key, value in var.env_vars : {
name = key
value = value
}]
command = var.command
args = var.args
# Declare volumes to be mounted.
# This is similar to how docker volumes are declared.
volumeMounts = [
{
mountPath = local.atlantis_data_dir
name = "atlantis-disk-0"
readOnly = false
},
]
}
volumes = [
{
name = "atlantis-disk-0"
gcePersistentDisk = {
pdName = "atlantis-disk-0"
fsType = "ext4"
}
},
]
restart_policy = "Always"
}
locals {
# in order to not add unecessary stuff to past deployments cos-update-strategy should not be set if enable_autoupdate is null, which is the default value
update_strategy_metadata = var.enable_autoupdate == null ? {} : { cos-update-strategy = var.enable_autoupdate ? "update_enabled" : "update_disabled" }
}
resource "google_compute_instance_template" "default" {
name_prefix = "${var.name}-"
description = "This template is used to create VMs that run Atlantis in a containerized environment using Docker"
instance_description = "VM running Atlantis in a containerized environment using Docker"
region = var.region
machine_type = var.machine_type
can_ip_forward = false
metadata_startup_script = var.startup_script
metadata = merge({
gce-container-declaration = module.container.metadata_value
user-data = data.cloudinit_config.config.rendered
google-logging-enabled = var.google_logging_enabled
google-monitoring-enabled = var.google_monitoring_enabled
google-logging-use-fluentbit = var.google_logging_use_fluentbit
block-project-ssh-keys = var.block_project_ssh_keys_enabled
enable-oslogin = var.enable_oslogin
}, local.update_strategy_metadata)
# Using the below scheduling configuration,
# the managed instance group will recreate the Spot VM if Compute Engine stops them
scheduling {
automatic_restart = var.spot_machine_enabled ? false : true
preemptible = var.spot_machine_enabled ? true : false
provisioning_model = var.spot_machine_enabled ? "SPOT" : "STANDARD"
on_host_maintenance = (var.spot_machine_enabled || var.enable_confidential_vm) ? "TERMINATE" : "MIGRATE"
instance_termination_action = var.spot_machine_enabled ? "STOP" : null
}
# Ephemeral OS boot disk
disk {
source_image = var.machine_image != null ? var.machine_image : data.google_compute_image.cos[0].self_link
auto_delete = true
boot = true
disk_type = "pd-ssd"
disk_size_gb = 10
labels = merge(
local.atlantis_labels,
{
"disk-type" = "boot"
},
)
dynamic "disk_encryption_key" {
for_each = var.disk_kms_key_self_link != null ? [1] : []
content {
kms_key_self_link = var.disk_kms_key_self_link
}
}
}
# Persistent disk for Atlantis
disk {
device_name = "atlantis-disk-0"
mode = "READ_WRITE"
source = google_compute_disk.persistent.name
auto_delete = false
}
network_interface {
subnetwork = var.subnetwork
subnetwork_project = try(var.shared_vpc.host_project_id, var.project)
}
shielded_instance_config {
enable_integrity_monitoring = var.shielded_instance_config.enable_integrity_monitoring
enable_vtpm = var.shielded_instance_config.enable_vtpm
enable_secure_boot = var.shielded_instance_config.enable_secure_boot
}
service_account {
email = var.service_account.email
scopes = var.service_account.scopes
}
confidential_instance_config {
enable_confidential_compute = var.enable_confidential_vm
}
tags = concat(local.atlantis_network_traffic_tags, var.tags)
labels = local.atlantis_labels
project = var.project
# Instance Templates cannot be updated after creation with the Google Cloud Platform API.
# In order to update an Instance Template, Terraform will destroy the existing resource and create a replacement
lifecycle {
create_before_destroy = true
}
}
resource "google_compute_disk" "persistent" {
name = var.name
type = var.persistent_disk_type
size = var.persistent_disk_size_gb
zone = var.zone
labels = merge(
local.atlantis_labels,
{
"disk-type" = "data"
},
)
dynamic "disk_encryption_key" {
for_each = var.disk_kms_key_self_link != null ? [1] : []
content {
kms_key_self_link = var.disk_kms_key_self_link
}
}
}
resource "google_compute_health_check" "default" {
name = var.name
check_interval_sec = 1
timeout_sec = 1
healthy_threshold = 1
unhealthy_threshold = 5
tcp_health_check {
port = local.atlantis_port
}
project = var.project
}
resource "google_compute_health_check" "default_instance_group_manager" {
name = "${var.name}-mig"
healthy_threshold = 1
unhealthy_threshold = 10
http_health_check {
port = local.atlantis_port
request_path = "/healthz"
}
project = var.project
}
resource "google_compute_instance_group_manager" "default" {
name = var.name
base_instance_name = var.name
zone = var.zone
description = "Instance group manager responsible for managing the VM running Atlantis in a containerized environment using Docker"
version {
instance_template = google_compute_instance_template.default.id
}
all_instances_config {
labels = local.atlantis_labels
}
named_port {
name = local.atlantis_port_name
port = local.atlantis_port
}
auto_healing_policies {
health_check = google_compute_health_check.default_instance_group_manager.id
initial_delay_sec = 30
}
# We cannot set target_size when using an autoscaler
target_size = var.autoscaling == null ? 1 : null
update_policy {
type = "PROACTIVE"
minimal_action = "RESTART"
most_disruptive_allowed_action = "REPLACE"
max_surge_fixed = 0
max_unavailable_fixed = 1
replacement_method = "RECREATE"
}
project = var.project
provider = google-beta
}
resource "google_compute_autoscaler" "default" {
count = var.autoscaling == null ? 0 : 1
name = var.name
zone = var.zone
target = google_compute_instance_group_manager.default.id
autoscaling_policy {
max_replicas = 1 # Allow at most one instance
min_replicas = 0 # Allow scaling down to zero
cooldown_period = 60
dynamic "scaling_schedules" {
for_each = var.autoscaling.schedules == null ? [] : var.autoscaling.schedules
content {
name = scaling_schedules.value.name
description = scaling_schedules.value.description
min_required_replicas = 1
schedule = scaling_schedules.value.schedule
time_zone = scaling_schedules.value.time_zone
duration_sec = scaling_schedules.value.duration_sec
}
}
}
}
resource "google_compute_global_address" "default" {
name = var.name
project = var.project
}
resource "google_compute_managed_ssl_certificate" "default" {
name = var.name
managed {
domains = [var.domain]
}
project = var.project
}
resource "google_compute_backend_service" "default" {
name = var.name
protocol = "HTTP"
port_name = local.atlantis_port_name
timeout_sec = 10
connection_draining_timeout_sec = 5
load_balancing_scheme = "EXTERNAL_MANAGED"
health_checks = [google_compute_health_check.default.id]
security_policy = var.default_backend_security_policy
log_config {
enable = true
sample_rate = 1
}
backend {
balancing_mode = "UTILIZATION"
max_utilization = 0.8
group = google_compute_instance_group_manager.default.instance_group
}
project = var.project
}
resource "google_compute_backend_service" "iap" {
count = var.iap != null ? 1 : 0
name = "${var.name}-iap"
protocol = "HTTP"
port_name = local.atlantis_port_name
timeout_sec = 10
connection_draining_timeout_sec = 5
load_balancing_scheme = "EXTERNAL_MANAGED"
health_checks = [google_compute_health_check.default.id]
security_policy = var.iap_backend_security_policy
log_config {
enable = true
sample_rate = 1
}
iap {
enabled = true
oauth2_client_id = var.iap.oauth2_client_id
oauth2_client_secret = var.iap.oauth2_client_secret
}
backend {
balancing_mode = "UTILIZATION"
max_utilization = 0.8
group = google_compute_instance_group_manager.default.instance_group
}
project = var.project
lifecycle {
create_before_destroy = true
}
}
resource "google_compute_url_map" "default" {
name = var.name
project = var.project
# If IAP is not used, use default backend service for unmatched requests
default_service = var.iap == null ? google_compute_backend_service.default.id : null
# If IAP is used, redirect unmatched requests to Atlantis domain
dynamic "default_url_redirect" {
for_each = var.iap != null ? [1] : []
content {
host_redirect = var.domain
https_redirect = true
redirect_response_code = "MOVED_PERMANENTLY_DEFAULT"
strip_query = false
}
}
# As Atlantis uses the `/events` path to handle incoming webhook events
# we shouldn't put it behind IAP, it should be protected using a webhook secret.
dynamic "host_rule" {
for_each = var.iap != null ? [1] : []
content {
hosts = [var.domain]
path_matcher = "public"
}
}
dynamic "path_matcher" {
for_each = var.iap != null ? [1] : []
content {
name = "public"
default_service = google_compute_backend_service.iap[0].id
path_rule {
paths = ["/events"]
service = google_compute_backend_service.default.id
}
dynamic "path_rule" {
for_each = var.expose_metrics_publicly ? [1] : []
content {
paths = ["/metrics"]
service = google_compute_backend_service.default.id
}
}
dynamic "path_rule" {
for_each = var.expose_healthz_publicly ? [1] : []
content {
paths = ["/healthz"]
service = google_compute_backend_service.default.id
}
}
}
}
}
resource "google_compute_target_https_proxy" "default" {
name = var.name
url_map = google_compute_url_map.default.id
ssl_certificates = [
google_compute_managed_ssl_certificate.default.id,
]
ssl_policy = var.ssl_policy
project = var.project
}
resource "google_compute_global_forwarding_rule" "https" {
name = var.name
target = google_compute_target_https_proxy.default.id
port_range = "443"
ip_address = google_compute_global_address.default.address
load_balancing_scheme = "EXTERNAL_MANAGED"
project = var.project
}
# Route public internet traffic to the default internet gateway
resource "google_compute_route" "public_internet" {
count = var.shared_vpc == null ? 1 : 0
network = var.network
name = "${var.name}-public-internet"
description = "Custom static route for Altantis to communicate with the public internet"
dest_range = "0.0.0.0/0"
next_hop_gateway = "default-internet-gateway"
priority = 0
project = var.project
tags = local.atlantis_network_traffic_tags
}
# This firewall rule allows Google Cloud to issue the health checks
resource "google_compute_firewall" "lb_health_check" {
count = var.shared_vpc == null ? 1 : 0
name = "${var.name}-lb-health-checks"
description = "Firewall rule to allow inbound Google Load Balancer health checks to the Atlantis instance"
priority = 0
direction = "INGRESS"
network = var.network
allow {
protocol = "tcp"
}
# These are the source IP ranges for health checks (managed by Google Cloud)
source_ranges = distinct(concat(
data.google_netblock_ip_ranges.this["health-checkers"].cidr_blocks_ipv4,
data.google_netblock_ip_ranges.this["legacy-health-checkers"].cidr_blocks_ipv4,
))
project = var.project
target_tags = local.atlantis_network_traffic_tags
}