How to get Nodes using Kubernetes Python Client

close up photo of programming of codes
Reading Time: 3 minutes

Hello Readers! In this blog we will see how we can list the nodes inside any cluster using Kubernetes Python Client. As we all know that generally we use kubectl commands for creating, listing, updating, deleting the kubernetes resources. But In this blog we will see how we can use python for doing these things with nodes. 

Prerequisites:

Before we move forward with getting nodes in a cluster using K8s python client we have some prerequisites that we need to follow.

Kubernetes library provides us modules such as client and config which we will use here. So, let’s install Kubernetes Python Client:

$ pip install kubernetes
kubernetes

Now, we have the python-kubernetes package-installed.

So, let’s get started!

Getting Nodes inside a cluster:

Step1: Firstly I will make a directory and inside this I will make a file in which I will write kubernetes python client code for listing all the nodes inside any cluster. 

Step2: Move to this file and write here the python code. Now that we have the python-kubernetes package installed, we can import it as:

from kubernetes import client, config

For Nodes, we use the CoreV1Api class from the kubernetes python client module. Authentication to the Kubernetes Python Client in other cluster is done by: 

configuration.api_key = {"authorization": "Bearer" + bearer_token}

We will use the Bearer Token which enables requests to authenticate using an access key. We are going to list all the nodes with their attached labels using this code. Here is the full code which will list the nodes inside a cluster:

from kubernetes import client
from kubernetes.client import ApiClient

def __get_kubernetes_client(bearer_token,api_server_endpoint):
    try:
        configuration = client.Configuration()
        configuration.host = api_server_endpoint
        configuration.verify_ssl = False
        configuration.api_key = {"authorization": "Bearer " + bearer_token}
        client.Configuration.set_default(configuration)
        client_api = client.CoreV1Api()
        return client_api
    except Exception as e:
        print("Error getting kubernetes client \n{}".format(e))
        return None

def __format_data_for_nodes(client_output):
        temp_dict={}
        temp_list=[]
        
        json_data=ApiClient().sanitize_for_serialization(client_output)
        #print("JSON_DATA OF KUBERNETES OBJECT:{}".format(json_data))
        if len(json_data["items"]) != 0:
            for node in json_data["items"]:
                temp_dict={
                    "node": node["metadata"]["name"],
                    "labels": node["metadata"]["labels"],
                }
                temp_list.append(temp_dict)
        return temp_list

def get_nodes(cluster_details, namespace="default",all_namespaces=False):
        client_api= __get_kubernetes_client(
            bearer_token=cluster_details["bearer_token"],
            api_server_endpoint=cluster_details["api_server_endpoint"],
        )
       
        node_list = client_api.list_node()
        data=__format_data_for_nodes(node_list)
        print (data)


if __name__ == "__main__":
    cluster_details={
        "bearer_token":"eyJhbGciOiJSUzI1NiIsImtpZCI6IlYxVWh2RUFSYnZPX1Nka0VTdExRVUNpYnhhdnR5WVNQVmtuYXdMMGFyekUifQ.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJkZWZhdWx0Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZWNyZXQubmFtZSI6ImRhc2hib2FyZC1jbHVzdGVyLXJvbGUtdG9rZW4tbXN3bngiLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlcnZpY2UtYWNjb3VudC5uYW1lIjoiZGFzaGJvYXJkLWNsdXN0ZXItcm9sZSIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VydmljZS1hY2NvdW50LnVpZCI6IjJmZTVkNjg4LWM5NjAtNDE4Yy04MWEyLTcyNTJiZDIwNWRhNyIsInN1YiI6InN5c3RlbTpzZXJ2aWNlYWNjb3VudDpkZWZhdWx0OmRhc2hib2FyZC1jbHVzdGVyLXJvbGUifQ.t7gBKdpf6jZNXLswm3aHS_3Gu_PLzuLVBVLx_4gOcxHkyaIJ-vJFj8gSVzSBAmW56D3Rq_tpSVAWPauXv4Cca11PJ9O3ZI_6yuCDRXZre7EcmFDOPrlTjQwH-63mH4ItdWMwqLD2HXABOtnRUwrtSMwBIurZJ53_U_O--XUFo9kxTGqMAyeNY7kCACutHwZeCIXchYQ9WMku01vKLcSyV4p5SdK3Wk6ek-CbyN4fScSfQStgsFN37CV2ssNZTThbi3PXzXVMuKnUQXUzYLSwe46kvvLGnaCIYqRgxWpGMSnHlh--pws73-QKLRFmvO_HOLFDnBOe_06yEJ8i47YP9Q",
        "api_server_endpoint":"https://34.123.166.9"

    }

    
get_nodes(cluster_details)

In the get_nodes.py file we have a function for getting nodes. Give your cluster details in which you want to list the nodes:

cluster_details={
        "bearer_token":"Your_cluster_bearer_token",
        "api_server_endpoint":"Your_cluster_IP"
    }

After providing the details, we need to call that function by:

get_nodes(cluster_details)

Step3: Now, let’s run our code and see the result. Run the code using following command:

$ python3 get_nodes.py

The output is here:

kubernetes python client

Here is the list of all the nodes and their labels which are in my GKE cluster. In the output you will see list of nodes inside a cluster with labels in the following format:

[{'node':'<node_name>', 'labels':{'<list_of_labels>'}}]

So, We are successfully done now. This is how we can list nodes inside any cluster using Kubernetes python client.

Conclusion:

Thank you for sticking to the end. In this blog we have seen how easily we can list nodes inside any cluster using Kubernetes python client. If you like this blog, please do show your appreciation by giving thumbs ups and share this blog and give me suggestions on how I can improve my future posts to suit your needs.

HAPPY LEARNING!

Written by 

Naincy Kumari is a DevOps Consultant at Knoldus Inc. She is always ready to learn new technologies and tools. She loves painting and dancing.