LoginSignup
5
5

More than 3 years have passed since last update.

【GitHub Actions】あるリポジトリへのpushをトリガーに、別のリポジトリのワークフローを開始する方法

Last updated at Posted at 2020-06-28

あるリポジトリへのpushをトリガーに、もう1つの々のリポジトリのGitHub Acionsのワークフローを開始する方法を調査したときのメモです。

環境

  • GitHub Actions: 2020年6月時点のもの
  • GitHub Rest API: v3

やりたいこと

以下の絵のようにリポジトリAにpushされたことを契機にして、リポジトリBのGitHub Actionsのワークフローを実行したいというものです。

構成図-やりたいこと.png

作ったもの

最終的に出来上がった構成は以下のようなものです。

構成図-作ったもの.png

必要な作業は以下になります。

(1)-1: GitHub APIを利用するためのpersonal access tokenの取得

(1)-2: Rest APIでのrepository dispatch eventの作成

(2): repository_dispatchをトリガーにしたワークフローの起動

以下、作業内容の詳細です。

(1)-1 personal access tokenの取得

GitHub Actionsのワークフローの中でGitHub APIを使用するためにはpersonal access tokenの取得が必要となります。

以下のページを参考にして取得します。

GitHub - Creating a personal access token

※ 必要なscopeはrepoです。

作成したpersonal access tokenはリポジトリAのsecretsに保存します。

GitHub - 暗号化されたシークレットの作成と保存

保存したtokeは(1)-2で、Rest APIを実行する際のsecrets.MY_GITHUB_ACCESS_TOKENで使用します。

(1)-2 repository dispatch eventの作成

リポジトリAにpushされたことを契機にして、Rest APIでrepository dispatch eventを作成します。

APIの仕様は以下になります。

GitHub - Create a repository dispatch event

リポジトリAのGitHub Actionsのymlファイルの内容

on:
  push:
    branches:
      - master

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
    - name: Create GitHub dispatch event
      run: |
        curl --request POST 'https://api.github.com/repos/username/repository-b-name/dispatches' \
        --header 'Authorization: Bearer ${{secrets.MY_GITHUB_ACCESS_TOKEN}}' \
        --header 'Content-Type: application/json' \
        --data-raw '{
          "event_type": "repository-a-updated"
        }'

(2) repository_dispatchをトリガーにしたワークフローの起動

リポジトリAからリポジトリBに向けてrepository dispatch eventが送出されるので、これをリポジトリBで受け取れるようにします。

repository_dispatchというイベントを受け取って、GitHub Actionsのワークフローを開始できるようにします。

GitHub - Events that trigger workflows

リポジトリBのGitHub Actionsのymlファイルの内容

on:
  repository_dispatch:
    types: 
      - repository-a-updated # repository_dispatch送出時のevent_typeの名前と揃える

jobs:
  build:
    name: Build
    runs-on: ubuntu-latest
    steps:
      - name: Checkout Repo
        uses: actions/checkout@master
      # 適宜、テストやビルドを実行

参考

GitHub Support Community - Triggering by other repository

GitHub Support Community - Trigger a workflow from another workflow

Github Actionsが使えるようになったので使ってみる

Github Actionsの使い方メモ

Github Actions 4ヶ月使ってみてわかったことまとめ

5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5