Following code snipet uses Python client for the kubernetes API and it takes the default kubeconfig file, list the contexts, and active context.
kubectl commands:
kubectl config get-contexts
kubectl config current-context
Code:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# prerequisite: pip3 install kubernetes | |
from kubernetes import client, config | |
def main(): | |
""" | |
This function will use the default kubeconfig file, list the contexts, and active context. | |
""" | |
contexts, active_context = config.list_kube_config_contexts() | |
if not contexts: | |
print("Cannot find any context in kube-config file.") | |
return | |
contexts = [context["name"] for context in contexts] | |
active_index = contexts.index(active_context["name"]) | |
active_context = active_context["name"] | |
print(f"List of contexts: {contexts}") | |
print(f"Active context index is: {active_index}") | |
print(f"Actice context name is: {active_context}") | |
if __name__ == "__main__": | |
main() |
Note: If you want to use a specific kubeconfig file, instead of
contexts, active_context = config.list_kube_config_contexts()
you can use
contexts, active_context = config.list_kube_config_contexts(config_file="path-to-kubeconfig")
Reference:
https://github.com/kubernetes-client/python
Hope it was useful. Cheers!
No comments:
Post a Comment