How to set workflow env variables depending on branch

后端 未结 2 822
天涯浪人
天涯浪人 2021-01-06 02:31

I currently have two GitHub actions workflow files that are pretty much identical, only one is configured to react to push/pull_requests on branch master the ot

相关标签:
2条回答
  • 2021-01-06 03:00

    It is not possible to set workflow-level environment variables from a job. Each job runs in its own machine and setting an env variable there only affects all of the later steps in that job.

    There are currently two ways to share data between jobs; either you create an artifact and use that, or you declare and set job outputs. The latter works for string values.

    Here's an example:

    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}}"
           
    
    0 讨论(0)
  • 2021-01-06 03:05

    You can drop the global env statement, combine the event triggers to

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

    and then add a first step that checks which branch the workflow is running on and set the environment there:

          - 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
    
    0 讨论(0)
提交回复
热议问题