Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I run some jobs conditionally in github workflow, e.g only on specific trigger?

I have workflow with Build and Publish jobs.

I would like to run Build job on push and pullrequest triggers, but Publish only on push. Is it possible?

like image 543
Liero Avatar asked Oct 20 '25 22:10

Liero


2 Answers

Yes it's possible:

on: [push, pull_request]

jobs:
  Build:
    runs-on: ubuntu-latest
    steps:
      [...]

  Publish:
    runs-on: ubuntu-latest
    if: ${{ github.event_name == 'push' }}
    steps:
      [...]

The worflow will run on both push and pull_request events. Since the Build job doesn't have any if statement or dependencies it will always run. Publish on the other hand will only run if the event that triggered the worflow is a push.

I am guessing here, but if both jobs have to run sequentially, one after the other, you should use this form instead:

on: [push, pull_request]

jobs:
  build_and_push:
    runs-on: ubuntu-latest
    steps:
      - name: Build
        run: [...]

      - name: Publish
        if: ${{ github.event_name == 'push' }}
        run: [...]

Jobs are running independently on different machines. You will need special actions to pass files around. By using steps in a same job, you ensure that both steps run sequentially and that files created by the first step are available to the second.

like image 67
ITChap Avatar answered Oct 23 '25 16:10

ITChap


Yes, there are separate push and pull_request events for the on: directive that will trigger a workflow run.

So, your build.yml workflow would have

on:
  push:
  pull_request:

which would trigger it on push and pull requests.

Your publish.yml workflow would have

on:
  push:
    branches
      - master

which would trigger only on push.

You can read more about trigger setup here.

like image 26
jidicula Avatar answered Oct 23 '25 16:10

jidicula



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!