LoginSignup
0
0

特定のpathに変更があった際にGithub Actionsを動作させる

Posted at

はじめに

個人開発でCI/CDをGithub Actionsで作成していた際に、ある特定のファイルやディレクトリに変更があった際にのみ実行する方法を調べたのでまとめていきます。

修正前のワークフロー

以下が実際に個人開発で使用していたワークフローです。
OpenAPIで定義したyamlファイルをhtmlに変換し、それを指定したサーバにホスティングするという内容です。この状態だと、yamlファイルの変更時だけでなくアプリケーションコードやその他のAPIドキュメントに関係のないコードが変更された場合にもこのワークフローが実行されてしまいます。

name: API Document Hosting

on:
  push:
    branches: [main]
  workflow_dispatch:

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Convert YML to HTML
        run: |
          npm install -g redoc-cli
          redoc-cli bundle reference/devlocator.yaml -o ./docs/index.html
      
      - name: Deploy to GitHub Pages
        uses: peaceiris/actions-gh-pages@v3
        with:
          github_token: ${{ secrets.GITHUB_TOKEN }}
          publish_dir: ./docs

      - name: Deploy to Hosting PC
        uses: appleboy/scp-action@v0.1.4
        with:
          host: ${{ secrets.HOST }}
          username: ${{ secrets.USERNAME }}
          password: ${{ secrets.PASSWORD }}
          port: ${{ secrets.PORT }}
          key: ${{ secrets.KEY }}
          passphrase: ${{ secrets.PASSPHRASE }}
          source: "index.html"
          target: "/var/www/html/api"

特定のpathsの変更のみ検知するには?

公式ドキュメントのワークフロー構文にありました。
https://docs.github.com/ja/actions/using-workflows/workflow-syntax-for-github-actions#onpushpull_requestpull_request_targetpathspaths-ignore

pathsを使うことで指定したpathsでの変更のみがワークフロー実行のトリガーとなります。

修正後のワークフロー

name: API Document Hosting

on:
  push:
    branches: [main]
    paths:
      - "reference/openapi.yaml"
  workflow_dispatch:

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Convert YML to HTML
        run: |
          npm install -g redoc-cli
          redoc-cli bundle reference/devlocator.yaml -o ./docs/index.html
      
      - name: Deploy to GitHub Pages
        uses: peaceiris/actions-gh-pages@v3
        with:
          github_token: ${{ secrets.GITHUB_TOKEN }}
          publish_dir: ./docs

      - name: Deploy to Hosting PC
        uses: appleboy/scp-action@v0.1.4
        with:
          host: ${{ secrets.HOST }}
          username: ${{ secrets.USERNAME }}
          password: ${{ secrets.PASSWORD }}
          port: ${{ secrets.PORT }}
          key: ${{ secrets.KEY }}
          passphrase: ${{ secrets.PASSPHRASE }}
          source: "index.html"
          target: "/var/www/html/api"

終わりに

pathsを加えることでより効率の良いワークフローができたのではないでしょうか!
CI/CDは今やどこの開発現場でも目にするので、当たり前に導入してより効率の良い方法を学習していきたいですね。cacheなんかは高速化の代表的な方法なので別記事にまとめていきます💪

0
0
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
0
0