如何根据分支设置工作流环境变量

Thi*_*man 7 github environment-variables github-actions

我目前有两个几乎相同的 GitHub 操作工作流文件,只有一个配置为对分支上master的push/pull_requests 做出反应,另一个配置为production.

登台工作流程如下所示:

env:
  GCLOUD_PROJECT: my-project-stg
  VERCEL_TARGET: staging

on:
  push:
    branches: [ master ]
  pull_request:
    branches: [ master ]
Run Code Online (Sandbox Code Playgroud)

生产工作流程开始如下:

env:
  GCLOUD_PROJECT: my-project-prd
  VERCEL_TARGET: production

on:
  push:
    branches: [ production ]
  pull_request:
    branches: [ production ]
Run Code Online (Sandbox Code Playgroud)

其余的工作流文件是相同的,所以这显然不是很 DRY。

我想有 1 个单一的工作流文件,并以某种方式根据分支名称在两组变量之间切换。有没有办法实现这一点,或者我可能从错误的角度来解决这个问题?

如果可以在共享基本定义上扩展两个工作流文件,我猜也可以解决这个问题。

Thi*_*man 10

无法从作业设置工作流级别的环境变量。每个作业都在自己的机器上运行,并且在那里设置一个 env 变量只会影响该作业中的所有后续步骤。

目前有两种方式可以在作业之间共享数据;要么创建工件并使用它,要么声明并设置作业输出。后者适用于字符串值。

下面是一个例子:

name: "Main"

on:
  push:
    branches:
      - master
      - production
  pull_request:
    branches:
      - master
      - production

jobs:
  init:
    runs-on: ubuntu-latest
    outputs:
      gcloud_project: ${{ steps.setvars.outputs.gcloud_project }}
      phase: ${{ steps.setvars.outputs.phase }}

    steps:
      - name: Cancel previous workflow
        uses: styfle/cancel-workflow-action@0.4.0
        with:
          access_token: ${{ github.token }}

      - name: Set variables
        id: setvars
        run: |
          if [[ "${{github.base_ref}}" == "master" || "${{github.ref}}" == "refs/heads/master" ]]; then
            echo "::set-output name=gcloud_project::my-project-dev"
            echo "::set-output name=phase::staging"
          fi

          if [[ "${{github.base_ref}}" == "production" || "${{github.ref}}" == "refs/heads/production" ]]; then
            echo "::set-output name=gcloud_project::my-project-prd"
            echo "::set-output name=phase::production"
          fi

  print:
    runs-on: ubuntu-latest
    needs: init
    steps:
      - name: Print
        run: echo "gcloud_project=${{needs.init.outputs.gcloud_project}}"
       
Run Code Online (Sandbox Code Playgroud)


Ben*_* W. 6

您可以删除全局env语句,将事件触发器组合到

on:
  push:
    branches:
      - master
      - production
  pull_request:
    branches:
      - master
      - production
Run Code Online (Sandbox Code Playgroud)

然后添加第一步,检查工作流在哪个分支上运行并在那里设置环境:

      - name: Set environment for branch
        run: |
          if [[ $GITHUB_REF == 'refs/heads/master' ]]; then
              echo "GLCOUD_PROJECT=my-project-stg" >> "$GITHUB_ENV"
              echo "VERCEL_TARGET=staging" >> "$GITHUB_ENV"
          else
              echo "GLCOUD_PROJECT=my-project-prd" >> "$GITHUB_ENV"
              echo "VERCEL_TARGET=production" >> "$GITHUB_ENV"
          fi
Run Code Online (Sandbox Code Playgroud)

  • 好的!我完全忽略了工作流程命令部分。惊人的 (2认同)