Home Github Action to GCS
Post
Cancel

Github Action to GCS

Github actions

GitHub Actions 是 GitHub 提供的一套 CI/CD(持續整合/持續部署)工具,讓開發者能夠自動化執行各種工作流程。例如,當你提交程式碼變更到儲存庫時,GitHub Actions 可以自動執行測試、編譯專案、部署應用程式,甚至可以進行檔案格式檢查或其他任務。

以下是 GitHub Actions 的一些主要特點:

工作流程 (Workflow):工作流程是一個 YAML 格式的設定檔,位於儲存庫的 .github/workflows 資料夾內。每個工作流程包含不同的自動化指令,可以根據特定事件(例如推送程式碼、建立 PR、發佈標籤)觸發。

工作 (Job):每個工作流程可以包含一個或多個工作。每個工作都是在虛擬環境(如 Ubuntu、Windows、macOS 等)中執行,並由多個步驟 (Step) 組成。

步驟 (Step):步驟是工作的基本執行單元,每一步驟可以執行一個指令,或使用預先定義的 GitHub Actions,例如拉取程式碼、安裝依賴、執行測試等。

觸發事件 (Event Triggers):GitHub Actions 支援許多觸發事件,包括程式碼推送、PR(Pull Request)變更、Issue 開啟/關閉、發佈標籤等。這讓工作流程可以根據不同需求進行自動化操作。

儲存憑證和密鑰 (Secrets):若需要在工作流程中使用敏感資訊(如 API 金鑰、密碼等),GitHub Actions 提供 secrets 機制來安全地儲存和使用這些資訊。

GitHub Actions 讓開發者能輕鬆構建、測試和部署程式碼,有效提升自動化程度和工作效率。

有許多類型的 Action, 其中 deployment 大致如下

Desktop View

GitHub Actions to GCS

GitHub 有外掛工具可以幫助你自動將打包好的前端代碼直接部署到 Google Cloud Storage。常見的解決方案是使用 GitHub Actions,它是一個內置於 GitHub 的 CI/CD 平台,可以通過定義工作流自動化部署過程。下面是使用 GitHub Actions 將你的前端打包並部署到 Google Cloud Storage 的步驟。

步驟 1: 配置 Google Cloud Service Account 和憑證

在 Google Cloud Console 上創建一個 Service Account,並為其分配 Storage Object Admin 角色,這樣它就有權限將文件上傳到 GCS。

生成一個 JSON 格式的密鑰文件,這將是 GitHub Actions 用來與 Google Cloud 進行身份驗證的憑證。

至 Google Cloud Platform 建立憑證

Desktop View

建立服務帳戶

Desktop View

服務帳戶名稱設定,基本上就是下一步

Desktop View

選用儲存空間管理員,這樣才有權限將資料上傳到 bucket

Desktop View

建立新的金鑰

Desktop View

建立完金鑰,將 secret 下載下來,晚點 Github Action 會用到

Desktop View

步驟 2 創建 Google Cloud Storage Bucket

建立 Bucket

Desktop View

下一步

Desktop View

下一步

Desktop View

步驟 3: 將 Google Cloud 密鑰添加到 GitHub Secrets

在你的 GitHub repository 中,導航到 Settings > Secrets and variables > Actions。 創建一個新的 Secret,名稱可以為 GCP_KEY,並將剛才下載的 Google Cloud Service Account JSON 文件內容粘貼到該 Secret 中。

GCP_PROJECT 就貼上你 JSON 中的 project_id, 直接貼上內容就好,不需要字串的雙引號

Desktop View

步驟 4: 創建 GitHub Actions 工作流

在你的 GitHub repository 中創建一個 .github/workflows/deploy.yml 文件,並填入以下內容:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
name: Deploy to Google Cloud Storage

on:
  push:
    branches:
      - main

jobs:
  build:
    runs-on: ubuntu-latest

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

    - name: Set up Node.js
      uses: actions/setup-node@v2
      with:
        node-version: '16'

    - name: Install dependencies
      run: npm install

    - name: Build project
      run: npm run build

    - name: Authenticate to Google Cloud
      uses: google-github-actions/auth@v1
      with:
        credentials_json: # $

    - name: Set up Google Cloud SDK
      uses: google-github-actions/setup-gcloud@v1
      with:
        project_id: # $

    - name: Upload to Google Cloud Storage
      run: |
        gsutil -m rsync -r public gs://words-storage # add comment

執行結果

Desktop View

Desktop View

完成啦!下次示範如何使用 Github Action to Google Cloud Run

☝ツ☝

This post is licensed under CC BY 4.0 by the author.

👈 ツ 👍