Github 工作流程:如何有条件地为所有后续作业设置 ENV?

Sca*_*ast 15 github-actions

在工作流程开始时,我想有条件地设置一些 ENV 变量的值。这些价值观应该是全球性的,适用于所有工作和步骤。以下代码在结构上无效,但它\xe2\x80\x99s是我\xe2\x80\x99m试图完成的任务

\n
if: github.ref_name == "target branch"  (for example)\n  env:\n    var1: 'Right Branch'\n\nif: github.ref_name != "target branch" \n  env:\n    var1: 'Wrong Branch'\n\njobs:\n  ...\n
Run Code Online (Sandbox Code Playgroud)\n

Gui*_*urd 12

Github Actions 似乎没有原生的东西来实现你想要的。

\n

作为一种解决方法,您可以使用outputs一个作业来完成此操作,该setup作业将用作后续作业的“所需”作业,您可以在其中设置所需的变量。

\n

以下是在同一作业或后续作业中使用输出的示例:

\n
jobs:\n  setup-job:\n    runs-on: ubuntu-latest\n    outputs:\n      var1: ${{ steps.set-variable.outputs.test }}\n    steps:\n      - uses: actions/checkout@v2\n      - name: Set test variable\n        id: set-variable\n        run: |\n          if [ ${{ github.ref }} != \'refs/heads/main\' ]; then\n            echo "IS NOT main branch"\n            echo "::set-output name=test::abc"\n          else\n            echo "IS main branch"\n            echo "::set-output name=test::123"\n          fi\n        shell: bash\n      - name: Read exported variable\n        run: |\n          echo "OUTPUT: ${{ steps.check.test-env.test }}"\n\n  subsequent-job:\n    runs-on: ubuntu-latest\n    needs: [setup-job]\n    steps:\n      - uses: actions/checkout@v2\n      - name: Read exported variable\n        run: |\n          echo "OUTPUT: ${{needs.setup-job.outputs.var1}}"\n
Run Code Online (Sandbox Code Playgroud)\n

注意:我无法使用$GITHUB_ENV variable(做类似的事情echo "test=abc" >> $GITHUB_ENV)来做到这一点,因为它不在作业之间共享。

\n\n
\n

10/22 更新:警告:该set-output命令已弃用,并将很快被禁用。请升级为使用环境文件。有关更多信息,请参阅:github.blog/changelog/\xe2\ x80\xa6

\n

现在,要设置环境变量,您需要使用以下语法

\n
echo "{environment_variable_name}={value}" >> $GITHUB_ENV\n
Run Code Online (Sandbox Code Playgroud)\n

  • 10/22 更新:`警告:`set-output` 命令已弃用,并将很快被禁用。请升级为使用环境文件。有关更多信息,请参阅:https://github.blog/changelog/2022-10-11-github-actions-deprecating-save-state-and-set-output-commands/` (2认同)