0

I'm trying to set the environment context for a HitHub Actions workflow dynamically based upon the branch. So if the workflow is being fired by a pull request to develop, then the development environment context would be used, but if the pull request is against main then the main environment context would be used.

At the moment I'm using an IF:

name: Deploy
on:
  pull_request:
  types: closed
    branches:
      - develop
      - master

  workflow_dispatch:

jobs:

  deploy-develop:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        node-version: [12.x]
    if: ${{ github.ref == 'refs/heads/develop' }}

    environment: develop

It's the last line of the above that I want to make dynamic. I've tried the below:

environment: ${GITHUB_REF#refs/heads/}

and

environment: ${{ GITHUB_REF#refs/heads/ }}

and

environment: ${{github.event.pull_request.base.ref}}

But all the things I've tried result in:

.github/workflows/deploy.yaml#L23
The workflow is not valid. .github/workflows/deploy.yaml (Line: 23, Col: 18): Unexpected symbol: 'GITHUB_REF#refs/heads/'. Located at position 1 within expression: GITHUB_REF#refs/heads/

or

The workflow is not valid. .github/workflows/deploy.yaml (Line: 22, Col: 18): Unrecognized named-value: 'github'. Located at position 1 within expression: github.event.pull_request.base.ref

Any ideas how to set the context dynamically?

Jim Jimson
  • 2,368
  • 3
  • 17
  • 40

1 Answers1

2

Here is how I'm doing it.

Add this job to your workflow

  ##################
  # Set Deploy Env #
  ##################
  SetDeployEnv:
    name: 'Set Deployment Environment'
    runs-on: [self-hosted, linux]
    env:
      deploy: Test
    outputs:
      deploy_env: ${{ env.deploy }}

    steps:
    steps:
    - name: Determine Environment
      run: |
          if [[ ${{ github.ref }} =~ /^refs\/heads\/sprint+[_|-]+[0-9]*+[_|-]+\S*/gi ]]; then
              echo "deploy=Test" >> $GITHUB_ENV
          elif [[ ${{ github.ref }} =~ /^refs\/heads\/sprint+[_|-]+[0-9]*/gi ]]; then
              echo "deploy=PreProd" >> $GITHUB_ENV
          elif [[ ${{ github.ref }} =~ /^refs\/heads\/main|master/gi ]]; then
             echo "deploy=Prod" >> $GITHUB_ENV
          else
              echo "deploy=Dev" >> $GITHUB_ENV
          fi
          echo "Deploying to ${{ env.deploy }} from branch ${{ GITHUB.REF }}"

Then use something similar for any job that you need to set the environment for.

  ################
  # Test Job     #
  ################
  TestJob:
    needs: SetDeployEnv
    name: 'Test Job'
    runs-on: [self-hosted, linux]
    environment: 
        name: ${{ needs.SetDeployEnv.outputs.deploy_env }}

    steps:
    - name: echo
      run: | 
        echo ${{ needs.SetDeployEnv.outputs.deploy_env }}
Frank The Tank
  • 441
  • 4
  • 6