GitHub Actionsをcurlを使って外部から実行する
やりたいこと
ここではHTTPのリクエストで外部から実行する。HTTPのリクエストで実行できるため様々な場所から利用できる可能性があると思う。
やりかた
workflow_dispatchを使うと可能。
具体例として以下のhello.ymlを作る。
code:.github/workflows/hello.yml
name: hello
on:
workflow_dispatch:
jobs:
hello_job:
runs-on: ubuntu-18.04
steps:
- run: echo "hello, world"
上記のワークフローを実行するには以下のようにcurlでHTTPのPOSTリクエストをする。
code:bash
curl \
-X POST \
-H 'Authorization: token xxxxxxxxxxxx' \
-H "Accept: application/vnd.github.v3+json" \
-d '{"ref":"master"}'
埋めるべき箇所は、
ユーザー名の部分はowner。organizationも含まれる。
リポジトリ名。
ワークフローの指定方法
上記のcurlのURLは以下のようになっていてhello.ymlが含まれる。ここでワークフローを指定することが出来る。
https://api.github.com/.../hello.yml/dispatches
入力を外部から渡す方法
inputを外部からもらってそれに基づいて動作を変えたりしたくなる。それを実現する方法。
具体例として、以下のようにhello-with-input.ymlを作る。
code:.github/workflows/hello-with-input.yml
name: hello with input
on:
workflow_dispatch:
inputs:
my_hello_input:
description: 'hello input'
required: true
default: 'this is a default hello input'
jobs:
hello_job:
runs-on: ubuntu-18.04
steps:
- run: echo "hello, ${{ github.event.inputs.my_hello_input }}"
上記のworkflow_dispatch: にinputs: が増えていて入力を受け付けられるようになっている。
入力は${{ github.event.inputs.my_hello_input }}を使って利用できる。
curlで入力値を渡す
以下のようにリクエストすることで入力値を渡すことができる。
code:bash
curl \
-X POST \
-H 'Authorization: token xxxxxxxxxxx' \
-H "Accept: application/vnd.github.v3+json" \
-d '{"ref":"master", "inputs": { "my_hello_input": "input from curl" } }' \
以下は実際に実行された結果。"input from curl"が表示できていることが分かる。
https://gyazo.com/9e455e9ff1774a38348eaafa1c3d93ee
おまけ:手動で実行する
workflow_dispatchは手動で(GiHubのUIで)実行できる。むしろworkflow_dispatchはこちらの手法で実行する方がよく知られていると思う。
まず、以下のようにすでに作成している「hello with input」をSelect workflowで選択する。
https://gyazo.com/3f3b088469a888bedb8658464932143b
すると以下のように「Run workflow」できる。ここで入力値を決めることも出来る。
https://gyazo.com/e7e8cc5e294a3f6088177126d16b624e
個人的にはworkflow_dispatchの良さはHTTPリクエストでも手動でもトリガーできる点。
おまけ:類似のイベント
workflow_dispatchの類似のイベントとしてrepository_dispatchがある。