簡體   English   中英

使用 Kubernetes Python 客戶端加載 kubect 配置文件返回錯誤:無效的 kube-config 文件

[英]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

在容器啟動時,它返回錯誤kubernetes.config.config_exception.ConfigException: Invalid kube-config file. No configuration found. kubernetes.config.config_exception.ConfigException: Invalid kube-config file. No configuration found. kubernetes_service.py文件中的config.load_kube_config()行。 我檢查了運行kubectl config view命令的配置文件,該文件確實是空的。 我在這里做錯了什么? 空配置文件:

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

如果我注釋掉kubernetes_service.py文件中的config.load_kube_config()行,容器將不會有任何錯誤。 還嘗試在容器的 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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM