🐺

github actions で job を再利用する

2024/12/15に公開

モチベーション

github actionsで複数のjobを実行する際にjobレベルで重複する箇所が多く見られたため
jobの再利用周りで課題感を感じていた

Reusing workflows

今回はgithub actionsで用意されているworkflow_callで対応

all_image
jobsからworkflow_callで定義されたjobを呼び出す

https://docs.github.com/ja/actions/sharing-automations/reusing-workflows#creating-a-reusable-workflow

再利用可能なワークフローの作成

再利用したいワークフローは、onの値にworkflow_callを含める

on:
  workflow_call:

再利用可能なワークフローの例

name: Reusable workflow example

on:
  workflow_call:
    inputs:
      config-path:
        required: true
        type: string
    secrets:
      token:
        required: true

jobs:
  triage:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/labeler@v4
      with:
        repo-token: ${{ secrets.token }}
        configuration-path: ${{ inputs.config-path }}

呼び出し

呼び出す際には、ワークフロー単位で呼び出す必要があります。

jobs.<job_id>.uses 構文を使うことで呼び出せる

再利用可能なワークフローファイルを参照する場合、次のいずれかの構文で利用できる

パブリックとプライベート リポジトリの再利用可能ワークフローの{owner}/{repo}/.github/workflows/{filename}@{ref}。
同じリポジトリ内の再利用可能なワークフローの ./.github/workflows/{filename}。

jobs:
  call-workflow-in-local-repo:
    uses: ./.github/workflows/workflow-2.yml

呼び出し元の例

name: Call a reusable workflow

on:
  pull_request:
    branches:
      - main

jobs:
  call-workflow:
    uses: octo-org/example-repo/.github/workflows/workflow-A.yml@v1

  call-workflow-passing-data:
    permissions:
      contents: read
      pull-requests: write
    uses: octo-org/example-repo/.github/workflows/workflow-B.yml@main
    with:
      config-path: .github/labeler.yml
    secrets:
      token: ${{ secrets.GITHUB_TOKEN }}

基本的な使い方としては以上

呼び出し側でサポートされているキーワード

https://docs.github.com/ja/actions/sharing-automations/reusing-workflows#supported-keywords-for-jobs-that-call-a-reusable-workflow

inputsを利用した動的対応

ワークフロー自体は共通化したが、Stepによっては動的に変えたいようなケースでは
on.workflow_call.inputを使用することで対応させる

https://docs.github.com/ja/actions/writing-workflows/workflow-syntax-for-github-actions#example-of-onworkflow_callinputs

on:
  workflow_call:
    inputs:
      username:
        description: 'A username passed from the caller workflow'
        default: 'john-doe'
        required: false
        type: string

jobs:
  print-username:
    runs-on: ubuntu-latest

    steps:
      - name: Print the input name to STDOUT
        run: echo The username is ${{ inputs.username }}

呼び出し側の実装

name: Call a reusable workflow

on:
  pull_request:
    branches:
      - main

jobs:
  call-workflow:
    uses: octo-org/example-repo/.github/workflows/workflow-A.yml
    with:
      username: "hoge"

Discussion