Reducing duplication for steps that run for PRs and master

I have a pretty common workflow.

I want to run some tests for each pull request and after the merge to master I run the tests again and then deploy an artifact, in my instance a docker container.

So far I have managed to only achieve this by creating two workflow files, one for the master branch, one for the PRs.

If you check the files, you can see that the test step is completely identical.

How can I achieve the same thing without having multiple copies of the test step?

Can I add references to a common step from both files? Is there another way I haven’t considered?

Hi @leonardehrenfried,

Glad to see you in Github Community Forum!
Add references to a common step from both files is not supported. The two workflows are different, based on your yaml code, it will:

  1. Trigger pull request workflow and test when create a PR to master branch.
  2. Besides the merge from PR, any commits in master branch will trigger the tests and then deploy an artifact.

If this is your expectation, you have to copy the test step into two yaml files, since test could be failed in the pull request workflow which will block the merge, and you need to execute test for the direct commit in master branch as well.

Thanks.

Would it be an option for you to remove the branch restrictions on the workflows, and instead check on the docker job (using if: either on the job or relevant steps) if you’re running on master, and skip if not?

This was exactly the sort of trick that i’m looking for. Can you give an example of what the syntax looks like?

Is it perhaps:

if: ${{ github.ref == "master" }}

?

1 Like

I think so, but I haven’t tried it myself. But as I understand the documentation adding that to the job should work. I’d recommend trying with a test job on a test branch (and a second test branch that shouldn’t run that job).

I figured it out. The correct syntax is:

if: ${{ github.ref == 'refs/heads/master' }}

Here is a complete example: https://github.com/stadtnavi/hsl-map-server/blob/6aadfc70df0f60ae4f68980ca546af788c6fb37c/.github/workflows/docker.yml

1 Like

Nice, thank you for sharing the working code!

2 Likes