【GitHub Actions】Go で 自作 Actions を 作ってみる
今回は、GitHub Actions の Custom Actions を利用して、他のリポジトリから利用できる自作の Actions を Go で作ってみようと思います。
Custom Actions とは
Custom Actionsは、独自のアクションを作成することやビルドしたアクションを共有することができます。
また、Docker, JavaScript, 複合アクションの3種類で作成することができます。
今回は、複合アクション(composite)を利用して actions を作成してみます。
Composite Action を作成
Composite Action のサンプルコードはこちらのリポジトリを参考にしてください。
まずは、sample-composite-actionというリポジトリを作成します。
次にComposite Action で実行したいGoのコードを書きます。まずは以下のmain.goを追加してください。
package main
import (
"flag"
"fmt"
)
func main() {
flag.Parse()
fmt.Println(flag.Args())
}
main.goは実行時の引数を出力するだけのコードです。
続いて Composite Action を作成します。
action.yaml という名前の新しいファイルを作成し、次のコード例を追加します。
name: "sample-composite-action"
description: "sample-composite-action"
inputs:
test-input:
description: "test input data"
required: true
default: ""
runs:
using: "composite"
steps:
- run: go run ${{ github.action_path }}/main.go ${{ inputs.test-input }}
shell: bash
inputsでは入力の定義をします。このコードでは test-inputという入力を受け取るようにします。requiredやdefaultも設定できます。
続いてrunsには実行したい処理を記述します。今回は、main.goを実行し、引数としてinputs.test-inputを渡しています。また${{ github.action_path }}/main.goというpathを指定することに注意してください。
ここまでコードが書けたらリポジトリにpushしてください。
次にターミナルから、v1というタグを追加します。
git tag -a -m "Description of this release" v1
git push --follow-tags
Custom Actions を他のリポジトリから実行する
Composite Action を実行するためのサンプルコードはこちらのリポジトリを参考にしてください。
Composite Action を実行するためにuse-sample-composite-actionというリポジトリを新しく作成してください。
続いて新しいリポジトリに.github/workflows/test.yamlを追加してください。
以下のコードには自分のUserNameを入れる部分があるので注意してください。
on: [push]
jobs:
test_job:
runs-on: ubuntu-latest
name: test
steps:
- name: Checkout
uses: actions/checkout@v3
- name: Use sample-composite-action
uses: <自分のuser-name>/sample-composite-action@v1
with:
test-input: "test"
sample-composite-actionの入力であるtest-inputに、"test"という文字列を入れました。
こちらをpushするとワークフローが実行されます。
以下のリンク先には実行結果があり、testという文字列が表示されます。
まとめ
今回は Custom Actions の Composite Action を Go で作成してみました。
Discussion