github-actionscode-duplication

In a GitHub Action, can I extract a recurring variable or condition?


I have a GitHub Action. In it I have several steps that should only be executed under certain conditions - in this case, these steps should be executed if the branch name matches a certain pattern. Like this:

- name: Deploy infrastructure
  if: github.ref == 'refs/heads/master' || startsWith(github.ref, 'refs/heads/features/lrd')

This if block recurs several times in my Action. Is it possible to extract it to a shared variable, condition or function so I can get rid of the ugly code duplication? What would be the nicest way to do this?

I suppose that one option would be to compute the variable in an earlier step and reference it in the later steps, as explained in this post: https://stackoverflow.com/a/58676568/4290962

It just seems a bit ugly to have a separate step to compute this value. Is it the best we can do? Or is there a nicer option?

Thanks in advance!


Solution

  • You could you use an environment variable at the workflow level, something like:

    on:
      push:
    
    env:
      BRANCH: ${{ github.ref == 'refs/heads/main' || startsWith(github.ref, 'refs/heads/features/lrd') }}
    
    jobs:
      job1:
        runs-on: ubuntu-latest
        steps:
          - name: Check branch and print it
            if: ${{ env.BRANCH == 'true' }} # using directly {{ env.BRANCH }} might work as well
            run: echo ${{ env.BRANCH }}
    

    Then, this variable could be used in any job step. I tested it here if you want to have a look:

    Note that you can't use the condition if: ${{ env.BRANCH }} at the job level, it's not supported yet. There is a reference in this post on the Github community from Github Partner brightran about this specific point:

    About the env context, you can only use it in the following scenarios:

    • the value of the with key;
    • the value of the step’s name key;
    • the value of the step’s env key;
    • in a step’s if conditional;
    • in the command lines of a run step.