我正在打包一个Python应用程序以在库伯内特斯集群中使用。在代码库中存在此方法:
def get_pymongo_client(self):
username = test;
password = 'test';
url = ‘test
conn_str = "mongodb+srv://" + username + ":" + password + “/”+ url
return pymongo.MongoClient(conn_str)
我正在尝试保护用户名密码
URLhttps://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烧瓶应用程序在群中访问docker机密详细说明了docker-comort文件中机密的使用,这对库伯内特斯来说也是必需的吗?从Pythonsrc代码文件中读取机密参数涉及哪些步骤?
传统的方法是通过环境变量
spec:
containers:
- name: your-app
# ...
env:
- name: PYMONGO_USERNAME
valueFrom:
secretKeyRef:
name: your-secret-name-here
key: PYMONGO_USERNAME
或者你可以通过使用格式良好的秘密和“envFrom:”字段来减少yaml的闲聊
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
另一种类似的想法是将秘密挂载到文件系统上,然后像读取文件一样读取值
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()