less is more

心のフルスタックエンジニア👨‍💻バイブスでコードを書いています🤘

自前のGithub Actionsを作ってみる

この記事を書いた時に、プラットフォームの発展に結構可能性を感じたので自分でも作ってみる。

bluepixel.hatenablog.com

何を作るかはさておき、まずは作り方を一通り調べてみる。

ドキュメントはここから。 help.github.com

基本的な仕様

About actions - GitHub Help

  • メタデータaction.yml または action.yaml に定義する。
  • アクションはDockerコンテナまたはJavaScriptで実装する。
  • 自前のアクションは.github/actions/*に配置するのが推奨。
  • 公開する場合はタグでセマンティックバージョニングを行うのが推奨。

チュートリアル

Dockerで作る方で進めてみる。

help.github.com

このページでは、hello-world-docker-actionというアクションを作るチュートリアル形式で流れを説明してくれる。

1. Dockerfileを作る

JavaScriptで作る分には実行環境がすでにGithubのランナーに用意されているが、それ以外の言語を使いたい場合はDockerをかます必要がある。

# Container image that runs your code
FROM alpine:3.10

# Copies your code file from your action repository to the filesystem path `/` of the container
COPY entrypoint.sh /entrypoint.sh

# Code file to execute when the docker container starts up (`entrypoint.sh`)
ENTRYPOINT ["/entrypoint.sh"]

2.メタデータaction.ymlに記述する

入力や出力値の定義、マーケットプレイスに公開する際のアイコンや作者名を管理するファイル。

# action.yml
name: 'Hello World'
description: 'Greet someone and record the time'
inputs:
  who-to-greet:  # id of input
    description: 'Who to greet'
    required: true
    default: 'World'
outputs:
  time: # id of output
    description: 'The time we greeted you'
runs:
  using: 'docker'
  image: 'Dockerfile'
  args:
    - ${{ inputs.who-to-greet }}

inputsに定義した値をargsとして注入して、imageに指定したファイルからコンテナをビルドするサンプル。

3. スクリプトを作る

エントリーポイントとなる entrypoint.sh を作成。

#!/bin/sh -l

echo "Hello $1"
time=$(date)
echo "::set-output name=time::$time"

実行権限を付与する。

chmod +x entrypoint.sh

echo "::set-output name=<output name>::<value>"Github Actionsのシンタックスで、後のワークフローで参照することのできる値として出力を行う。

エラーがなくスクリプトの実行が終了すると、ステータスがsuccessとなる。 0以外でexitした場合はfailureとしてマークされる。

4. READMEを書く

こういうサンプルは参考になる。

# Hello world docker action

This action prints "Hello World" or "Hello" + the name of a person to greet to the log.

## Inputs

### `who-to-greet`

**Required** The name of the person to greet. Default `"World"`.

## Outputs

### `time`

The time we greeted you.

## Example usage

uses: actions/hello-world-docker-action@v1
with:
  who-to-greet: 'Mona the Octocat'

5. テストする

ワークフローをテストする。 別のリポジトリの場合はusesを使って自分のリポジトリに参照を向ければよい。同じリポジトリでやる場合はサンプルをそのまま使う。プライベートリポジトリの場合、別のリポジトリからは参照できない。

on: [push]

jobs:
  hello_world_job:
    runs-on: ubuntu-latest
    name: A job to say hello
    steps:
    - name: Hello world action step
      id: hello
      uses: actions/hello-world-docker-action@v1
      with:
        who-to-greet: 'sakuraya'
    # Use the output from the `hello` step
    - name: Get the output time
      run: echo "The time was ${{ steps.hello.outputs.time }}"

チュートリアル終了。

自前のアクションを作ってマーケットプレイスにリリースする

CloudFormationの定義ファイルを監視してスタックの変更内容をプルリクにコメントするBotを作りました。

github.com

マーケットプレイスにリリース済みです。

次回はこれの実装方法とリリースを解説します〜

bluepixel.hatenablog.com