Showing posts with label context. Show all posts
Showing posts with label context. Show all posts

Sunday, October 9, 2022

Working with Kubernetes using Python - Part 06 - Create namespace

Following code snipet uses Python client for the kubernetes API to create namespace. You will need to specify the kubeconfig file and the context to use for creating the namespace. This is an example case if you are working with multiple kubeconfig files where multiple K8s clusters could be present in each kubeconfig file.

from kubernetes import client, config
import argparse


def load_kubeconfig(kubeconfig_file, context_name):
try:
config.load_kube_config(
config_file=f"{kubeconfig_file}", context=f"{context_name}"
)
except config.ConfigException as err:
print(err)
raise Exception("Could not configure kubernetes python client!")
v1 = client.CoreV1Api()
return v1


def create_ns(v1, ns_name):
print("Creating namespace")
namespace = client.V1Namespace(metadata={"name": ns_name})
ret = v1.create_namespace(namespace)
print(ret)


def main():
parser = argparse.ArgumentParser()
parser.add_argument("-c", "--context", required=True, help="K8s context")
parser.add_argument("-f", "--file", required=True, help="Kubeconfig file")
args = parser.parse_args()

context = args.context

v1 = load_kubeconfig(args.file, context)

ns_name = input("Enter namespace name: ")
create_ns(v1, ns_name)


if __name__ == "__main__":
main()

Following is sample output:

❯ python3 create_namespace.py -c tkc-admin@tkc -f /Users/vineethac/testing/ccs/tkc.kubeconfig
Enter namespace name: vineethac-test11
Creating namespace
{'api_version': 'v1',
'kind': 'Namespace',
'metadata': {'annotations': None,
'cluster_name': None,
'creation_timestamp': datetime.datetime(2022, 12, 7, 11, 57, 17, tzinfo=tzutc()),
'deletion_grace_period_seconds': None,
'deletion_timestamp': None,
'finalizers': None,
'generate_name': None,
'generation': None,
'labels': {'kubernetes.io/metadata.name': 'vineetha-test11'},
'managed_fields': [{'api_version': 'v1',
'fields_type': 'FieldsV1',
'fields_v1': {'f:metadata': {'f:labels': {'.': {},
'f:kubernetes.io/metadata.name': {}}}},
'manager': 'OpenAPI-Generator',
'operation': 'Update',
'time': datetime.datetime(2022, 12, 7, 11, 57, 17, tzinfo=tzutc())}],
'name': 'vineethac-test11',
'namespace': None,
'owner_references': None,
'resource_version': '5518430',
'self_link': None,
'uid': '0e9f1211-e09f-4d2d-b475-8995bb0c0907'},
'spec': {'finalizers': ['kubernetes']},
'status': {'conditions': None, 'phase': 'Active'}}

Sunday, September 25, 2022

Working with Kubernetes using Python - Part 05 - Get pods

Following code snipet uses Python client for the kubernetes API to get all pods and pods under a specific namespace for a given context:

from kubernetes import client, config
import argparse


def load_kubeconfig(context_name):
config.load_kube_config(context=f"{context_name}")
v1 = client.CoreV1Api()
return v1


def get_all_pods(v1):
print("Listing all pods:")
ret = v1.list_pod_for_all_namespaces(watch=False)
for i in ret.items:
print(i.metadata.namespace, i.metadata.name, i.status.phase)


def get_namespaced_pods(v1, ns):
print(f"Listing all pods under namespace {ns}:")
ret = v1.list_namespaced_pod(f"{ns}")
for i in ret.items:
print(i.metadata.namespace, i.metadata.name, i.status.phase)


def main():
parser = argparse.ArgumentParser()
parser.add_argument("-c", "--context", required=True, help="K8s context")
parser.add_argument("-n", "--namespace", required=False, help="K8s namespace")
args = parser.parse_args()

context = args.context
v1 = load_kubeconfig(context)

if not args.namespace:
get_all_pods(v1)
else:
get_namespaced_pods(v1, args.namespace)


if __name__ == "__main__":
main()


Saturday, June 11, 2022

Working with Kubernetes using Python - Part 04 - Get namespaces

Following code snipet uses Python client for the kubernetes API to get namespace details from a given context:
from kubernetes import client, config
import argparse


def load_kubeconfig(context_name):
config.load_kube_config(context=f"{context_name}")
v1 = client.CoreV1Api()
return v1


def get_all_namespace(v1):
print("Listing namespaces with their creation timestamp, and status:")
ret = v1.list_namespace()
for i in ret.items:
print(i.metadata.name, i.metadata.creation_timestamp, i.status.phase)


def main():
parser = argparse.ArgumentParser()
parser.add_argument("-c", "--context", required=True, help="K8s context")
args = parser.parse_args()

context = args.context
v1 = load_kubeconfig(context)
get_all_namespace(v1)


if __name__ == "__main__":
main()


Friday, April 8, 2022

Working with Kubernetes using Python - Part 03 - Get nodes

Following code snipet uses kubeconfig python module to switch context and Python client for the kubernetes API to get cluster node details. It takes the default kubeconfig file, and switch to the required context, and get node info of the respective cluster. 

kubectl commands: 

kubectl config get-contexts
kubectl config current-context
kubectl config use-context <context_name>
kubectl get nodes -o json

Code: 

# prerequisite: pip3 install kubernetes, pip3 install kubeconfig
# this sample code snipet can be used to get basic node details of a given list of clusters/ contexts
from kubernetes import client, config
from kubeconfig import KubeConfig
import argparse
import json
def get_nodes():
config.load_kube_config()
v1 = client.CoreV1Api()
return v1.list_node(_preload_content=False)
def switch_context(cluster_name):
conf = KubeConfig()
conf.use_context(f"{cluster_name}")
conf_doc = conf.view()
return conf.current_context()
def main():
"""
This function will use the default kubeconfig file, and prints basic node details of a given context.
"""
parser = argparse.ArgumentParser()
parser.add_argument(
"-c", "--cluster", required=True, help="K8s cluster context name"
)
args = parser.parse_args()
all_clusters = args.cluster
cluster_list = all_clusters.split(",")
for cluster_name in cluster_list:
current_context = switch_context(cluster_name)
print(f"Current context: {current_context}")
get_nodes_info = get_nodes()
get_nodes_info_dict = json.loads(get_nodes_info.data)
for each_node in get_nodes_info_dict["items"]:
if (
"node-role.kubernetes.io/control-plane"
in each_node["metadata"]["labels"]
):
role = "Control Plane Node"
elif "node-role.kubernetes.io/agent" in each_node["metadata"]["labels"]:
role = "Worker Node"
print(
f'{each_node["metadata"]["name"]} - {each_node["status"]["nodeInfo"]["operatingSystem"]} - {role}'
)
print("------------------------------------------")
if __name__ == "__main__":
main()
view raw get_nodes.py hosted with ❤ by GitHub

Reference:

https://kubeconfig-python.readthedocs.io/en/latest/
https://github.com/kubernetes-client/python

Hope it was useful. Cheers!

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!