如何将GitHub Secrets传入Newman运行的Postman集合与环境?
解决Postman Newman在GitHub Action中传入Secrets的问题
问题描述
我把带有硬编码ApiKey的Postman环境变量文件Test-env.postman_environment.json推到了GitHub Action里,为了避免风险,已经把ApiKey存成了GitHub Secrets(名称是test),但不知道怎么在Newman运行集合和环境时传入这个密钥,保证API请求正常。我是Postman和GitHub新手,求指导。
原环境变量文件
{ "key": "ApiKey", "value": "abcdefg", "type": "secret", "enabled": true }
API请求头配置
{ "key": "Api-Key", "value": "{{ApiKey}}" }
原GitHub Action YAML
name: Test secrets on: push: workflow_dispatch: jobs: Test-api: runs-on: ubuntu-latest steps: # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it - uses: actions/checkout@v2 # Install Node on the runner - name: Install Node uses: actions/setup-node@v3 with: node-version: "20.x" # Install the newman command line utility and also install the html extra reporter - name: Install newman run: | npm install -g newman npm install -g newman-reporter-htmlextra # Run the POSTMAN collection - name: Run POSTMAN collection run: | run: | newman run "Testapi.postman_collection.json" -e "Test-env.postman_environment.json" -r cli,htmlextra --reporter-htmlextra-showEnvironmentData --reporter-htmlextra-export Reports/reports.html # Upload the contents of Test Results directory to workspace - name: Output the run Details uses: actions/upload-artifact@v4 if: success() || failure() with: name: Report - Test path: Reports/Terstreports.html retention-days: 20
解决方案
1. 清理环境变量文件的硬编码值
把Test-env.postman_environment.json里的value字段留空,Newman会优先读取传入的变量值,修改后内容:
{ "key": "ApiKey", "value": "", "type": "secret", "enabled": true }
2. 在Newman命令中传入GitHub Secrets
Newman支持用--env-var参数直接覆盖环境变量,在GitHub Action里通过${{ secrets.test }}引用你存储的密钥。
3. 修正GitHub Action YAML的错误
原YAML存在两处问题:
Run POSTMAN collection步骤重复了run: |,导致命令无法执行- 上传报告的路径与Newman导出路径不一致,无法正确上传
修改后的完整YAML:
name: Test secrets on: push: workflow_dispatch: jobs: Test-api: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Install Node uses: actions/setup-node@v3 with: node-version: "20.x" - name: Install newman run: | npm install -g newman npm install -g newman-reporter-htmlextra - name: Run POSTMAN collection run: | newman run "Testapi.postman_collection.json" \ -e "Test-env.postman_environment.json" \ --env-var "ApiKey=${{ secrets.test }}" \ -r cli,htmlextra \ --reporter-htmlextra-showEnvironmentData \ --reporter-htmlextra-export Reports/reports.html - name: Output the run Details uses: actions/upload-artifact@v4 if: success() || failure() with: name: Report - Test path: Reports/reports.html retention-days: 20
关键说明
--env-var "ApiKey=${{ secrets.test }}":将GitHub Secrets中名为test的密钥值赋值给Postman环境变量ApiKey- 环境变量的
type: secret会确保该值不会在Newman运行日志中明文显示 - 修正后的YAML移除了冗余代码,统一了报告路径,确保流程能正常执行
内容的提问来源于stack exchange,提问作者rbi test
相关产品推荐
相关产品推荐

