forked from hcloud-talos/terraform-hcloud-talos
-
Notifications
You must be signed in to change notification settings - Fork 0
/
firewall.tf
84 lines (76 loc) · 2.66 KB
/
firewall.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
# Retrieve the public IP address of the current machine if the firewall should be opened for the current IP
data "http" "personal_ipv4" {
count = var.firewall_use_current_ip ? 1 : 0
url = "https://ipv4.icanhazip.com"
}
data "http" "personal_ipv6" {
count = var.firewall_use_current_ip ? 1 : 0
url = "https://ipv6.icanhazip.com"
}
locals {
current_ips = var.firewall_use_current_ip ? [
"${chomp(data.http.personal_ipv4[0].response_body)}/32",
"${chomp(data.http.personal_ipv6[0].response_body)}/128",
] : []
base_firewall_rules = concat(
var.firewall_kube_api_source == null && !var.firewall_use_current_ip ? [] : [
{
description = "Allow Incoming Requests to Kube API Server"
direction = "in"
protocol = "tcp"
port = "6443"
source_ips = var.firewall_kube_api_source != null ? var.firewall_kube_api_source : local.current_ips
}
],
var.firewall_talos_api_source == null && !var.firewall_use_current_ip ? [] : [
{
description = "Allow Incoming Requests to Talos API Server"
direction = "in"
protocol = "tcp"
port = "50000"
source_ips = var.firewall_talos_api_source != null ? var.firewall_talos_api_source : local.current_ips
}
],
)
# create a new firewall list based on base_firewall_rules but with direction-protocol-port as key
# this is needed to avoid duplicate rules
firewall_rules = {
for rule in local.base_firewall_rules :
format("%s-%s-%s",
lookup(rule, "direction", "null"),
lookup(rule, "protocol", "null"),
lookup(rule, "port", "null")
) => rule
}
# do the same for var.extra_firewall_rules
extra_firewall_rules = {
for rule in var.extra_firewall_rules :
format("%s-%s-%s",
lookup(rule, "direction", "null"),
lookup(rule, "protocol", "null"),
lookup(rule, "port", "null")
) => rule
}
# merge the two lists
firewall_rules_merged = merge(local.firewall_rules, local.extra_firewall_rules)
# convert the merged list back to a list
firewall_rules_list = values(local.firewall_rules_merged)
}
resource "hcloud_firewall" "this" {
name = var.cluster_name
dynamic "rule" {
for_each = local.firewall_rules_list
//noinspection HILUnresolvedReference
content {
description = rule.value.description
direction = rule.value.direction
protocol = rule.value.protocol
port = lookup(rule.value, "port", null)
destination_ips = lookup(rule.value, "destination_ips", [])
source_ips = lookup(rule.value, "source_ips", [])
}
}
labels = {
"cluster" = var.cluster_name
}
}