如何遠程觸發 GitHub Action

  1. 常見的幾種觸發 GitHub Action 的方式

下面是一個 GitHub Action 的示例:

name: GitHub Actions Demo
on: [push, pull_request]
jobs:
  Explore-GitHub-Actions:
    runs-on: ubuntu-latest
    steps:
      - run: echo "Hello World!"

在 on 關鍵字下,定義的就是觸發 Workflow 執行的事件。下面常用的幾種 GitHub Action 事件:

在 inputs 中可以添加交互參數 (可選)。

on:
  workflow_dispatch:
    inputs:
      name:
        description: 'Person to greet'
        required: true
        default: 'Mona the Octocat'
on:
  push
on:
  issues:
    types: [opened, edited, milestoned]
on:
  issue_comment:
    types: [created, deleted]
on:
  project:
    types: [created, deleted]
on:
  pull_request:
    types: [assigned, opened, synchronize, reopened]

利用這些事件 hook,可以自動化很多流程。

  1. 使用 API 遠程觸發 GitHub Action

2.1 創建一個 Token

訪問鏈接頁面 https://github.com/settings/tokens/new 申請一個 Token。

需要勾選 repo 權限。

2.2 添加

在倉庫 https://github.com/shaowenchen/wait-webhook-to-run 下,新建一個文件 .github/workflows/worker.yml。內容如下:

on: 
  repository_dispatch:
    types:
      - webhook-1
      - webhook-2

jobs:
  run:
    runs-on: ubuntu-latest

    steps:
    - name: Hello World
      run: |
        echo Hello World!

repository_dispatchtypes 中,可以自定義事件類型。

2.3 遠程觸發 Github Action

下面是 API 調用格式:

curl -X POST https://api.github.com/repos/:owner/:repo/dispatches \
    -H "Accept: application/vnd.github.everest-preview+json" \
    -H "Authorization: token TRIGGER_TOKEN" \
    --data '{"event_type": "TRIGGER_EVENT"}'

其中,owner 是用戶名,repo 是倉庫名, TRIGGER_TOKEN 是上面申請的 Token 憑證,TRIGGER_EVENT 是自定義的事件名。

curl -X POST https://api.github.com/repos/shaowenchen/wait-webhook-to-run/dispatches \
    -H "Accept: application/vnd.github.everest-preview+json" \
    -H "Authorization: token ghp_xxxxxxxxxxxxxxxxxxxxxxxxxx" \
    --data '{"event_type": "webhook-1"}'
curl -X POST https://api.github.com/repos/shaowenchen/wait-webhook-to-run/dispatches \
    -H "Accept: application/vnd.github.everest-preview+json" \
    -H "Authorization: token ghp_xxxxxxxxxxxxxxxxxxxxxxxxxx" \
    --data '{"event_type": "webhook-2"}'

查看 GitHub Action 執行:

  1. 參考

本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源https://mp.weixin.qq.com/s/THp2gUZmUT90rauZzrip2A