Skip to content

Commit 02cf9e5

Browse files
committed
k8s: get cluster from current context
1 parent 506bd58 commit 02cf9e5

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

src/warnet/k8s.py

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -395,6 +395,48 @@ def get_kubeconfig_value(jsonpath):
395395
return run_command(command)
396396

397397

398+
def get_cluster_of_current_context(kubeconfig_data: dict) -> dict:
399+
# Get the current context name
400+
current_context_name = kubeconfig_data.get("current-context")
401+
402+
if not current_context_name:
403+
raise K8sError("No current context found in kubeconfig.")
404+
405+
# Find the context entry for the current context
406+
context_entry = next(
407+
(
408+
context
409+
for context in kubeconfig_data.get("contexts", [])
410+
if context["name"] == current_context_name
411+
),
412+
None,
413+
)
414+
415+
if not context_entry:
416+
raise K8sError(f"Context '{current_context_name}' not found in kubeconfig.")
417+
418+
# Get the cluster name from the context entry
419+
cluster_name = context_entry.get("context", {}).get("cluster")
420+
421+
if not cluster_name:
422+
raise K8sError(f"Cluster not specified in context '{current_context_name}'.")
423+
424+
# Find the cluster entry associated with the cluster name
425+
cluster_entry = next(
426+
(
427+
cluster
428+
for cluster in kubeconfig_data.get("clusters", [])
429+
if cluster["name"] == cluster_name
430+
),
431+
None,
432+
)
433+
434+
if not cluster_entry:
435+
raise K8sError(f"Cluster '{cluster_name}' not found in kubeconfig.")
436+
437+
return cluster_entry
438+
439+
398440
def get_namespaces() -> list[V1Namespace]:
399441
sclient = get_static_client()
400442
try:

0 commit comments

Comments
 (0)