使用 Kubernetes Python 客戶端創建部署并公開型別為 ClusterIP 的服務后,如何使用 python 客戶端而不是使用 Kubectl 命令獲取集群 IP?
服務是基于示例代碼創建的
def create_service():
core_v1_api = client.CoreV1Api()
body = client.V1Service(
api_version="v1",
kind="Service",
metadata=client.V1ObjectMeta(
name="service-example"
),
spec=client.V1ServiceSpec(
selector={"app": "deployment"},
ports=[client.V1ServicePort(
port=5678,
target_port=5678
)]
)
)
# Creation of the Deployment in specified namespace
# (Can replace "default" with a namespace you may have created)
core_v1_api.create_namespaced_service(namespace="default", body=body)
有一個命令可以在檔案中列出 pod ips
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))
我想知道是否有辦法對來自服務的 Cluster-IP 做類似的事情。
uj5u.com熱心網友回復:
只需獲取服務并讀取其spec.cluster_ip屬性:
from kubernetes import client, config
config.load_kube_config()
api = client.CoreV1Api()
service = api.read_namespaced_service(name="kubernetes", namespace="default")
print(service.spec.cluster_ip)
# 10.100.0.1
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/317624.html
標籤:Python Kubernetes
