Conditionally set an environment variable

I’d hoped this was trivial but it seems not.

Consider this:

    env:
       GH_PKG_USER:  ${USER}
       GH_PKG_TOKEN: ${{ format('{0}{1}', secrets.PACKAGE_RESTORE_SECRET, secrets.GITHUB_TOKEN) }}
       ACTIONS_ALLOW_UNSECURE_COMMANDS: true
    steps:
    - uses: actions/checkout@v1
      name: Checkout Code

I want to change this to something like this:


    env:
       GH_PKG_USER:  ${USER}
       if: secrets.PACKAGE_RESTORE_SECRET exists then
          GH_PKG_TOKEN: ${{ secrets.PACKAGE_RESTORE_SECRET }}
       else:
          GH_PKG_TOKEN: ${{ secrets.GITHUB_TOKEN }}
       ACTIONS_ALLOW_UNSECURE_COMMANDS: true
    steps:
    - uses: actions/checkout@v1
      name: Checkout Code

I’ve had a lot of trouble trying to find out if this is even possible let alone pin down the exact syntax.

Any help is greatly appreciated.

There are no conditionals in the env section. The closest you can do is a step where you compute the value you want (e.g. check if a secret value is non-empty) and write the result to GITHUB_ENV to set the environment variable for the steps after.

Hi,

I did just stumble upon this as a solution and it seems to work:

GHUB_PACKAGES_TOKEN: ${{ secrets.GHUB_PACKAGES_TOKEN == '' && secrets.GITHUB_TOKEN || secrets.GHUB_PACKAGES_TOKEN }}

When run in the context of a fork the secret exists and is used, but when executing in the context of the main repo the secret does not exist and so the GITHUB_TOKEN gets used!

The syntax is quite alien to me but seems to represent a crude “ternary” capability, I found it on the web.

This allows us to generate builds whenever a developer pushes to branches on their fork as well as the more traditional case of when pull requests are created.

Being able to do it for pushes to forks is a great help in cases where the repo is private and the team all use forks to store their work, they get helpful feedback from GitHub before they even get to the pull request stage.

1 Like