无效的 kube-config 文件。当我在 pod 中使用 kubernetes 客户端 python 时找不到配置

Invalid kube-config file. No configuration found when i use kubernetes client python in pod

我正在尝试从 pod 获取 kubernetes api 服务器。

这是我的 pod 配置

apiVersion: batch/v1beta1
kind: CronJob
metadata:
  name: test
spec:
  schedule: "*/5 * * * *"
  jobTemplate:
    spec:
      template:
        spec:
          containers:
          - name: test
            image: test:v5
            env:
            imagePullPolicy: IfNotPresent
            command: ['python3']
            args: ['test.py']
          restartPolicy: OnFailure

这是我的 kubernetes-client python 代码 test.py

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))

但是我收到这个错误:

kubernetes.config.config_exception.ConfigException: Invalid kube-config file. No configuration found.

在集群中运行时,您需要 load_incluster_config()