Search code examples
github-actionsenvironment

Github workflow does not read variables from environments


Following is my simple github workflow. It is intended to print an environment variable.

name: verify

on:
  workflow_dispatch:

jobs:
  read_env_variables:
    environment: build 
    runs-on: [ self-hosted, onprem_dae, docker ]
    steps:
      - name: cat on branch file
        run: |
          echo ${{ env.SOME_VARIABLE }}

I have created an environment named "build". In this environment, I have an environment variable named SOME_VARIABLE set to xyz.

When the workflow is triggered, I expected to echo value xyz but actual value is "". Is there something missing?


Solution

  • Your issue here is related to the syntax.

    To use the ${{ env.SOME_VARIABLE }} syntax, you need to set an env variable at the workflow, job or step level.

    Here is an example:

    name: Environment Workflow
    
    on:
      workflow_dispatch:
    
    env:
      WORKFLOW_VARIABLE: WORKFLOW
    
    jobs:
    
      job1:
        runs-on: ubuntu-latest
        env:
          JOB_VARIABLE: JOB
        steps:
          - name: Run Commands with various variables
            if: ${{ env.WORKFLOW_VARIABLE == 'WORKFLOW' }}
            env:
              STEP_VARIABLE: STEP
            run: |
              echo "Hello World"
              echo "This is the $WORKFLOW_VARIABLE environment variable"
              echo "This is the $JOB_VARIABLE environment variable"
              echo "This is the $STEP_VARIABLE environment variable"
    

    Now, if you want to use the environment secrets for deployment, as explained here on the Github Documentation, the syntax would be different using the job_id.environment as you are already using following this doc.

    Here is an example:

      job4:
        runs-on: ubuntu-latest
        environment: build
        steps:
          - name: Show repo env secret
            run: |
              echo ${{ secrets.REPO_ENV_SECRET }}
    

    Note that this variable is a secret, therefore you won't be able to see it through an echo command on the step (it will show ***)


    Here is the workflow I used to validate all this implementation if you want to take a look: