Use dynamic input value for Environment in GitHub Actions workflow job

Viewed 2140

I'm trying to make a GitHub Actions workflow where one job has a dynamic value to its environment setting. https://docs.github.com/en/actions/reference/environments I have two jobs in this workflow. The first job determines which environment the second job will run in, and this is in turn based on which git branch the Actions job is run from.

This is my naive attempt to make it work, but I get an error which says

(Line: 29, Col: 18): Unrecognized named-value: 'needs'. Located at position 1 within expression: needs.get-environment.outputs.environment_name

name: Environments

on:
  push:
  workflow_dispatch:

jobs:
  get-environment:
    runs-on: ubuntu-latest
    outputs:
      environment_name: ${{ steps.get_environment.outputs.environment_name }}
    steps:
      - id: get_environment
        run: |
          if [ "$GITHUB_REF" = "refs/heads/test" ]
          then
            echo "::set-output name=environment_name::test"
          elif [ "$GITHUB_REF" = "refs/heads/qa" ]
          then
            echo "::set-output name=environment_name::qa"
          elif [ "$GITHUB_REF" = "refs/heads/master" ]
          then
            echo "::set-output name=environment_name::production"
          fi
    
  use-environment:
    runs-on: ubuntu-latest
    needs: [get-environment]
    environment: ${{ needs.get-environment.outputs.environment_name }}
    steps:
      - uses: actions/checkout@v2

      - name: Run a one-line script
        run: echo ${{ secrets.ENV_DEPENDENT_SECRET }}

Is it possible to achieve what I'm trying to do? My end goal is to have a single workflow file for three different app environments (test, QA and prod), where each app environment uses a separate Actions environment. (terminology gets confusing, I know)

2 Answers

I actually had to solve this issue for the place I work. You can use a matrix with the list of your env names and dynamically set the environment name. Take a look at the link for the workflow file.

enter image description here

Have you tried

>   use-environment:
>     runs-on: ubuntu-latest
>     needs: [get-environment]
>     environment: 
>          name: ${{ needs.get-environment.outputs.environment_name }}
Related