Reputation: 403
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.
Upvotes: 9
Views: 19723
Reputation: 336
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)
Upvotes: 1
Reputation: 1380
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))
Upvotes: 24