Python: Find pod name

Created on 13 Feb 2019  路  6Comments  路  Source: kubernetes-client/python

Hi!
Is there a way to query the pod name by app name?

Most helpful comment

Your method checks a label named app, not a pod name. So if it's true that you want to find pods which have the label app equals app_name you can do it simpler using the label selector:

k8s_api_obj.list_namespaced_pod(namespace, label_selector="app=" + app_name)

All 6 comments

E.g:

kubectl get pods -n dev |grep account

account-service-7f8d56f78c-vlj2c 2/2 Running 0 1d

account-service-7f8d56f78c-vlj2c#

I want to get this name through the interface.

Here is my method

from kubernetes import client, config
from kubernetes.client.rest import ApiException

config.load_kube_config("/root/.kube/config")



def find_namespace_pod(namespace, app_name):
    """
     find namespace pod msg
    """
    k8s_api_obj = client.CoreV1Api()
    api_response = k8s_api_obj.list_namespaced_pod(namespace)
    msg = {}
    for i in api_response.items:
        msg = i.metadata.labels
        msg['pod_name'] = i.metadata.name
        try:
            if msg['app']  == app_name:
                msg.pop('pod-template-hash')
                break
            else:
                continue
        except Exception as e:
            continue
    return msg
print(find_namespace_pod('dev', 'account-service'))
##{'app': 'account-service', 'pod_name': 'account-service-7f8d56f78c-vlj2c'}
######################################################

Is there a better way?

Your method checks a label named app, not a pod name. So if it's true that you want to find pods which have the label app equals app_name you can do it simpler using the label selector:

k8s_api_obj.list_namespaced_pod(namespace, label_selector="app=" + app_name)

@tomplus Thank you. I'll try.

@tomplus Thank you very much. That's exactly what I want.

Why is this closed though? The question was to find a pod based on it's name. an app label doesn't mean that the pod is named that.

Was this page helpful?
0 / 5 - 0 ratings