Github actions jobs/workflows/repository depend on each other

Posted by Bruce Liu on May 21, 2023 , updated on May 26, 2023

🏷️ Tags: Github , workflow , Github Action

There are different ways to trigger a workflow based on the completion or status of another workflow in GitHub Actions. One method is to use the keyword needs in the same YAML file to specify the dependencies between jobs. Another method is to use the workflow_run event to run a workflow after another workflow has been completed or requested. A third method is to use the repository_dispatch event to send a custom webhook event to a repository and trigger a workflow.

needs method

All-in-one YAML file:

name: test of needs method

on: push

jobs:
  job1:
    runs-on: ubuntu-latest

    steps:
    - uses: actions/checkout@v3
    
    - name: Do something
      run: ...

  job2:
    needs: job1	        # keyword
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v3

      - name: Do something
        run: ...

workflow_run method

YAML file for job1:

name: job1's name

on: push

jobs:
  job1:
    runs-on: ubuntu-latest

    steps:
    - uses: actions/checkout@v3
    
    - name: Do something
      run: ...

YAML file for job2:

name: job2's name

on: 
  workflow_run:
    workflows: ['job1's name']
    types:
      - completed
	  
jobs:
  job2:
    runs-on: ubuntu-latest

    steps:
    - uses: actions/checkout@v3
    
    - name: Do something
      run: ...

repository_dispatch method

YAML file for job1:

name: job1's name

on: push

jobs:
  job1:
    runs-on: ubuntu-latest

    steps:
    - uses: actions/checkout@v3
    
    - name: Do something
      run: ...

    - name: send a POST request to the GitHub API
      run: |
        curl -X POST \
        -H "Accept: application/vnd.github.v3+json" \
        -H "Authorization: token <your token>" \	# $
        --data '{"event_type": "job1-event"}' \
        https://api.github.com/repos/<owner>/<repo>/dispatches		# repository which job2 file is located

YAML file for job2:

name: job2's name

on: 
  repository_dispatch:
    types:['job1-event']
	  
jobs:
  job2:
    runs-on: ubuntu-latest

    steps:
    - uses: actions/checkout@v3
    
    - name: Do something
      run: ...

Of course, you can trigger the job2 from the terminal:

curl -X POST \
-H "Accept: application/vnd.github.v3+json" \
-H "Authorization: token <your token>" \
--data '{"event_type": "job1-event"}' \
https://api.github.com/repos/<owner>/<repo>/dispatches

Or python requests

References


Share on:

« PREVIOUS: 计算机软件著作权登记流程
NEXT: Update home assistant core and os »