Skip to content

Commit 1a4f065

Browse files
committed
k8s: update getting namespace logic
1 parent 35a233a commit 1a4f065

File tree

1 file changed

+20
-5
lines changed

1 file changed

+20
-5
lines changed

src/warnet/k8s.py

Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,8 @@
88
import yaml
99
from kubernetes import client, config, watch
1010
from kubernetes.client import CoreV1Api
11-
from kubernetes.client.models import V1PodList
11+
from kubernetes.client.exceptions import ApiException
12+
from kubernetes.client.models import V1Namespace, V1PodList
1213
from kubernetes.dynamic import DynamicClient
1314
from kubernetes.stream import stream
1415

@@ -351,18 +352,32 @@ def write_file_to_container(pod_name, container_name, dst_path, data):
351352
return True
352353
except Exception as e:
353354
print(f"Failed to copy data to {pod_name}({container_name}):{dst_path}:\n{e}")
355+
356+
354357
def get_kubeconfig_value(jsonpath):
355358
command = f"kubectl config view --minify -o jsonpath={jsonpath}"
356359
return run_command(command)
357360

358361

359-
def get_namespaces_by_prefix(prefix: str):
362+
def get_namespaces() -> list[V1Namespace]:
363+
sclient = get_static_client()
364+
try:
365+
return sclient.list_namespace().items
366+
367+
except ApiException as e:
368+
if e.status == 403:
369+
ns = sclient.read_namespace(name=get_default_namespace())
370+
return [ns]
371+
else:
372+
return []
373+
374+
375+
def get_namespaces_by_prefix(prefix: str) -> list[V1Namespace]:
360376
"""
361377
Get all namespaces beginning with `prefix`. Returns empty list of no namespaces with the specified prefix are found.
362378
"""
363-
command = "kubectl get namespaces -o jsonpath={.items[*].metadata.name}"
364-
namespaces = run_command(command).split()
365-
return [ns for ns in namespaces if ns.startswith(prefix)]
379+
namespaces = get_namespaces()
380+
return [ns for ns in namespaces if ns.metadata.name.startswith(prefix)]
366381

367382

368383
def get_service_accounts_in_namespace(namespace):

0 commit comments

Comments
 (0)