【初心者】GitHub Actionsのカスタムアクションを作ってみる

【初心者】GitHub Actions のカスタムアクションを作ってみる
はじめに
こんにちは、BTMの藤野です。
GitHub Actions を勉強していてカスタムアクションはどうやったら作れるのかな?と思ったので作りかたを調べて纏めてみました。
やりたいこと
- GitHub Actions で使えるカスタムアクションを作成したい
- 作成したカスタムアクションを同じユーザーの各リポジトリから呼び出し実行したい
GitHub Actions のカスタムアクションとは?
GitHub Actions のワークフロー内で再利用可能な独自のアクションを作成し、特定の処理の実行を提供できる仕組みです。複数のワークフローから同じ処理を再利用したりできます。
カスタムアクションの種類
- Docker コンテナアクション
Dockerfile を作成しコンテナ内でアクションを実行 - JavaScript アクション
JavaScript を作成しアクションを実行 - Composite アクション
他のアクション呼び出しやシェルコマンドをYAML内で実装
※本稿では JavaScript アクションを使ってカスタムアクションを作っていきます。
カスタムアクションを作ってみる
事前準備
Personal Access Token の取得
公式ドキュメントを参考に Personal Access Token を取得
– Select scope で workflow
にチェック
必要なディレクトリ/ファイルの作成
- GitHub にプライベートリポジトリ
my_custom_actions_repo
を作成 - ローカルに
git clone
(ユーザー名+PAT 登録) - 以下構成でファイルを作成
my_custom_actions_repo
├── .github
│ └── workflows
│ └── hello-world.yml
├── action.yml
└── index.js
※JavaScript 実行に Node.js が必要
ワークフローファイルの定義 .github/workflows/hello-world.yml
name: Hello World Workflow
on:
push:
branches:
- main
jobs:
hello-world:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Run Hello World Action
uses: ./ # 同リポジトリの action.yml を参照
アクション定義 action.yml
name: "Hello World Action"
description: "Outputs Hello, World!"
inputs:
name:
description: "Your name"
required: false
default: "World"
runs:
using: "node20"
main: "index.js"
JavaScript 本体 index.js
import { getInput, info, setFailed } from '@actions/core';
try {
const name = getInput('name');
info(`Hello, ${name}!`);
} catch (error) {
setFailed(error.message);
}
@vercel/ncc でコンパイル
- 依存パッケージをインストール
npm install @actions/core @actions/github
- ncc をグローバルインストール
npm i -g @vercel/ncc
- コンパイル
ncc build index.js
- action.yml の main を修正
runs: using: "node20" main: "dist/index.js"
コミット & プッシュ
git add .
git commit -m "create my_custom_actions_repo"
git push origin main
Actions 実行結果の確認
GitHub リポジトリの Actions タブで「Hello, World!」が出力されていることを確認
タグの追加(リリース)
git tag -a v1.0.0 -m "release my_custom_actions_repo"
git push origin v1.0.0
別リポジトリから呼び出す
同ユーザーからのアクセス許可
ホストリポジトリの Settings > Actions > General で
- Access:
Accessible from repositories owned by the user ''
を選択
呼び出し用リポジトリのワークフロー
name: Use Custom Actions
on:
push:
branches:
- main
jobs:
hello-world:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Use custom action
uses: btm-m-fujino/my_custom_actions_repo@v1.0.0
with:
name: 'm-fujino'
コミット & プッシュ & 実行確認
別リポジトリの Actions タブで「Hello, m-fujino!」が出力されることを確認
まとめ
- GitHub Actions カスタムアクションは再利用可能な独自処理
- 種類:Docker/JavaScript/Composite
- JavaScript アクションは依存含め ncc コンパイルが必要
- 同ユーザー別リポジトリから呼び出すにはアクセス許可設定が必須
おわりに
基本を押さえた上で、より複雑な処理にもチャレンジしてみてください。
株式会社BTMではエンジニア採用をしております。
ご興味がある方はぜひ コチラ をご覧ください。
-
SNS
-
投稿日
-
カテゴリー
BTM Useful