Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kubernetes: How do I get all pods in a namespace using the python api?

I am using python to access my cluster. The only thing I came across, that is close is list_namespaced_pod, which does not give me the actual names of the pods.

like image 410
A_test_user Avatar asked Sep 14 '18 09:09

A_test_user


2 Answers

As stated in the comments, you can access all information in the metadata of each pod in the list of pod items returned by the API call.

Here is an example:

def get_pods():  

    v1 = client.CoreV1Api()
    pod_list = v1.list_namespaced_pod("example")
    for pod in pod_list.items:
        print("%s\t%s\t%s" % (pod.metadata.name,
                              pod.status.phase,
                              pod.status.pod_ip))
like image 62
Baily Avatar answered Oct 03 '22 07:10

Baily


You would have already found the sol. for getting pod name I am posting here one more.

Below you can get pod from a namespace with particular regex (regex = if you want to search specific pod with some pattern). Also you can check if a specific pod Exists or not with below fn.

from kubernetes import config , client
from kubernetes.client import Configuration
from kubernetes.client.api import core_v1_api
from kubernetes.client.rest import ApiException
from kubernetes.stream import stream
import re 

  pod_namespace = "dev_staging"
  pod_regex = "log_depl"
try:
    config.load_kube_config()
    c = Configuration().get_default_copy()
except AttributeError:
    c = Configuration()
    c.assert_hostname = False
Configuration.set_default(c)
core_v1 = core_v1_api.CoreV1Api()

    def get_pod_name(core_v1,pod_namespace,pod_regex):    
    ret = core_v1.list_namespaced_pod(pod_namespace)
    for i in ret.items:
        #print("%s\t%s\t%s" % (i.status.pod_ip, i.metadata.namespace, i.metadata.name))
        pod_name=i.metadata.name
        if re.match(pod_regex, pod_name):
            return pod_name
    def check_pod_existance(api_instance,pod_namespace,pod_name):
    resp = None
    try:
        resp = api_instance.read_namespaced_pod(name=pod_name,namespace=pod_namespace)
    except ApiException as e:
        if e.status != 404:
            print("Unknown error: %s" % e)
            exit(1)
    if not resp:
        print("Pod %s does not exist. Create it..." % pod_name)

You can call your Functions as:

pod_name=get_pod_name(core_v1,pod_namespace,pod_regex)
    check_pod_existance(core_v1,pod_namespace,pod_name)
like image 23
Dev pokhariya Avatar answered Oct 03 '22 06:10

Dev pokhariya