ungleich-tools/k8s/k8s-router.py
2023-06-10 13:59:08 +02:00

64 lines
1.5 KiB
Python
Executable file

#!/usr/bin/env python3
# Connect to the router pod
# On Alpine: nb3:~# apk add py3-kubernetes
import sys
import os
import subprocess
from kubernetes import client, config
# ~/k8s contains the config files
K8SCONFIGDIR=os.path.join(os.environ['HOME'], "k8s")
routermap = {
"p5-r1": "server137",
"p5-r2": "server138",
"p6-r1": "server139",
"p6-r2": "server140",
"p10-r1": "server122",
"p10-r2": "server123",
"p15-r1": "server120",
"p15-r2": "server121",
}
if not len(sys.argv) == 2:
print(f"{sys.argv[0]} <pX-r1|r2>")
sys.exit(1)
router=sys.argv[1]
if not router in routermap:
print(f"Router {router} not known")
sys.exit(1)
k8sconfig = os.path.join(K8SCONFIGDIR, f"{routermap[router]}.conf")
print(f"Using KUBECONFIG={k8sconfig} for accessing {router} ...")
if not os.path.exists(k8sconfig):
print(f"You need to have {k8sconfig} for accessing {router}")
sys.exit(1)
config.load_kube_config(config_file=k8sconfig)
v1 = client.CoreV1Api()
pods = v1.list_pod_for_all_namespaces(watch=False,
label_selector="app.kubernetes.io/component=bird")
num_pods = len(pods.items)
print("Number of pods: " + str(num_pods))
if not num_pods == 1:
print(f"There should be exactly 1 matching pod - there are {num_pods} pods")
sys.exit(1)
pod=pods.items[0].metadata.name
print(f"Pod: {pod}")
os.environ["KUBECONFIG"] = k8sconfig
cmd = f"kubectl exec -ti {pod} -c bird -- sh"
p = subprocess.run(cmd, shell=True)