如何在Python应用中读取挂载的Kubernetes Secret并设为环境变量
读取Kubernetes挂载的Secret文件并设置为环境变量
一、处理单个内容文件(accessKeyId、storageAccount等)
对于文件名即键、文件内容为值的Secret文件,直接读取内容后设置为对应环境变量即可:
import os # Secret挂载路径 SECRET_MOUNT_PATH = "/etc/secrets/azure-bs" def set_single_file_env(file_name): full_path = os.path.join(SECRET_MOUNT_PATH, file_name) if not os.path.exists(full_path): return # 读取文件内容,去除首尾空白字符 with open(full_path, 'r') as f: content = f.read().strip() # 将文件名转换为符合规范的环境变量名(大写、替换特殊字符) env_var_name = file_name.upper().replace('.', '_').replace('-', '_') os.environ[env_var_name] = content # 批量处理单个文件 target_files = ["accessKeyId", "storageAccount", "bucketName", "key.json"] for file in target_files: set_single_file_env(file)
二、解析bucket.properties文件
利用团队提供的property_source解析器解析键值对文件,再将解析结果设置为环境变量:
# 导入团队提供的解析工具 from your_team_package import property_source props_file_path = os.path.join(SECRET_MOUNT_PATH, "bucket.properties") if os.path.exists(props_file_path): # 解析文件得到键值对字典 props_dict = property_source.parse(props_file_path) # 遍历字典设置环境变量 for key, value in props_dict.items(): env_key = key.upper().replace('.', '_').replace('-', '_') os.environ[env_key] = value.strip()
三、验证环境变量
可以通过以下方式验证环境变量是否成功设置:
# 示例:打印部分环境变量 print(os.environ.get("ACCESS_KEY_ID")) print(os.environ.get("STORAGE_ACCOUNT")) # 假设bucket.properties中有bucket_region字段 print(os.environ.get("BUCKET_REGION"))
内容的提问来源于stack exchange,提问作者capedCoder
相关产品推荐
相关产品推荐

