[GitHub] 使用 GitHub CLI (gh) 觸發還在 PR 中的 GitHub Actions workflow 測試

[GitHub] 使用 GitHub CLI (gh) 觸發還在 PR 中的 GitHub Actions workflow 測試

最近在研究修改 GitHub Actions 的 workflow,

不過卻遇到一個問題:我要怎麼測試我修改的 workflow 呢?

 

我的修改是放在一個 GitHub PR 裡面,

但在 PR 合併到主分支前,這個新的 workflow 內容是不會被跑到的。

這樣就有點尷尬,總不能一直合併到主分支,

然後修 bug,再持續合併到主分支吧,完全失去 PR 的意義了~

 

爬文了一下,有人提到可以用 GitHub CLI 處理這個問題。

來看一下怎麼做吧~

 

1. 安裝 GitHub CLI

首先,在 Mac 上用 Homebrew 安裝 gh 這個工具程式:

brew install gh

 

2. 讓 GitHub CLI 連上 GitHub

接著,我們需要執行 gh auth login 指令來連上 GitHub。

這邊會需要提供像 GitHub 伺服器的位置,然後會在瀏覽器上登入 GitHub:

$ gh auth login

? What account do you want to log into? GitHub Enterprise Server
? GHE hostname: github.test.com
? What is your preferred protocol for Git operations on this host? HTTPS
? Authenticate Git with your GitHub credentials? Yes
? How would you like to authenticate GitHub CLI? Login with a web browser

! First copy your one-time code: F70D-EA71
Press Enter to open github.test.com in your browser...
✓ Authentication complete.
- gh config set -h github.test.com git_protocol https
✓ Configured git protocol
✓ Logged in as testuser

 

登入成功後,GitHub CLI 就已經可以跟 GitHub 伺服器通訊了~

 

3. 使用 GitHub CLI 觸發 GitHub Actions workflow

gh workflow run 來執行我們的 GitHub Actions workflow,

這邊有幾個參數要給:

  • 要先指定要跑的 workflow yaml
  • --ref 指定要使用哪一個分支
  • -f 指定 workflow 需要的參數的對應值

 

執行的樣子如下,它會產生一個 workflow_dispatch 的事件,

就好像你手動去觸發那個 GitHub Actions workflow 一樣,

只是它會用你放在 --ref 指定分支裡的 workflow 去跑:

$ gh workflow run test-cd.yml \
    --ref poc/test-github-actions \
    -f environment=test \
    -f region=eu-central-1 \
    -f action=plan

✓ Created workflow_dispatch event for test-cd.yml at poc/test-github-actions

To see runs for this workflow, try: gh run list --workflow=test-cd.yml

 

這樣子的觸發方式也比較方便,因為參數可以固定下來,

就可以持續的跑一樣的 CLI 指令來測試,

比起一直在 GitHub web UI 上操作,要快得多囉~

 

參考資料:How to test github workflow without merging into master/main branch

(本頁面已被瀏覽過 40 次)

2 thoughts on “[GitHub] 使用 GitHub CLI (gh) 觸發還在 PR 中的 GitHub Actions workflow 測試

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料