GitHub Actions中能否共享或复用作业步骤?
问题解答
你说的没错,用一个前置作业让foo和bar直接复用其运行环境的方式不可行。因为GitHub Actions中每个作业都运行在完全独立的虚拟机/容器里,作业间的环境是隔离的,没法共享已经完成的Checkout、Go环境配置这类状态——就算单独做一个完成这些步骤的作业,foo和bar也没法直接调用它的运行环境,只能通过上传/下载工件(artifact)共享文件类资源,已安装的依赖、环境变量这类没法直接传递。
不过完全可以提取重复步骤,避免重复编写,下面是两种常用方案:
方案一:用YAML锚点复用步骤
这是最简单的方案,无需额外文件,直接在当前工作流里定义可复用的步骤锚点:
name: My workflow on: pull_request # 定义可复用的步骤锚点 _shared_steps: &shared_steps - name: Checkout repository uses: actions/checkout@v3 with: fetch-depth: 0 - name: Setup Go uses: actions/setup-go@v3 with: go-version: 1.19 jobs: foo: runs-on: ubuntu-latest steps: # 引用锚点的重复步骤 - <<: *shared_steps - name: Foo run: echo "foo" bar: runs-on: ubuntu-latest steps: - <<: *shared_steps - name: Bar run: echo "bar"
方案二:创建复合动作(Composite Action)
如果需要在多个工作流里复用这些步骤,可以把它们做成自定义复合动作,存放在仓库的.github/actions/目录下:
- 先创建文件
.github/actions/setup-go-env/action.yml,内容如下:
name: "Setup Go Environment" description: "完成代码检出与Go环境配置" runs: using: "composite" steps: - name: Checkout repository uses: actions/checkout@v3 with: fetch-depth: 0 shell: bash - name: Setup Go uses: actions/setup-go@v3 with: go-version: 1.19 shell: bash
- 然后在主工作流中引用这个动作:
name: My workflow on: pull_request jobs: foo: runs-on: ubuntu-latest steps: - name: 配置Go环境 uses: ./.github/actions/setup-go-env - name: Foo run: echo "foo" bar: runs-on: ubuntu-latest steps: - name: 配置Go环境 uses: ./.github/actions/setup-go-env - name: Bar run: echo "bar"
两种方案都能避免重复编写步骤,同时foo和bar依然保持并行运行的状态。
内容的提问来源于stack exchange,提问作者baitendbidz
相关产品推荐
相关产品推荐

