1

我编写了一个服务来从 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中的行返回错误。我通过运行命令检查了配置文件,该文件确实是空的。我在这里做错了什么?空配置文件:config.load_kube_config()kubernetes_service.pykubectl config view

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

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

4

1 回答 1

2

我相信您会想要kubernetes.config.load_configload_kube_config您当前使用的不同,因为包级别$HOME/.kube/config会按照您的预期查找任何内容,但随后ServiceAccount会根据使用情况回退到集群内配置

from kubernetes.config import load_config

class KubernetesService:
    def __init__(self):
        super().__init__()
        load_config()
于 2021-11-15T21:57:57.780 回答