Add current IP automatically to whitelists for SSH and Kubernetes

After I removed the automatic IP addition to the firewalls for SSH and
Kubernetes I ran into a problem only a few days later. My ISP changed
my IPs and I was to stupid to realize that immediately. So, this change
reintroduces the automatic addition of my current IPs to the whitelists
for Kubernetes and SSH. Though, I adjusted the algorithm, so it will not
change every day or so, but instead really only when my ISP changes my
IPs.
This commit is contained in:
2025-10-22 19:20:01 +02:00
parent adfa2674c6
commit 0eaa5d3b08
3 changed files with 45 additions and 2 deletions

29
main.tf
View File

@@ -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"]

View File

@@ -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" {

View File

@@ -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" {}