Search code examples
githubcontinuous-integrationgithub-actions

Variable define on environment in GitHub seems not readable by actions


I define environment in my GitHub repository, in Development environment I define variable ENVIRONMENT_STAGE = dev.

In my GitHub action I want to get this env var (https://docs.github.com/en/actions/learn-github-actions/contexts#vars-context) and it's doesn't work :

name: Deploy environment for PR

on:
  push:
    branches: [ development ]

jobs:
  test-env-var:
    runs-on: ubuntu-latest
    steps:
      - name: Show env var
        run: |
          echo "${{env.ENVIRONMENT_STAGE}}"

Result is :

Run echo ""
  echo ""
  shell: /usr/bin/bash -e {0}

How can I get environment variables in GitHub Actions?


Solution

  • You need to make a few changes:

    1. Add the environment: dev to the job to have it include the variables defined in the environment on GitHub.
    2. Reference the variable using the vars. scope.
    3. Pass the variable into the environment block of the step
    4. Reference the variable using a standard environment variable in bash.

    Step 3 and 4 are optional, but highly recommended from a security standpoint.

    name: Deploy environnement for PR
    
    on:
      push:
        branches: [ development ]
    
    jobs:
      test-env-var:
        runs-on: ubuntu-latest
        environment: dev                 
        # ^
        # Add the environment to your job
    
        steps:
          - name: SHow env var
            run: |
              echo $ENVIRONMENT_STAGE    
            # ^ 
            # Reference by environment variable for added security
            
    
            env:
              ENVIRONMENT_STAGE = ${{ vars.ENVIRONMENT_STAGE }}
              # ^                        # ^
              # Pass the Github          # Reference the GitHub Environment's
              # environment variable     # variable using the vars 
              # to the step's            # context
              # environment