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

kar*_*los 2 kubernetes kubectl

我正在尝试从 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
Run Code Online (Sandbox Code Playgroud)

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

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))
Run Code Online (Sandbox Code Playgroud)

但我收到此错误:

kubernetes.config.config_exception.ConfigException: Invalid kube-config file. No configuration found.
Run Code Online (Sandbox Code Playgroud)

cod*_*ger 5

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

  • 谢谢错误消失了,但我看到这个知道 kubernetes.client.exceptions.ApiException: (403) Reason: Forbidden HTTP response body: {"kind":"Status","apiVersion":"v1","metadata": {},"status":"Failure","message":"pod 被禁止: (5认同)
  • 您需要使用各种角色/绑定类型为其设置 ServiceAccount 和 RBAC 权限,就像您向人类授予权限一样。 (3认同)
  • 请参阅 https://kubernetes.io/docs/reference/access-authn-authz/rbac/ 作为起点。 (3认同)