我们都知道在编写github actions时,可以使用其他预定义好的github action,类似如下写法.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 # .github/workflows/flow1.yml on: workflow_call: inputs: source_branch: description: 'source code branch' required: true default: 'main' type: string push: branches: [ "main" ] # ... jobs: fetch: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 with: ref: ${{ github.ref }} # ...
那么当我们写好了这样一个workflow之后,能否进一步在多个workflow中复用这个文件呢,实际上是可以的。
首先比编辑.github/workflows/flow1.yml
,增加workflow_call
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 on: workflow_call: inputs: param1: required: true type: string push: branches: [ "main" ] # ... jobs: job1: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 with: ref: ${{ github.ref }} # ...
之后在另一个workflow中就可以这样调用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 # .github/workflows/flow2.yml # ... jobs: job1: steps: uses: actions/checkout@v4 # can do smthing else job2: needs: [job1] uses: ./.github/workflows/flow1.yml # uses: <user_name>/<repo>/workflows/flow1.yml@<branch/commit> with: ref: ${{ github.ref }} runs-on: ubuntu-latest # ...
这种用法有以下几点需要注意:
./.github/workflows/flow1.yml
只能作为一个job使用,而不能作为step使用,否则会得倒类似 Can't find 'action.yml' or 'Dockerfile' under xxxx Did you forget to run actions/checkout before running your local action
uses
字段必须紧接着job2
声明,否则会报错The workflow is not valid
执行job2之前,必须先执行job1,将项目代码clone到当前目录,并设置job2和job1的依赖关系,否则找不到目标文件
调用本地文件时uses
的值必须为./.github/...
,而不能是.github/...