Saturday, March 19, 2022

Working with Kubernetes using Python - Part 02 - Switch context

Following code snipet uses kubeconfig python module and it takes the default kubeconfig file, and switch to a new context. 

kubectl commands: 

kubectl config get-contexts
kubectl config current-context
kubectl config use-context <context_name>

Code: 

# prerequisite: pip3 install kubeconfig
# this code snipet can be used to switch to a different context
from kubeconfig import KubeConfig
import argparse
def main():
parser = argparse.ArgumentParser()
parser.add_argument(
"-c", "--cluster", required=True, help="K8s cluster context name"
)
args = parser.parse_args()
new_context = args.cluster
conf = KubeConfig()
print("Kubeconfig file: ", conf.view())
print("Current context: ", conf.current_context())
conf.use_context(new_context)
print("Switched to context: ", conf.current_context())
if __name__ == "__main__":
main()

Note: If you want to use a specific kubeconfig file, instead of  conf = KubeConfig() 

you can use conf = KubeConfig('path-to-your-kubeconfig')

Reference:

https://kubeconfig-python.readthedocs.io/en/latest/

Hope it was useful. Cheers!

Friday, March 4, 2022

Working with Kubernetes using Python - Part 01 - List contexts

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: 

# 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!