GitHub Actions中Python连接Azure Cosmos DB模拟器SSL验证失败
问题原因分析
- Python证书存储与系统存储分离:Python的Azure SDK依赖的HTTP库(如requests/urllib3)默认使用
certifi库维护的证书池,而非系统信任存储。即使你将模拟器证书安装到系统存储,Python进程仍无法读取到。 - 证书获取或安装时机错误:若你在模拟器容器未完全启动时就拷贝证书,或证书未正确添加到Python可访问的存储路径,都会导致验证失败。
- 容器内证书未正确导出:Cosmos DB模拟器的自签名证书是容器生成的,必须从运行中的容器内拷贝,而非使用外部下载的通用证书。
解决步骤
1. 确保正确获取并安装模拟器证书(GitHub Actions YAML步骤)
# 启动Cosmos DB模拟器容器 - name: Start Cosmos DB Emulator run: | docker run -d --name cosmos-emulator \ -p 8081:8081 -p 10250-10255:10250-10255 \ -e AZURE_COSMOS_EMULATOR_PARTITION_COUNT=1 \ -e AZURE_COSMOS_EMULATOR_ENABLE_DATA_PERSISTENCE=false \ mcr.microsoft.com/cosmosdb/linux/azure-cosmos-emulator:latest # 等待模拟器启动完成(避免提前拷贝证书) - name: Wait for Cosmos Emulator to initialize run: | until curl -k https://localhost:8081/_explorer/emulator.pem > /dev/null 2>&1; do echo "Waiting for Cosmos Emulator ready..." sleep 5 done # 从容器拷贝证书并安装到系统存储 - name: Install Cosmos Emulator Certificate run: | docker cp cosmos-emulator:/usr/local/share/ca-certificates/azure cosmos_cert.crt sudo cp cosmos_cert.crt /usr/local/share/ca-certificates/ sudo update-ca-certificates
2. 让Python读取到证书(二选一即可)
方法一:通过环境变量指定证书路径
在运行测试脚本前添加环境变量配置:
- name: Configure Python CA Cert Path run: | # 指向系统合并后的证书文件 export REQUESTS_CA_BUNDLE=/etc/ssl/certs/ca-certificates.crt # 或直接指向拷贝的单个证书文件 # export REQUESTS_CA_BUNDLE=./cosmos_cert.crt
方法二:将证书添加到Python的certifi证书池
- name: Add Cert to Python's Certifi Store run: | cat cosmos_cert.crt >> $(python -c "import certifi; print(certifi.where())")
方法三:测试环境临时禁用SSL验证(仅限单元测试,生产环境禁止)
在初始化CosmosClient时添加connection_verify=False参数:
from azure.cosmos import CosmosClient # 初始化客户端时关闭SSL验证 client = CosmosClient( endpoint="https://localhost:8081/", key="<your-emulator-key>", connection_verify=False )
3. 验证证书生效
运行测试前可先执行curl命令确认证书可用:
curl --cacert cosmos_cert.crt https://localhost:8081/
内容的提问来源于stack exchange,提问作者Mart
相关产品推荐
相关产品推荐

