在基于 Python 的应用程序中从 Kubernetes 读取机密

Reading secrets from Kubernetes within Python based app

我正在打包一个 Python 应用程序以便在 Kubernetes 集群中使用。在代码库中存在此方法:

   def get_pymongo_client(self):
        username = test;
        password = 'test';
        url = ‘test
        conn_str = "mongodb+srv://" + username + ":" + password + “/”+ url

        return pymongo.MongoClient(conn_str)

我正在尝试保护用户名、密码和 URL 字段,以便它们在 src 代码中不可见。为此,我打算使用秘密。

URL https://kubernetes.io/docs/tasks/configmap-secret/managing-secret-using-kubectl/ 详细说明了如何创建机密。但我不确定如何从 Python 应用程序中读取秘密。

.我的应用程序的 Dockerfile:

#https://docs.docker.com/language/python/build-images/

FROM python:3.8-slim-buster

WORKDIR /app

COPY requirements.txt requirements.txt

RUN pip3 install -r requirements.txt

COPY . .

CMD [ "python3", "-m" , "flask", "run", "--host=0.0.0.0"]

阅读 Python flask application access to docker secrets in a swarm 详细介绍了 docker-compose 文件中秘密的使用,这对 Kubernetes 也是必需的吗?从 Python src 代码文件中读取秘密参数涉及哪些步骤?

传统方式是通过环境变量

spec:
  containers:
  - name: your-app
    # ...
    env:
    - name: PYMONGO_USERNAME
      valueFrom:
        secretKeyRef:
           name: your-secret-name-here
           key: PYMONGO_USERNAME

或者您可以使用格式正确的 Secret 和 "envFrom:" field

kind: Secret
metadata:
  name: pymongo
stringData:
  PYMONGO_USERNAME: test
  PYMONGO_PASSWORD: sekrit
---
spec:
  containers:
  - name: your-app
    envFrom:
    - secretRef:
        name: pymongo
    # and now the pod has all environment variables matching the keys in the Secret

然后您的代码将正常从其环境中读取它

   def get_pymongo_client(self):
        username = os.getenv('PYMONGO_USERNAME')
        password = os.getenv('PYMONGO_PASSWORD')
        # etc

另一种但类似的想法是 mount the Secret onto the filesystem,然后像读取文件一样读入值

spec:
  containers:
  - name: your-app
    env:
    # this part is 100% optional, but allows for easier local development
    - name: SECRETS_PATH
      value: /secrets
    volumeMounts:
    - name: pymongo
      mountPath: /secrets 
  volumes:
  - name: pymongo
    secret:
      secretName: your-secret-name-here

然后:

   def get_pymongo_client(self):
        sec_path = os.getenv('SECRETS_PATH', './secrets')
        with open(os.path.join(sec_path, 'PYMONGO_USERNAME')) as fh:
            username = fh.read()

如果可能,使用pydantic

Pydantic 设置支持 docker 秘密,k8s 秘密的工作方式相同。 https://pydantic-docs.helpmanual.io/usage/settings/#use-case-docker-secrets

来自文档的示例:

from pydantic import BaseSettings

class Settings(BaseSettings):
    my_secret_data: str

    class Config:
        secrets_dir = '/run/secrets'

如果你有超过 1 个 k8s 秘密容器,pydantic 设置也从环境变量中读取,但似乎只支持 1 个秘密文件夹。