Load kubect config file using Kubernetes Python client returns error: Invalid kube-config file

Load kubect config file using Kubernetes Python client returns error: Invalid kube-config file

我编写了一个服务来从 Kubernetes 集群中检索一些信息。下面是 kubernetes_service.py 文件的一个片段,当我 运行 它在我的本地机器上时它完美地工作。

from kubernetes.client.rest import ApiException
from kubernetes import client, config
from exceptions.logs_not_found_exceptions import LogsNotFound
import logging

log = logging.getLogger("services/kubernetes_service.py")


class KubernetesService:
    def __init__(self):
        super().__init__()
        config.load_kube_config()
        self.api_instance = client.CoreV1Api()

    def get_pods(self, body):
        try:
            api_response = self.api_instance.list_namespaced_pod(namespace=body['namespace'])
            dict_response = api_response.to_dict()
            pods = []
            for item in dict_response['items']:
                pods.append(item['metadata']['name'])

            log.info(f"Retrieved the pods: {pods}")
            return pods
        except ApiException as e:
            raise ApiException(e)

    def get_logs(self, body):
        try:
            api_response = self.api_instance.read_namespaced_pod_log(name=body['pod_name'], namespace=body['namespace'])
            tail_logs = api_response[len(api_response)-16000:]

            log.info(f"Retrieved the logs: {tail_logs}")
            return tail_logs
        except ApiException:
            raise LogsNotFound(body['namespace'], body['pod_name'])

使用 Dockerfile 创建 docker 镜像时,它还安装了 kubectl。下面是我的 Dockerfile。

FROM python:3.8-alpine
RUN mkdir /app
WORKDIR /app

COPY requirements.txt .
RUN pip install -r requirements.txt && rm requirements.txt

RUN apk add curl openssl bash --no-cache
RUN curl -LO "https://storage.googleapis.com/kubernetes-release/release/$(curl -s https://storage.googleapis.com/kubernetes-release/release/stable.txt)/bin/linux/amd64/kubectl" \
    && chmod +x ./kubectl \
    && mv ./kubectl /usr/local/bin/kubectl

COPY . .
EXPOSE 8087
ENTRYPOINT [ "python", "bot.py"]

为了向 运行 命令授予容器权限 kubectl get pods 我在 deployment.yml 文件中添加了角色:

apiVersion: v1
kind: Service
metadata:
  name: pyhelper
spec:
  selector:
    app: pyhelper
  ports:
    - protocol: "TCP"
      port: 8087
      targetPort: 8087
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: pyhelper
spec:
  selector:
    matchLabels:
      app: pyhelper
  replicas: 1
  template:
    metadata:
      labels:
        app: pyhelper
    spec:
      serviceAccountName: k8s-101-role
      containers:
        - name: pyhelper
          image: **********
          imagePullPolicy: Always
          ports:
            - containerPort: 8087
---
kind: ClusterRoleBinding
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: k8s-101-role
subjects:
  - kind: ServiceAccount
    name: k8s-101-role
    namespace: ind-iv
roleRef:
  kind: ClusterRole
  name: cluster-admin
  apiGroup: rbac.authorization.k8s.io
---
apiVersion: v1
kind: ServiceAccount
metadata:
  name: k8s-101-role

容器启动时 returns kubernetes_service.py 文件中 config.load_kube_config() 行的错误 kubernetes.config.config_exception.ConfigException: Invalid kube-config file. No configuration found。我通过 运行ning 命令 kubectl config view 检查了配置文件,该文件确实是空的。我在这里做错了什么? 空配置文件:

apiVersion: v1
clusters: null
contexts: null
current-context: ""
kind: Config
preferences: {}
users: null

还尝试 运行 容器 shell 中的命令 kubectl get pods 并成功返回了 pods。

我相信您会想要 kubernetes.config.load_config,它与您当前使用的 load_kube_config 不同,因为包级别的会像您预期的那样查找任何 $HOME/.kube/config,但是然后 回退到集群内配置,如 ServiceAccount 用法预期

from kubernetes.config import load_config

class KubernetesService:
    def __init__(self):
        super().__init__()
        load_config()