Hi!
Is there a way to query the pod name by app name?
E.g:
account-service-7f8d56f78c-vlj2c 2/2 Running 0 1d
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.
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 labelappequalsapp_nameyou can do it simpler using the label selector: