githubcontinuous-integrationdevopsgithub-actionscd

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?


Solution

  • 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.