Conditional Setting of Env Variables in GH Actions

Can we use if condition while setting the value of custom environment variables? If yes, please provide some examples. I couldn’t find any documentation on how to achieve this. I am looking for something like below.

env:
if: ${{ runner.os }} == ‘Linux’
MY_VAR: “Some Value”
if: ${{ runner.os }} == ‘Windows’
MY_VAR: “Some Other Value”

You can’t do that at the job or workflow level. You can use conditionals when a step dynamically sets environment variables, either on the step level like this:

steps:
  - name: Set the value
    if: runner.os == 'Linux'
    run: |
        echo "animal=penguin" >> $GITHUB_ENV

Or using shell conditionals within the run block.

Thanks a lot for your prompt response. However, I have a couple of requirements also.

  1. I need to use the below snippet in every workflow. Hence I would prefer to keep it short and probably a way to make it reusable if possible in a custom action(not sure how to achieve it). Since, every developer will have to do it, I (as part of DevOps team) need to ensure every team includes this snippet in their GH workflow. Basically I need a way to enforce this.

  2. Also, the penguin value that you have shown (in the snippet) will be actually retrieved from Secrets in our case. Hence, it will be great if I can use a syntax like ${{ secrets.MY_VARIABLE_${{ runner.os }} }} or an indexing approach for accessing Secrets, something like ${{ secrets[“MY_VARIABLE_${{ runner.os }}”] }}. I saw this indexing approach in this SO article, but not able to get it working.

You can try:

  • set up org secrets,
  • write an action to do your work,
  • create a template repository that has workflow(s) that use the action.

You could probably also have an org project which has a workflow with a schedule that checks the other org projects’ workflows and complains if it finds some that aren’t using the action (bonus point for complaining about the version of the action, since you can use that to recognize when workflows are out of date – you might even be able to have it automate PRs to update the workflows…), but note that it’ll get turned off if the repository doesn’t see pushes periodically, so odds are it’ll be off w/in 6 months.

n.b. I haven’t done something like this. We do have a template repository w/ a workflow or two, and we’re starting to rely on dependabot to track updates for actions (but it’s flaky, e.g. it doesn’t distinguish between unreleased and released versions of actions).