首页 > 解决方案 > Kubernetes REST API call using python

问题描述

I'm looking for a way to find a pod by name, and run REST call using python. I thought of using port forwarding and kubernetes client

Can someone share a code sample or any other way to do it?

Here is what I started to do:

from kubernetes import client, config 
config.load_kube_config(config_file="my file") client = client.CoreV1Api() 
pods = client.list_namespaced_pod(namespace="my namespace") # loop pods to 
#find my pod

Next I thought of using:

stream(client.connect_get_namespaced_pod_portforward_with_http_info ...

In kubectl command line tool I do the following: 1. List pods 2. Open port forward 3. Use curl to perform the REST call

I want to do the same in python

标签: pythonkubernetes

解决方案


列出所有 pod:

from kubernetes import client, config

# Configs can be set in Configuration class directly or using helper utility
config.load_kube_config()

v1 = client.CoreV1Api()
print("Listing pods with their IPs:")
ret = v1.list_pod_for_all_namespaces(watch=False)
for i in ret.items:
    print("%s\t%s\t%s" % (i.status.pod_ip, i.metadata.namespace, i.metadata.name))

然后在上面的 for 循环中,您可以检查您的 pod name ,如果匹配则返回。


推荐阅读