使用Jenkins/Newman/Postman做CI/CD时,如何安全保护Client ID/Client Secret?
解决Postman+Newman+Jenkins CI/CD中凭据隐藏的问题
核心原因说明
Postman的Initial Value会同步到云端(若使用Postman Cloud)或在导出集合时被包含,而Current Value仅在本地生效。Newman运行时默认优先读取集合中的Initial Value,未设置则会报错,这就是必须填写该字段的原因。直接填入敏感信息存在泄露风险,以下是几种安全可行的解决方案:
方案1:Jenkins凭据管理+Newman命令行传参
- 在Jenkins中添加全局凭据:进入「凭据」→「系统」→「全局凭据」,添加「用户名和密码」类型凭据,用户名填Client ID,密码填Client Secret。
- 在Jenkins任务中引用凭据并通过命令行传递变量:
- Pipeline脚本示例:
pipeline { agent any environment { CLIENT_ID = credentials('your-client-id-credential-id') CLIENT_SECRET = credentials('your-client-secret-credential-id') } stages { stage('Run Newman Tests') { steps { sh 'newman run your-collection.json --env-var CLIENT_ID=$CLIENT_ID --env-var CLIENT_SECRET=$CLIENT_SECRET' } } } } - Freestyle任务:在「构建环境」勾选「使用秘密文本或文件」,添加对应凭据并设置环境变量名,构建步骤执行Shell命令:
newman run your-collection.json --env-var CLIENT_ID=$CLIENT_ID --env-var CLIENT_SECRET=$CLIENT_SECRET
- Pipeline脚本示例:
- Postman集合中仅定义变量名(如
CLIENT_ID、CLIENT_SECRET),无需填写Initial Value或Current Value,Newman运行时会用命令行传入的值覆盖。
方案2:Postman环境文件+Jenkins动态替换
- 创建本地Postman环境变量文件(如
env.json),内容如下(不填敏感值):{ "name": "CI/CD Env", "values": [ { "key": "CLIENT_ID", "value": "", "type": "default", "enabled": true }, { "key": "CLIENT_SECRET", "value": "", "type": "secret", "enabled": true } ] } - 在Jenkins中用凭据管理存储敏感值,构建时动态替换环境文件中的空值:
sed -i "s/\"CLIENT_ID\", \"value\": \"\"/\"CLIENT_ID\", \"value\": \"$CLIENT_ID\"/" env.json sed -i "s/\"CLIENT_SECRET\", \"value\": \"\"/\"CLIENT_SECRET\", \"value\": \"$CLIENT_SECRET\"/" env.json - 运行Newman:
newman run your-collection.json -e env.json - 注意:不要将
env.json提交到代码仓库,仅在Jenkins构建环境中生成或修改。
方案3:Postman API动态更新环境变量(团队协作场景)
- 在Postman Cloud中创建环境,仅定义变量名,不填
Initial Value。 - 用Postman API在Jenkins构建前动态更新环境变量值(Postman API Key需存储在Jenkins凭据中):
POSTMAN_API_KEY=$POSTMAN_API_KEY ENV_ID="your-environment-id" curl -X PUT "https://api.getpostman.com/environments/$ENV_ID" \ -H "X-Api-Key: $POSTMAN_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "environment": { "name": "CI/CD Env", "values": [ { "key": "CLIENT_ID", "value": "'"$CLIENT_ID"'", "type": "default", "enabled": true }, { "key": "CLIENT_SECRET", "value": "'"$CLIENT_SECRET"'", "type": "secret", "enabled": true } ] } }' - 运行Newman时指定该环境:
newman run your-collection.json -e "CI/CD Env" - 注意:Postman API Key需具备环境编辑权限,且妥善保管在Jenkins凭据中。
关键注意事项
- 切勿将包含敏感凭据的Postman集合或环境文件提交到代码仓库,添加到
.gitignore中。 - Jenkins中的凭据需设置为「保密」类型,避免日志泄露。
- Newman运行时,尽量避免使用
--export-env或--export-collection参数,防止敏感值写入文件。
内容的提问来源于stack exchange,提问作者Davidson
相关产品推荐
相关产品推荐

