You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让GitHub Actions读取.gitignore中的config.json且不泄露密钥?

解决GitHub Actions无法读取.gitignore中config.json的问题

因为仓库是公开的,不能推送包含密钥的config.json,所以可以通过GitHub Secrets存储敏感信息+在Actions流程中动态生成config.json的方式解决,具体步骤如下:

1. 将config.json中的敏感项存入GitHub Secrets

进入你的GitHub仓库,依次操作:

  • 点击「Settings」→「Secrets and variables」→「Actions」
  • 点击「New repository secret」,逐个添加config.json里的敏感字段(比如密钥、私密API地址等)。例如:
    • 把密钥字段命名为SECRET_API_KEY,值填入实际密钥内容
    • 其他私密项同理添加对应的Secret

2. 修改GitHub Actions工作流文件

在你的.github/workflows/xxx.yml中,添加动态生成config.json的步骤,放在「Install dependencies」之后、「Run the app」之前。

方式一:直接通过echo生成文件(适合简单结构的config)

name: Node Integrate

on:
  push:
    branches:
      - main
  pull_request:
    branches:
      - main

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - name: Use Node.js 16.x
        uses: actions/setup-node@v1
        with:
          node-version: 16.x
      - name: Install dependencies
        run: rm -rf node_modules && yarn install --frozen-lockfile
      # 新增步骤:生成config.json
      - name: Generate config.json
        run: |
          echo '{
            "apiKey": "${{ secrets.SECRET_API_KEY }}",
            "baseUrl": "https://your-public-api-url.com" // 公开字段直接填写
          }' > config.json
      - name: Run the app
        run: yarn start

方式二:用模板文件生成(适合结构复杂的config)

  1. 在仓库根目录创建config.template.json(该文件可正常推送到仓库,不含敏感信息),用占位符代替敏感项:
{
  "apiKey": "${SECRET_API_KEY}",
  "baseUrl": "${BASE_URL}",
  "otherPublicConfig": "fixed-public-value"
}
  1. 修改工作流文件,用envsubst替换模板中的占位符生成config.json:
name: Node Integrate

on:
  push:
    branches:
      - main
    pull_request:
      branches:
        - main

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - name: Use Node.js 16.x
        uses: actions/setup-node@v1
        with:
          node-version: 16.x
      - name: Install dependencies
        run: rm -rf node_modules && yarn install --frozen-lockfile
      # 新增步骤:基于模板生成config.json
      - name: Generate config.json
        run: envsubst < config.template.json > config.json
        env:
          SECRET_API_KEY: ${{ secrets.SECRET_API_KEY }}
          BASE_URL: "https://your-public-api-url.com"
      - name: Run the app
        run: yarn start

通过以上操作,GitHub Actions运行时会动态生成包含敏感信息的config.json,既不会把密钥暴露在仓库中,也能让应用正常读取配置。

内容的提问来源于stack exchange,提问作者kattah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 01:25:27