Skip to content

Commit e7dbaf1

Browse files
committed
k8s: add open/write kubeconfig fn; add K8sError
The K8sError allows us to easily handle one single error that crops up from functions that life in k8s.py. Right now I just have it implemented in the open/write kubeconfig functions.
1 parent ae19f28 commit e7dbaf1

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

src/warnet/k8s.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,10 @@
2525
from .process import run_command, stream_command
2626

2727

28+
class K8sError(Exception):
29+
pass
30+
31+
2832
def get_static_client() -> CoreV1Api:
2933
config.load_kube_config(config_file=KUBECONFIG)
3034
return client.CoreV1Api()
@@ -458,3 +462,24 @@ def can_delete_pods(namespace: Optional[str] = None) -> bool:
458462
except ApiException as e:
459463
print(f"An error occurred: {e}")
460464
return False
465+
466+
467+
def open_kubeconfig(kubeconfig_path: str) -> dict:
468+
try:
469+
with open(kubeconfig_path) as file:
470+
return yaml.safe_load(file)
471+
except FileNotFoundError as e:
472+
raise K8sError(f"Kubeconfig file {kubeconfig_path} not found.") from e
473+
except yaml.YAMLError as e:
474+
raise K8sError(f"Error parsing kubeconfig: {e}") from e
475+
476+
477+
def write_kubeconfig(kube_config: dict, kubeconfig_path: str) -> None:
478+
dir_name = os.path.dirname(kubeconfig_path)
479+
try:
480+
with tempfile.NamedTemporaryFile("w", dir=dir_name, delete=False) as temp_file:
481+
yaml.safe_dump(kube_config, temp_file)
482+
os.replace(temp_file.name, kubeconfig_path)
483+
except Exception as e:
484+
os.remove(temp_file.name)
485+
raise K8sError(f"Error writing kubeconfig: {kubeconfig_path}") from e

0 commit comments

Comments
 (0)