我编写了一个服务来从 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.py
kubectl config view
apiVersion: v1
clusters: null
contexts: null
current-context: ""
kind: Config
preferences: {}
users: null
还尝试kubectl get pods
在容器的 shell 中运行该命令,并成功返回了 pod。