···11+#! /usr/bin/env nix-shell
22+#! nix-shell -i python3 -p python313Packages.pyyaml
33+44+import json
55+import subprocess
66+import sys
77+import yaml
88+99+def get_kubeconfig(host, user):
1010+ try:
1111+ result = subprocess.check_output(
1212+ ["ssh", f"{user}@{host}", "cat /etc/rancher/k3s/k3s.yaml"],
1313+ stderr=subprocess.STDOUT
1414+ ).decode("utf-8")
1515+1616+ # Replace the value of the server field with the IP of the K3s server
1717+ config = yaml.safe_load(result)
1818+ config["clusters"][0]["cluster"]["server"] = f"https://[{host}]:6443"
1919+2020+ updated_yaml = yaml.dump(config, default_flow_style=False)
2121+2222+ return {"kubeconfig": updated_yaml}
2323+ # TODO fail hard when error
2424+ except subprocess.CalledProcessError as e:
2525+ return {"error": e.output.decode("utf-8")}
2626+ except Exception as e:
2727+ return {"error": str(e)}
2828+2929+if __name__ == "__main__":
3030+ args = json.load(sys.stdin)
3131+ host = args.get("host")
3232+ user = args.get("user", "root")
3333+ output = get_kubeconfig(host, user)
3434+ print(json.dumps(output))
+9
infra/_modules/nixos/main.tf
···2626 local_file.hosts
2727 ]
2828}
2929+3030+data "external" "kubeconfig" {
3131+ program = ["${path.module}/kubeconfig_datasource.py"]
3232+3333+ query = {
3434+ user = "root"
3535+ host = var.hosts["kube-1"].ipv6_address # TODO better way to get this
3636+ }
3737+}