diff --git a/main.tf b/main.tf index 6559abf..a80cfd4 100644 --- a/main.tf +++ b/main.tf @@ -4,6 +4,31 @@ resource "hcloud_ssh_key" "this" { public_key = each.value } +data "external" "current_ips" { + count = var.add_local_ip_to_ssh_allowed_ips || var.add_local_ip_to_kubernetes_allowed_ips ? 1 : 0 + program = [ + "sh", + "-c", + "(ip -6 route show | awk '/proto ra metric/&&!/^default/{print $1}'; curl -s ipinfo.io/ip; echo /32) | jq -R '{(.): .}' | jq -s add" + ] +} + +locals { + current_ips = flatten([ for value in data.external.current_ips.*.result : values(value) ]) + kubernetes_allowed_ips = toset( + concat( + tolist(var.kubernetes_allowed_ips), + var.add_local_ip_to_kubernetes_allowed_ips ? local.current_ips : [] + ) + ) + ssh_allowed_ips = toset( + concat( + tolist(var.ssh_allowed_ips), + var.add_local_ip_to_ssh_allowed_ips ? local.current_ips : [] + ) + ) +} + module "k8s" { source = "./modules/hetzner/kubernetes" @@ -12,8 +37,8 @@ module "k8s" { servers = var.k8s_servers agents = var.k8s_agents auto_delete_primary_ips = false - kubernetes_exposed_ips = var.kubernetes_allowed_ips - ssh_exposed_ips = var.ssh_allowed_ips + kubernetes_exposed_ips = local.kubernetes_allowed_ips + ssh_exposed_ips = local.ssh_allowed_ips ssh_port = 1022 public_tcp_services = { git-ssh = ["22"] diff --git a/variables.tf b/variables.tf index 2d09672..68520af 100644 --- a/variables.tf +++ b/variables.tf @@ -1,11 +1,23 @@ variable "kubernetes_allowed_ips" { type = set(string) description = "A set of IPs (IPv4 and IPv6) which have access to the kubernetes API." + default = [] } variable "ssh_allowed_ips" { type = set(string) description = "A set of IPs (IPv4 and IPv6) which can access the cluster via SSH." + default = [] +} + +variable "add_local_ip_to_kubernetes_allowed_ips" { + default = true + description = "Whether to add the current local ip to the set of IPs which have access to the kubernetes API." +} + +variable "add_local_ip_to_ssh_allowed_ips" { + default = true + description = "Whether to add the current local ip to the set of IPs which have access to the cluster via SSH." } variable "hetzner_dns_apitoken" { diff --git a/versions.tf b/versions.tf index ea420a6..3b22b83 100644 --- a/versions.tf +++ b/versions.tf @@ -26,6 +26,10 @@ terraform { source = "hashicorp/random" version = "3.7.1" } + external = { + source = "hashicorp/external" + version = "2.3.4" + } } } @@ -38,3 +42,5 @@ provider "hcloud" { } provider "random" {} + +provider "external" {}