Skip to content

Commit 6a48a64

Browse files
committed
k8s: update getting namespace logic
1 parent 8ccb33f commit 6a48a64

File tree

1 file changed

+19
-5
lines changed

1 file changed

+19
-5
lines changed

src/warnet/k8s.py

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
import yaml
1010
from kubernetes import client, config, watch
1111
from kubernetes.client import CoreV1Api
12-
from kubernetes.client.models import V1Pod, V1PodList
12+
from kubernetes.client.models import V1Namespace, V1Pod, V1PodList
1313
from kubernetes.client.rest import ApiException
1414
from kubernetes.dynamic import DynamicClient
1515
from kubernetes.stream import stream
@@ -360,18 +360,32 @@ def write_file_to_container(pod_name, container_name, dst_path, data):
360360
return True
361361
except Exception as e:
362362
print(f"Failed to copy data to {pod_name}({container_name}):{dst_path}:\n{e}")
363+
364+
363365
def get_kubeconfig_value(jsonpath):
364366
command = f"kubectl config view --minify -o jsonpath={jsonpath}"
365367
return run_command(command)
366368

367369

368-
def get_namespaces_by_prefix(prefix: str):
370+
def get_namespaces() -> list[V1Namespace]:
371+
sclient = get_static_client()
372+
try:
373+
return sclient.list_namespace().items
374+
375+
except ApiException as e:
376+
if e.status == 403:
377+
ns = sclient.read_namespace(name=get_default_namespace())
378+
return [ns]
379+
else:
380+
return []
381+
382+
383+
def get_namespaces_by_prefix(prefix: str) -> list[V1Namespace]:
369384
"""
370385
Get all namespaces beginning with `prefix`. Returns empty list of no namespaces with the specified prefix are found.
371386
"""
372-
command = "kubectl get namespaces -o jsonpath={.items[*].metadata.name}"
373-
namespaces = run_command(command).split()
374-
return [ns for ns in namespaces if ns.startswith(prefix)]
387+
namespaces = get_namespaces()
388+
return [ns for ns in namespaces if ns.metadata.name.startswith(prefix)]
375389

376390

377391
def get_service_accounts_in_namespace(namespace):

0 commit comments

Comments
 (0)