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

如何在Github Actions中正确访问Secrets并赋值给环境变量?

解决GitHub Actions中workflow_call访问Secrets为空的问题

核心原因:workflow_call需要显式传递Secrets

当使用workflow_call调用工作流时,Secrets不会自动从调用方传递到被调用方,必须在被调用工作流中声明需要接收的Secrets,同时在调用方工作流中显式传入对应的值。这是Vars和Secrets的关键区别——Vars会默认传递,但Secrets出于安全要求必须显式配置。

步骤1:修改被调用的Run rspec工作流

在你的工作流中,给on.workflow_call添加secrets字段,声明需要接收的GOOGLE_API_KEY:

name: Run rspec

on:
  workflow_call:
    secrets:
      GOOGLE_API_KEY:
        required: true # 若该Secret为必填则设为true,可选则改为false

jobs:
  rspec:
    runs-on: ubuntu-latest
    env:
      GOOGLE_API_KEY: ${{ secrets.GOOGLE_API_KEY }}

    steps:
      - name: Checkout code
        uses: actions/checkout@v3

      - name: Set up Ruby
        uses: ruby/setup-ruby@v1
        with:
          ruby-version: 3.1.3
          bundler-cache: true

      - name: Database create and migrate
        run: |
          cp config/database.yml.ci config/database.yml
          bundle exec rails db:create RAILS_ENV=test
          bundle exec rails db:migrate RAILS_ENV=test

      - name: Create dotenv file
        run: |
          touch .env
          echo GOOGLE_API_KEY = $GOOGLE_API_KEY >> .env

      - name: Run rspec
        run: |
          bundle exec rspec

步骤2:在调用该工作流的父工作流中传入Secrets

假设你在主工作流中调用这个rspec工作流,需要在调用时指定传入的Secrets:

name: Main Workflow

on: [push, pull_request]

jobs:
  trigger-rspec:
    uses: your-username/your-repo/.github/workflows/rspec.yml@main # 替换为你的工作流路径
    secrets:
      GOOGLE_API_KEY: ${{ secrets.GOOGLE_API_KEY }}

其他排查方向

如果上述配置后仍为空,检查以下几点:

  • Secrets名称拼写:确认仓库Secrets中的名称与工作流中使用的GOOGLE_API_KEY完全一致(大小写敏感,无空格或拼写错误)。
  • Secrets权限:若使用组织级Secrets,需确保当前仓库被授权访问该Secret;仓库级Secrets要确认存在于当前仓库的Secrets列表中。
  • 验证Secret是否传递成功:可临时添加一个步骤验证(避免直接打印Secret内容):
    - name: Verify Secret length
      run: echo "Secret length: $(echo $GOOGLE_API_KEY | wc -c)"
    
    若输出长度大于1,说明Secret已成功传递。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 23:05:02