Search code examples
github-actions

Reference to Environment Variables in GitHub actions in the same step


I have a job which needs to refer to the environment variable set in the command in the same step prior to be set. GitHub Actions sets the variable correctly but does not refer to it in the same step, leaving me with an empty value.

jobs:
  test-commands:
    runs-on: ubuntu-latest
    steps:
      - run: |
          echo "image=2.1" >> $GITHUB_ENV
          echo "image_ref=$image" >> $GITHUB_ENV
          echo "image_ref_2=${{env.image}}" >> $GITHUB_ENV
      - run: echo ${{env.image}} ${{env.image_ref}} ${{env.image_ref_2}}

This is a sample job of what I am trying to accomplish, as shown neither of the methods work , with only the image variable being printed properly in the 2nd step, and the other variables being set as null.

I was not able to find any reference in the docs which mentioned that variables can be referred in the next step only.

Any suggestions to set this properly are most welcome. Thanks in advance!


Solution

  • From the documentation:

    You can make an environment variable available to any subsequent steps in a workflow job by defining or updating the environment variable and writing this to the GITHUB_ENV environment file. The step that creates or updates the environment variable does not have access to the new value, but all subsequent steps in a job will have access. The names of environment variables are case-sensitive, and you can include punctuation. For more information, see "Environment variables."

    So in your case, you can write your result to a bash variable that you can use in your step, then you export that same variable to GITHUB_ENV.

    Example:

    steps:
      - run: |
          IMAGE=2.1
          echo "image=${IMAGE}" >> $GITHUB_ENV
          echo "image_ref=${IMAGE}" >> $GITHUB_ENV
      - run: echo ${{env.image}} ${{env.image_ref}}
    

    Run:

    Github Action example