GitHub Actions 教學:免金鑰部署 Cloud Run,靠 GitHub 5 分鐘的通行證換 Google 1 小時的憑證。
很多 GitHub Actions 教學的第一步,是叫你建一把服務帳戶金鑰(一個 JSON 檔),貼進 GitHub 的 Secrets(GitHub 存放密碼、金鑰的加密欄位,workflow 執行時才讀得到)。那把金鑰預設永不過期,誰拿到誰就能用你的 Google Cloud,直到你發現並手動停用為止。
這篇改用 Google 官方推薦的 Workload Identity Federation(簡稱 WIF):repo 裡、GitHub Secrets 裡都沒有任何金鑰。部署的對象是一個只回一行文字的 Python 小網站,我在 2026 年 12 月 4 日深夜實際做了一次:
- push 到
main,GitHub Actions 自動測試 → 建映像檔 → 推到 Artifact Registry → 部署到 Cloud Run,整條 57 秒 - 故意換一個分支跑,看它在「換憑證」那一步被 Google 擋下來
- 用 Cloud Audit Logs(稽核記錄)查出每次部署是哪個 repo、哪個分支做的
- 再用自架的 GitLab CI 做同一件事,比較兩邊寫法
這篇寫給想學 GitHub Actions、想把 CI/CD 接上 GCP、或正在準備 GCP DevOps 證照的人,指令都可以整段複製。這是「DevOps 證照+Ops 名詞」系列第 14 篇。

為什麼你需要知道
- 金鑰外流的代價很大:JSON 金鑰檔外流(不小心 commit 進 repo、被貼進聊天群組、CI 的 log 印出來),拿到的人不用密碼、不用手機驗證,就能用那個服務帳戶的所有權限
- 新的 GCP 機構已經不讓你建金鑰:Google 官方文件寫明,2024 年 5 月 3 日以後建立的機構(organization),預設會擋「建立服務帳戶金鑰」(
constraints/iam.disableServiceAccountKeyCreation)。照舊教學做,第一步就會卡住(2026 年 12 月查官方文件) - 證照新版考綱新增了這題:Professional Cloud DevOps Engineer 2026 年 11 月 23 日起的新版考綱,2.3 節多了一條「Managing short-lived credentials」(管理短效憑證),而 Workload Identity Federation 本來就列在 2.3 的設定與秘密管理裡
- 面試會被問到:「你們的 CI/CD 怎麼拿雲端權限?」答「把金鑰放在 Secrets」,很容易被追問「那金鑰外流怎麼辦」
GitHub Actions 是什麼:放在 GitHub 上的自動化流水線
GitHub Actions 是 GitHub 內建的自動化服務:你在 repo 裡放一個 YAML 設定檔,寫好「發生什麼事就做哪些步驟」,GitHub 就會開一台臨時的機器幫你照做。
- 白話:push 程式碼之後,自動幫你跑測試、打包、部署的機器人
- 生活比喻:像餐廳的出餐流程表貼在廚房牆上。單子一進來(push),廚房照表做:洗菜(測試)、炒菜(建映像檔)、出餐(部署)。流程表就是那個 YAML 檔
- 來龍去脈:GitHub 在 2019 年 8 月讓 Actions 支援 CI/CD、2019 年 11 月正式推出。在那之前,GitHub 上的專案要另外接 Travis CI、CircleCI、Jenkins 這些外部服務
- 為什麼要學:GitHub 是最多人用的程式碼平台,很多公司的 CI/CD 直接用 Actions。會寫 workflow 檔,等於會看懂公司的部署流程
YAML 是一種用縮排表示層級的設定檔格式,冒號左邊是名稱、右邊是值。GitHub Actions 的設定檔都放在 repo 的 .github/workflows/ 資料夾裡,副檔名是 .yml。
這篇會一直出現 3 個 Git 基本詞:repo(repository,程式碼倉庫)是放一個專案所有程式碼和修改紀錄的地方;push 是把自己電腦上的修改上傳到 repo;分支(branch)是同一份程式碼的平行版本,main 通常是要上線的那一條,其他分支用來開發、試東西。
| 名詞 | 白話 | 這篇的例子 |
|---|---|---|
| workflow(工作流程) | 一整份流程表,一個 .yml 檔 | .github/workflows/deploy.yml |
| event(觸發事件) | 什麼時候開始跑,寫在 on: | push 到 main、手動按 Run workflow |
| job(工作) | 流程表裡的一大段,每個 job 開一台新的臨時機器 | test、deploy 兩個 job |
| step(步驟) | job 裡的一行一行指令 | 跑測試、建映像檔、部署 |
| runner(執行器) | 真正跑 job 的機器 | GitHub 提供的 ubuntu-latest |
| action(現成積木) | 別人寫好的步驟,用 uses: 呼叫 | google-github-actions/auth@v3 |
收費(2026 年 12 月查 GitHub 官方文件):公開 repo 用 GitHub 提供的標準 runner 免費。私人 repo 的 GitHub Free 方案每月內含 12 美元的運算額度,標準 Linux runner 每分鐘 0.006 美元,12 ÷ 0.006 = 2,000 分鐘。
算一次:這篇的 workflow 兩個 job 加起來 51 秒(測試 7 秒、部署 44 秒)。保守抓「每個 job 算 1 分鐘、一次 2 分鐘」,2,000 ÷ 2 = 每月可以部署約 1,000 次。部署越頻繁、job 越長,額度用得越快;用不完不會累積到下個月。
Workload Identity Federation 是什麼:拿通行證換房卡
Workload Identity Federation 是 Google Cloud IAM 的功能:讓 GCP 外面的程式,拿它自己平台發的身分證明,去換 Google 的短效憑證,不用下載任何金鑰檔。
- 白話:GitHub 幫你的 workflow 開一張「我是某某 repo、某某分支」的證明,Google 看了證明、照你設的規則核對,發一張 1 小時後就失效的權杖
- 生活比喻:飯店換房卡。你拿護照(GitHub 發的通行證)到櫃台(Google 的權杖服務),櫃台照規則核對(只收這個 repo、只收
main分支),發你一張隔天就失效的房卡(存取權杖)。你不用把萬能鑰匙(金鑰檔)一直放在背包裡 - 來龍去脈:名字拆開是 Workload(工作負載,就是程式)+Identity(身分)+Federation(聯盟,互相承認對方發的身分)。Console 中文介面叫「Workload Identity 聯盟」。Google Cloud 官方部落格在 2021 年 12 月發文介紹 GitHub Actions 用它免金鑰登入,同時推出
google-github-actions/auth這個 action - 為什麼要學:它是「CI/CD 怎麼安全地拿雲端權限」的標準答案,證照、面試、實際工作都會碰到
先看整個流程:4 步
- GitHub 在 workflow 執行時,發一張「我是哪個 repo、哪個分支」的通行證
- workflow 拿通行證到 Google 的換證櫃台(STS,Security Token Service,下面名詞表會再講)
- 櫃台照你設的規則核對,過了,就讓它「扮演」一個專門部署用的服務帳戶
- 換到 Google 的存取權杖(房卡),拿去推映像檔、部署 Cloud Run
這篇的說法固定這樣用:通行證=GitHub 或 GitLab 發的 OIDC 權杖,幾分鐘就過期;存取權杖(也叫短效憑證,就是房卡)=Google 發的,約 1 小時過期。兩個都是「一串證明身分的文字」,差在誰發的、拿去哪裡用。
會用到的 6 個名詞
OIDC 權杖(OpenID Connect token):OIDC 是一套「怎麼發身分證明」的公開標準;權杖是一段用 . 隔成三段的文字,中間那段寫著「誰發的、發給誰、什麼時候過期」,最後一段是簽名,偽造不了。這篇叫它「通行證」。
| 名詞 | 白話 | 這篇建的 |
|---|---|---|
| 身分集區(Workload Identity Pool) | 一個「我信任哪些外部身分」的資料夾 | do-14-pool |
| 提供者(Provider) | 集區裡的一個發證單位,記著它的網址和規則 | do-14-github、do-14-gitlab |
| 屬性對應(attribute mapping) | 從通行證裡挑哪些欄位出來用 | repo ID、分支名稱 |
| 屬性條件(attribute condition) | 通行證要符合什麼才收,不符合直接拒絕 | 只收這個 repo ID 的 main 分支 |
| STS(Security Token Service,安全權杖服務) | Google 負責「驗通行證、換權杖」的櫃台 | sts.googleapis.com |
| 扮演服務帳戶(service account impersonation) | 換到的身分去「借用」一個服務帳戶的權限 | 扮演 do-14-deployer |
服務帳戶(service account)是給程式用的 Google Cloud 帳號,跟你登入用的個人帳號分開。IAM(Identity and Access Management)是 Google Cloud 管「誰能對哪個資源做什麼」的權限系統;權限是用 IAM 角色(一包權限的組合)「綁」上去的,綁一次就叫一條授權。
為什麼要「扮演服務帳戶」,不直接給權限?
Google 官方文件建議優先用「直接授權」(direct resource access):不經過服務帳戶,直接把角色給外部身分。但官方的支援服務清單寫明:Cloud Run 不支援直接授權,要用扮演服務帳戶(2026 年 12 月查)。
所以這篇的做法是:GitHub 的通行證換到身分後,去扮演 do-14-deployer 這個專門部署用的服務帳戶,用它的權限推映像檔、部署 Cloud Run。官方也建議每條管線用一個專用的服務帳戶,這篇 GitHub 和 GitLab 各用一個。

動手做:GitHub Actions 用 WIF 部署 Cloud Run
這段做完會有:一個公開的 GitHub repo,push 到 main 就自動測試、建映像檔、部署到 Cloud Run,全程沒有任何金鑰。
- 在哪裡做:GCP 的設定在 Cloud Shell(Google 提供、開瀏覽器就能打指令的 Linux 終端機),專案 dong-dong-gcp-3,區域
asia-east1(台灣彰化);程式碼放在 GitHub - 花多久:GCP 設定約 10 分鐘,GitHub 跑一次約 1 分鐘
- 事前準備:一個已連結帳單帳戶的 GCP 專案、一個 GitHub 帳號。下面指令裡的
dong-dong-gcp-3要換成你的專案 ID,aaronlee700618/do-14-github-actions-demo要換成你的「帳號/repo 名稱」 - 會不會花錢:幾乎不會。WIF 屬於 IAM,IAM 定價頁寫明 IAM API 全部免費;公開 repo 的 GitHub Actions 免費;Cloud Run 沒人用時縮到 0 台。做完照最後一段刪乾淨
怎麼開 Cloud Shell:登入 Google Cloud Console,左上角藍框是專案選單,右上角紅框那個 >_ 圖示就是 Cloud Shell:

點下去,畫面下方會開出黑底的終端機,看到結尾是 $ 的提示字元就能打指令(這張是容器系列拍的畫面):

下面每段指令都是整段複製、貼進 Cloud Shell、按 Enter,等提示字元再出現就是跑完了。截圖裡的提示字元有縮短,你的畫面會是「你的帳號@cloudshell:~ (專案ID)$」。這篇建的東西一律 do-14- 開頭,刪的時候不會刪錯。
步驟 1:設定變數,開 6 個 API
先把會重複用到的值存進變數(終端機暫時記住的名稱和值,後面用 $名稱 取出來)。PROJECT_NUMBER 是專案編號(一串數字,跟專案 ID 不一樣),WIF 的設定要用編號:
PROJECT_ID=dong-dong-gcp-3; PROJECT_NUMBER=$(gcloud projects describe $PROJECT_ID --format='value(projectNumber)'); REGION=asia-east1; GH_REPO=aaronlee700618/do-14-github-actions-demo; echo "$PROJECT_ID / $PROJECT_NUMBER / $REGION / $GH_REPO"
dong-dong-gcp-3 / 600195576280 / asia-east1 / aaronlee700618/do-14-github-actions-demo
變數只活在這一個 Cloud Shell 分頁裡。Cloud Shell 閒置太久斷線、或你開了新分頁,變數就不見了,指令會出現空白值而失敗;這時把這行(和步驟 3、步驟 7 開頭設變數的那行)重貼一次就好。
接著開 API(服務對外的操作介面,要先「啟用」才能用)。sts 是換權杖的櫃台、iamcredentials 是扮演服務帳戶用的,這兩個是 WIF 一定要的:
gcloud services enable iam.googleapis.com iamcredentials.googleapis.com sts.googleapis.com cloudresourcemanager.googleapis.com run.googleapis.com artifactregistry.googleapis.com
Operation "operations/acat.p2-600195576280-4ca99d37-c429-4dde-97a7-3b27e49bef24" finished successfully.

步驟 2:建放映像檔的存放區
Artifact Registry 是 Google Cloud 放映像檔的倉庫,存放區(repository)是裡面的一個資料夾。映像檔是「程式加上執行環境」打包好的檔案,Cloud Run 照它把網站跑起來:
gcloud artifacts repositories create do-14-repo --repository-format=docker --location=$REGION --description="第 14 篇 GitHub Actions 示範"
Create request issued for: [do-14-repo]
Waiting for operation [projects/dong-dong-gcp-3/locations/asia-east1/operations/9e55c72c-1ce0-41a5-8b92-f55774702eee] to complete...
...................done.
Created repository [do-14-repo].
步驟 3:建兩個服務帳戶,各給最小的權限
建兩個服務帳戶,分工很清楚:
do-14-deployer:部署用,GitHub Actions 會扮演它do-14-run:網站執行時用的身分,Cloud Run 上的程式用它的權限做事。這個小網站不用呼叫任何 Google Cloud 服務,所以它一個角色都不給
gcloud iam service-accounts create do-14-deployer --display-name="do-14 CI/CD 部署用"
gcloud iam service-accounts create do-14-run --display-name="do-14 Cloud Run 執行身分"
Created service account [do-14-deployer].
Service account email: do-14-deployer@dong-dong-gcp-3.iam.gserviceaccount.com
Created service account [do-14-run].
Service account email: do-14-run@dong-dong-gcp-3.iam.gserviceaccount.com
為什麼不用預設的服務帳戶?Cloud Run 沒指定身分時,用的是專案的 Compute Engine 預設服務帳戶,很多舊專案的它有「編輯者」這種大權限。網站被打穿的話,攻擊者就拿到整個專案。
接著給部署帳戶三個角色,每個都綁在最小的範圍:
DEPLOYER=do-14-deployer@$PROJECT_ID.iam.gserviceaccount.com; RUNTIME=do-14-run@$PROJECT_ID.iam.gserviceaccount.com
gcloud projects add-iam-policy-binding $PROJECT_ID --member=serviceAccount:$DEPLOYER --role=roles/run.developer --condition=None --format=none
gcloud artifacts repositories add-iam-policy-binding do-14-repo --location=$REGION --member=serviceAccount:$DEPLOYER --role=roles/artifactregistry.writer --format=none
gcloud iam service-accounts add-iam-policy-binding $RUNTIME --member=serviceAccount:$DEPLOYER --role=roles/iam.serviceAccountUser --format=none
Updated IAM policy for project [dong-dong-gcp-3].
Updated IAM policy for repository [do-14-repo].
Updated IAM policy for serviceAccount [do-14-run@dong-dong-gcp-3.iam.gserviceaccount.com].

| 角色 | 綁在哪 | 為什麼要 | 沒給會怎樣 |
|---|---|---|---|
roles/run.developer(Cloud Run 開發人員) | 專案 | 建立、更新 Cloud Run 服務 | 部署那步 PERMISSION_DENIED |
roles/artifactregistry.writer(Artifact Registry 寫入者) | 只有 do-14-repo | 推映像檔進去(寫入者也包含讀取) | 推映像檔被拒 |
roles/iam.serviceAccountUser(服務帳戶使用者) | 只有 do-14-run | 讓部署出來的服務「用 do-14-run 的身分跑」 | 部署時說你不能使用這個服務帳戶 |
這三個正好對上 Cloud Run 官方文件列的部署所需角色(開發人員、服務帳戶使用者、存放區讀取者)。官方範例常給 roles/run.admin(管理員),它多了「改服務的存取權限」,部署用不到,這篇不給。
run.developer 綁在專案層級,代表它也能改同一個專案裡的其他 Cloud Run 服務。正式環境建議一個環境一個專案,或在服務第一次建好之後,改成只綁在那個服務上。--condition=None 是「這條授權沒有附加條件」,專案裡已經有條件式授權時不寫會跳出詢問。
步驟 4:查 repo 的數字 ID
先在 GitHub 建一個公開 repo:右上角 + → New repository,Repository name 填 do-14-github-actions-demo,Choose visibility 選 Public,下面的 README、.gitignore、license 都不用加(檔案步驟 9 會自己放),按 Create repository:

等一下的規則要用 repo 的數字 ID,不用名稱。原因:repo 刪掉或改名後,別人可以註冊同一個名稱,名稱會被「搶註」;數字 ID 不會重複使用(Google 官方文件也這樣建議)。回到 Cloud Shell,用 GitHub 的公開 API 查(curl 是打網址拿回應的指令,jq 是挑出 JSON 欄位的工具):
curl -s https://api.github.com/repos/$GH_REPO | jq '{full_name, id, owner_id: .owner.id}'
{
"full_name": "aaronlee700618/do-14-github-actions-demo",
"id": 1483676804,
"owner_id": 50737700
}
id 是 repo 的編號、owner_id 是帳號的編號,下一步會寫進規則。
步驟 5:建身分集區
步驟 5~8 會設好兩道關卡:第一道是提供者的屬性條件(像大樓門禁,決定這張通行證換不換得到身分),第二道是服務帳戶上的授權(像房間鑰匙,決定換到的身分能扮演哪個服務帳戶)。先建放提供者的集區:
gcloud iam workload-identity-pools create do-14-pool --location=global --display-name="do-14 CI/CD pool"
Created workload identity pool [do-14-pool].
--location=global:身分集區只有 global(全球)一種位置。
步驟 6:先試試看「不加條件」建提供者
很多舊教學建 GitHub 提供者時,只設屬性對應、不設屬性條件。現在照做會直接被拒:
gcloud iam workload-identity-pools providers create-oidc do-14-github --location=global --workload-identity-pool=do-14-pool --issuer-uri="https://token.actions.githubusercontent.com" --attribute-mapping="google.subject=assertion.sub,attribute.repository=assertion.repository"
ERROR: (gcloud.iam.workload-identity-pools.providers.create-oidc) INVALID_ARGUMENT: The attribute condition must reference one of the provider's claims. For more information, see https://cloud.google.com/iam/docs/workload-identity-federation-with-deployment-pipelines#conditions

為什麼 Google 要強制?全世界的 GitHub repo 都由同一個網址 https://token.actions.githubusercontent.com 發通行證。如果提供者不設條件,任何人的 GitHub repo 都能拿通行證來你的集區換身分;再加上授權範圍給太寬,陌生人的 workflow 就能部署到你的專案。官方文件寫明:GitHub、GitLab SaaS、HCP Terraform 這類共用網址的平台,一定要用屬性條件限制成自己的組織或 repo(2026 年 12 月查)。
步驟 7:加上條件,建 GitHub 提供者
這次加上三個條件,全部符合才收:帳號 ID、repo ID 對得上,而且是 main 分支:
GH_OWNER_ID=50737700; GH_REPO_ID=1483676804
gcloud iam workload-identity-pools providers create-oidc do-14-github --location=global --workload-identity-pool=do-14-pool --display-name="GitHub Actions" --issuer-uri="https://token.actions.githubusercontent.com" --attribute-mapping="google.subject=assertion.sub,attribute.repository=assertion.repository,attribute.repository_id=assertion.repository_id,attribute.repository_owner_id=assertion.repository_owner_id,attribute.ref=assertion.ref" --attribute-condition="assertion.repository_owner_id=='$GH_OWNER_ID' && assertion.repository_id=='$GH_REPO_ID' && assertion.ref=='refs/heads/main'"
Created workload identity pool provider [do-14-github].
| 參數 | 意思 |
|---|---|
--issuer-uri | 發通行證的單位網址,Google 會去這裡拿公開的簽名鑰匙來驗證 |
--attribute-mapping | assertion.X 是通行證裡的欄位,attribute.X 是 Google 這邊的名字;google.subject 是這個身分的「主名稱」,會出現在稽核記錄 |
--attribute-condition | 用 CEL(Google 的條件運算式語法)寫規則,&& 是「而且」;不符合的通行證直接拒絕 |
查一下建好的樣子,state: ACTIVE 就是可以用了:
gcloud iam workload-identity-pools providers describe do-14-github --location=global --workload-identity-pool=do-14-pool --format='yaml(name,state,attributeCondition,oidc.issuerUri)'
attributeCondition: assertion.repository_owner_id=='50737700' && assertion.repository_id=='1483676804'
&& assertion.ref=='refs/heads/main'
name: projects/600195576280/locations/global/workloadIdentityPools/do-14-pool/providers/do-14-github
oidc:
issuerUri: https://token.actions.githubusercontent.com
state: ACTIVE

name 那一長串(projects/600195576280/.../providers/do-14-github)等一下要寫進 workflow。
步驟 8:允許這個 repo 扮演部署帳戶
最後一道授權:把「扮演 do-14-deployer」的權利(roles/iam.workloadIdentityUser,Workload Identity 使用者)給這個 repo:
gcloud iam service-accounts add-iam-policy-binding $DEPLOYER --role=roles/iam.workloadIdentityUser --member="principalSet://iam.googleapis.com/projects/$PROJECT_NUMBER/locations/global/workloadIdentityPools/do-14-pool/attribute.repository_id/$GH_REPO_ID" --format=none
Updated IAM policy for serviceAccount [do-14-deployer@dong-dong-gcp-3.iam.gserviceaccount.com].
principalSet://...attribute.repository_id/1483676804 拆開看:前面 projects/專案編號/.../workloadIdentityPools/do-14-pool 是集區的位置,最後的 attribute.repository_id/1483676804 是「repo ID 等於這個數字」,合起來就是「集區裡、repo ID 是 1483676804 的所有身分」。這樣就有兩道關卡:
- 提供者的屬性條件(步驟 7):不是這個 repo 的
main分支,連換身分都換不到 - 服務帳戶的授權(這步):換到身分之後,也只有這個 repo 能扮演
do-14-deployer
做完先等 1~5 分鐘再 push。google-github-actions/auth 的 README 寫明集區、提供者、IAM 權限要最多 5 分鐘才會生效;我實測綁完馬上跑,第一次就失敗了(「實測時的意外」第 2 條)。
用 Console 看(IAM 與管理 → Workload Identity 聯盟 → do-14-pool),右邊是提供者清單,左邊的圖是每秒成功換權杖的次數。這張是後面加上 GitLab 提供者之後拍的:

步驟 9:寫 workflow 檔
repo 裡除了說明用的 README.md,要放 6 個檔案:小網站、測試、Dockerfile、兩個排除清單,加上最重要的 workflow 檔。
檔案怎麼放進 repo,兩種方法選一種:
- 不會 git,用網頁:在 repo 首頁按 Add file → Create new file,上面的檔名欄打檔名,下面貼內容,按右上角 Commit changes 存進
main。檔名欄可以直接打路徑,例如.github/workflows/deploy.yml,打到/會自動變成資料夾 - 會 git:在自己電腦建好這些檔案,
git commit後git push到main(我是用這個方法)

6 個檔案都放好之後,repo 首頁長這樣(紅框是檔案清單,.github/workflows 資料夾裡就是 deploy.yml):

要注意:用網頁新增時,每存一個檔案就是一次 commit。deploy.yml 一進到 main,那次和之後的每次存檔都會觸發 workflow,所以最後才建 .github/workflows/deploy.yml,而且要在步驟 8 做完、等幾分鐘之後再存。
前 5 個檔案都很短,以下是這次實際用的內容(也可以直接看示範 repo)。
app.py:用 Python 內建模組寫的小網站,回一行 Hello from do-14-github-actions-demo (版本),版本從環境變數 APP_VERSION 讀(環境變數是程式啟動時從外面傳進去的設定值):
"""DevOps 系列示範用的小網站:不用任何套件,Cloud Run 會給 PORT 環境變數。"""
import os
from http.server import BaseHTTPRequestHandler, HTTPServer
VERSION = os.environ.get("APP_VERSION", "v1")
def message(version: str = VERSION) -> str:
return f"Hello from do-14-github-actions-demo ({version})"
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
body = (message() + "\n").encode("utf-8")
self.send_response(200)
self.send_header("Content-Type", "text/plain; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
if __name__ == "__main__":
port = int(os.environ.get("PORT", "8080"))
HTTPServer(("", port), Handler).serve_forever()
test_app.py:1 個測試,檢查回傳的文字對不對:
import unittest
from app import message
class TestMessage(unittest.TestCase):
def test_message_has_version(self):
self.assertEqual(message("v2"), "Hello from do-14-github-actions-demo (v2)")
if __name__ == "__main__":
unittest.main()
Dockerfile:建映像檔的食譜,從 python:3.12-slim 開始,複製 app.py、啟動它:
FROM python:3.12-slim
WORKDIR /app
COPY app.py .
ENV PORT=8080
CMD ["python", "app.py"]
.gitignore(不要 commit 進 repo 的檔案)和 .dockerignore(不要包進映像檔的檔案):兩個是各自獨立的檔案,檔名開頭都有一個點,都寫了 gha-creds-*.json。這是 google-github-actions/auth 執行時寫在工作目錄的憑證設定檔,它在 job 結束時會被自動刪掉,但同一個 job 裡後面的步驟(例如 docker build)還看得到它,所以要排除,才不會被 commit 或包進映像檔。
.gitignore 的內容:
gha-creds-*.json
__pycache__/
.dockerignore 的內容:
gha-creds-*.json
.git
.github
__pycache__
重點是第 6 個檔案 .github/workflows/deploy.yml。照做時只要改 env: 底下那 7 行的值:專案 ID、WIF_PROVIDER 裡的專案編號(步驟 7 查到的 name),還有映像檔路徑、兩個服務帳戶 email 裡的專案 ID;其他照抄:
# push 到 main 就自動測試、建映像檔、部署到 Cloud Run。
# 全程沒有服務帳戶金鑰:用 Workload Identity Federation 把 GitHub 發的 OIDC 權杖換成 Google 短效憑證。
name: deploy-cloud-run
on:
push:
branches: [main]
workflow_dispatch:
env:
PROJECT_ID: dong-dong-gcp-3
REGION: asia-east1
SERVICE: do-14-hello
IMAGE: asia-east1-docker.pkg.dev/dong-dong-gcp-3/do-14-repo/do-14-hello
WIF_PROVIDER: projects/600195576280/locations/global/workloadIdentityPools/do-14-pool/providers/do-14-github
DEPLOYER_SA: do-14-deployer@dong-dong-gcp-3.iam.gserviceaccount.com
RUNTIME_SA: do-14-run@dong-dong-gcp-3.iam.gserviceaccount.com
jobs:
test:
runs-on: ubuntu-latest
permissions:
contents: read # 測試只要讀程式碼,拿不到 Google 憑證
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v7
with:
python-version: '3.12'
- run: python -m unittest -v
deploy:
needs: test # 測試沒過就不部署
runs-on: ubuntu-latest
permissions:
contents: read
id-token: write # 允許這個 job 向 GitHub 要 OIDC 權杖(通行證)
steps:
- uses: actions/checkout@v7
- name: 看 GitHub 發的通行證寫了什麼(只印欄位,不印權杖)
run: |
JWT=$(curl -sS -H "Authorization: bearer $ACTIONS_ID_TOKEN_REQUEST_TOKEN" \
"$ACTIONS_ID_TOKEN_REQUEST_URL&audience=https://iam.googleapis.com/$WIF_PROVIDER" | jq -r .value)
python3 - "$JWT" <<'PY'
import sys, json, base64
p = sys.argv[1].split(".")[1]; p += "=" * (-len(p) % 4)
c = json.loads(base64.urlsafe_b64decode(p))
keys = ["iss", "sub", "repository", "repository_id", "repository_owner_id", "ref"]
out = {k: c[k] for k in keys}; out["valid_seconds"] = c["exp"] - c["iat"]
print(json.dumps(out, indent=2))
PY
- id: auth
name: 換 Google 短效憑證(Workload Identity Federation)
uses: google-github-actions/auth@v3
with:
project_id: ${{ env.PROJECT_ID }}
workload_identity_provider: ${{ env.WIF_PROVIDER }}
service_account: ${{ env.DEPLOYER_SA }}
token_format: access_token
- name: 確認憑證是誰、多久過期(不印權杖)
env:
ACCESS_TOKEN: ${{ steps.auth.outputs.access_token }}
run: |
jq '{type, token_url, service_account_impersonation_url}' "$GOOGLE_APPLICATION_CREDENTIALS"
curl -sS -d "access_token=$ACCESS_TOKEN" https://oauth2.googleapis.com/tokeninfo | jq '{scope, expires_in}'
- uses: docker/login-action@v4
with:
registry: asia-east1-docker.pkg.dev
username: oauth2accesstoken
password: ${{ steps.auth.outputs.access_token }}
- id: build
name: 建映像檔並推到 Artifact Registry
run: |
TAG=${GITHUB_SHA::7}
docker build -t "$IMAGE:$TAG" .
docker push "$IMAGE:$TAG"
echo "tag=$TAG" >> "$GITHUB_OUTPUT"
- id: deploy
uses: google-github-actions/deploy-cloudrun@v3
with:
service: ${{ env.SERVICE }}
region: ${{ env.REGION }}
image: ${{ env.IMAGE }}:${{ steps.build.outputs.tag }}
env_vars: APP_VERSION=${{ steps.build.outputs.tag }}
flags: --service-account=${{ env.RUNTIME_SA }}
- run: echo "部署完成:${{ steps.deploy.outputs.url }}"
逐段看重點:
permissions: id-token: write:允許這個 job 向 GitHub 要 OIDC 通行證。沒有這行,要通行證那步就會失敗。GitHub 官方文件寫明:它只開放「拿通行證」,不會給任何其他寫入權限(2026 年 12 月查)- 只在
deploy開,test不開:job 裡只要寫了permissions,沒寫到的權限就是「沒有」。test只有contents: read(讀程式碼),測試程式就算被改壞,也拿不到 Google 憑證 needs: test:deploy要等test成功才跑,測試沒過就不會部署env:裡的提供者名稱和服務帳戶 email 不是秘密:看到它們的人也換不到權杖,因為條件只認你的 repo ID。google-github-actions/auth 官方 README 的範例也是直接寫在 YAML 裡,不用放 Secretsgoogle-github-actions/auth@v3:拿通行證去 STS 換身分、扮演do-14-deployer,寫出一個憑證設定檔給後面的gcloud用。token_format: access_token是多要一張存取權杖,給docker login推映像檔用gha-creds-*.json:auth 寫出來的憑證設定檔會放在工作目錄裡,job 結束才自動刪(官方 README 提醒),所以.gitignore和.dockerignore都要排除,免得被 commit 或包進映像檔- 映像檔標記用 commit 編號前 7 碼(
${GITHUB_SHA::7}):看映像檔名稱就知道是哪一版程式碼 deploy-cloudrun@v3的flags: --service-account=...:指定網站用do-14-run的身分跑,這就是步驟 3 要給「服務帳戶使用者」的原因
action 的版本(checkout@v7、auth@v3、deploy-cloudrun@v3、login-action@v4)是寫稿時各自 GitHub 頁面上的最新主版本(2026 年 12 月查)。網路上很多範例還是 auth@v0、checkout@v2,太舊的版本跑在已經淘汰的 Node.js 上,會跳警告或不能跑。
步驟 10:push,看 GitHub Actions 跑起來
把檔案 commit、push 到 main(用網頁新增的話,deploy.yml 存進 main 那一刻就會觸發)。到 repo 的 Actions 分頁就會看到它在跑:

點第 2 次(commit 6976a9f)進去,test 7 秒、deploy 44 秒,整條 57 秒:

點 deploy 展開兩個檢查步驟,可以看到通行證寫了什麼和換到的憑證長什麼樣:

{
"iss": "https://token.actions.githubusercontent.com",
"sub": "repo:aaronlee700618@50737700/do-14-github-actions-demo@1483676804:ref:refs/heads/main",
"repository": "aaronlee700618/do-14-github-actions-demo",
"repository_id": "1483676804",
"repository_owner_id": "50737700",
"ref": "refs/heads/main",
"valid_seconds": 300
}
{
"type": "external_account",
"token_url": "https://sts.googleapis.com/v1/token",
"service_account_impersonation_url": "https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/do-14-deployer@dong-dong-gcp-3.iam.gserviceaccount.com:generateAccessToken"
}
{
"scope": "https://www.googleapis.com/auth/cloud-platform",
"expires_in": "3599"
}
這三段輸出,正好是換憑證的三個階段:
- 通行證:GitHub 發的,
iss是發行者,sub寫著帳號、repo 和分支,有效 300 秒(5 分鐘) - 憑證設定檔:
type是external_account(外部身分),先到sts.googleapis.com換身分,再到iamcredentials扮演do-14-deployer - 存取權杖:
expires_in3599 秒,大約 1 小時後失效
sub 的格式是 repo:帳號@帳號ID/repo@repoID:ref:分支,跟很多舊文章寫的 repo:帳號/repo:ref:分支 不一樣。GitHub 官方文件說明:2026 年 7 月 15 日以後建立的 repo,sub 改成包含帳號 ID 和 repo ID 的固定格式,就是為了防 repo 名稱被搶註(2026 年 12 月查)。這篇的條件用的是 repository_id,不受影響;如果你的條件寫的是 assertion.sub,要照新格式改。
google-github-actions/auth 的官方 README 在 WIF 那節警告:GitHub 通行證 5 分鐘過期,由它衍生的憑證也會在 5 分鐘後過期(2026 年 12 月查)。這篇用 token_format: access_token 另外產生的存取權杖,實測剩 3599 秒;但 deploy job 44 秒就跑完,兩種都碰不到期限。如果你的 job 會跑超過 5 分鐘,換憑證那步要放在真正用到之前,不要一開頭就換。
步驟 11:打開網址
部署好的服務一開始打開是 403(拒絕存取):
URL=$(gcloud run services describe do-14-hello --region=$REGION --format='value(status.url)'); echo $URL; curl -s -o /dev/null -w '%{http_code}\n' $URL
https://do-14-hello-b5j2wtbgca-de.a.run.app
403
這是故意的。Cloud Run 預設只讓有權限的人呼叫;要變成公開網站,要關掉「叫用者 IAM 檢查」(Invoker IAM check),而這個動作需要 run.services.setIamPolicy 權限,官方文件寫在 Cloud Run 管理員(roles/run.admin)裡。部署帳戶只有開發人員,它沒辦法自己把服務改成公開,這正是最小權限想要的效果:管線只能「換版本」,不能「改誰看得到」。
所以這步由專案擁有者(你自己)在 Cloud Shell 做一次就好,之後的部署會保留這個設定。公司的專案如果有組織政策 constraints/run.managed.requireInvokerIam(預設沒開),這個指令會被拒絕,不是你打錯,要找組織管理員處理:
gcloud run services update do-14-hello --region=$REGION --no-invoker-iam-check
curl -s $URL
Updating...
Done.
Service [do-14-hello] has been updated.
Hello from do-14-github-actions-demo (7b153d9)

括號裡的 7b153d9 就是第 1 次 push 的 commit 編號前 7 碼。再看每個版本是誰部署的:
gcloud run revisions list --service=do-14-hello --region=$REGION --format='table(metadata.name,metadata.annotations."serving.knative.dev/creator":label=DEPLOYED_BY,metadata.creationTimestamp.date("%m/%d %H:%M",tz=Asia/Taipei):label=CREATED)'
NAME DEPLOYED_BY CREATED
do-14-hello-00001-nsq do-14-deployer@dong-dong-gcp-3.iam.gserviceaccount.com 12/04 23:34
部署者是 do-14-deployer,不是我的個人帳號。
步驟 12:確認真的沒有金鑰
gcloud iam service-accounts keys list --iam-account=$DEPLOYER --managed-by=user; gcloud iam service-accounts keys list --iam-account=$DEPLOYER
Listed 0 items.
KEY_ID CREATED_AT EXPIRES_AT DISABLED DISABLE_REASON EXTENDED_STATUS
a5270ac151369e04a70cd40d48c9cb27cad1209a 2026-12-04T15:30:27Z 2028-12-03T15:30:27Z

- 第一行
--managed-by=user(使用者自己建立、可以下載的金鑰):0 把 - 不加篩選看到的那一把是 Google 自己管理的金鑰,用來簽發短效憑證。官方文件寫明:這種金鑰的私鑰一直由 Google 保管,任何人都拿不到,而且 Google 會定期自動換(2026 年 12 月查)
步驟 13:換一個分支跑,看它被擋下
建一個 try-other-branch 分支 push 上去,在 Actions 分頁選 deploy-cloud-run → Run workflow → 選這個分支手動執行(workflow_dispatch 就是允許手動執行):

Error: google-github-actions/auth failed with: failed to generate Google Cloud federated token for //iam.googleapis.com/projects/600195576280/locations/global/workloadIdentityPools/do-14-pool/providers/do-14-github: {"error":"unauthorized_client","error_description":"The given credential is rejected by the attribute condition."}
同一個 repo、同一份 workflow,只是分支不同,在 STS 那關就被屬性條件拒絕,建映像檔、部署都沒跑。這就是「只有 main 能上線」:開發中的分支、別人送來的 PR 分支,都碰不到正式環境。
步驟 14:用稽核記錄查「是哪個 repo 部署的」
Cloud Audit Logs(稽核記錄)是 Google Cloud 記錄「誰在什麼時候對哪個資源做了什麼」的服務。其中「管理活動」記錄(Admin Activity)預設就開著、不能關,部署 Cloud Run 會記在這裡。下面這段把最近 1 小時對 do-14-hello 的操作撈出來,換成台灣時間,sed 那段只是把我的 email 遮掉。指令很長,是因為 jq 要把記錄排成好讀的格式,照貼就好,重點看輸出:
gcloud logging read 'logName="projects/dong-dong-gcp-3/logs/cloudaudit.googleapis.com%2Factivity" AND protoPayload.serviceName="run.googleapis.com" AND protoPayload.resourceName:"do-14-hello"' --freshness=1h --limit=5 --format=json | jq -r '.[] | .protoPayload as $p | "\(.timestamp | sub("\\.[0-9]+Z$";"Z") | fromdateiso8601 + 28800 | strftime("%H:%M:%S")) \($p.methodName | split(".") | last)\n 誰:\($p.authenticationInfo.principalEmail)\n 代表:\($p.authenticationInfo.serviceAccountDelegationInfo[0].principalSubject // "(自己操作,沒有代表別人)")"' | sed -E 's/[a-z0-9.]+@gmail\.com/你的帳號/g'
23:37:00 ReplaceService
誰:do-14-deployer@dong-dong-gcp-3.iam.gserviceaccount.com
代表:principal://iam.googleapis.com/projects/600195576280/locations/global/workloadIdentityPools/do-14-pool/subject/repo:aaronlee700618@50737700/do-14-github-actions-demo@1483676804:ref:refs/heads/main
23:35:52 ReplaceService
誰:你的帳號
代表:(自己操作,沒有代表別人)
23:34:41 CreateService
誰:do-14-deployer@dong-dong-gcp-3.iam.gserviceaccount.com
代表:principal://iam.googleapis.com/projects/600195576280/locations/global/workloadIdentityPools/do-14-pool/subject/repo:aaronlee700618@50737700/do-14-github-actions-demo@1483676804:ref:refs/heads/main

- 23:34:41 CreateService:第 1 次部署,建立服務
- 23:35:52 ReplaceService:我手動關掉叫用者 IAM 檢查(步驟 11)
- 23:37:00 ReplaceService:第 2 次部署
「代表」那欄來自 serviceAccountDelegationInfo(服務帳戶代理資訊),直接寫出是哪個 repo、哪個分支扮演了部署帳戶。用金鑰檔的話,記錄只會看到服務帳戶的名字,查不出是哪條管線、哪台機器用了那把金鑰。
動手做:GitLab CI 用 WIF 部署同一個服務
GitLab 是另一個常見的程式碼平台,CI/CD 叫 GitLab CI,設定檔是 repo 根目錄的 .gitlab-ci.yml;跑 job 的機器叫 GitLab Runner,要自己裝。這個系列在 GCP 開了一台 VM(虛擬機器,在雲端租的一台電腦)自架 GitLab(gitlab-ee 套件、版本 19.6.2,網址 https://35-229-139-139.sslip.io),Runner 也裝在同一台。
- 沒有自架 GitLab 的話,這段可以只看不做:GitHub 那段已經是完整流程,這段是給公司用 GitLab 的人對照寫法;只想學 GitHub 的話,直接跳到「金鑰、WIF+GitHub、WIF+GitLab 一張表」
- 自己架的話會花錢:這台 VM 是 e2-standard-4(4 vCPU、16 GB 記憶體)加 50 GB 開機磁碟,開著就按秒計費。我建立時加了
--max-run-duration=8h --instance-termination-action=DELETE,8 小時後自動刪除;你自己架的話,用完一定要刪 VM 和磁碟 - sslip.io 是一個免費的網域服務,網址裡寫 IP,就會解析到那個 IP,不用買網域;再用 Let’s Encrypt 申請免費的 HTTPS 憑證
- 為什麼 GitLab 一定要能從網路上連到:Google STS 驗通行證時,會去 GitLab 拿公開的簽名鑰匙。GitLab 在公司內網、外面連不到的話,可以改成把鑰匙檔上傳給提供者(
--jwk-json-path) - 流程跟 GitHub 一樣:GitLab 發通行證 → STS 驗證、看條件 → 扮演服務帳戶 → 部署。差別在 GitLab 沒有官方的「auth action」,要用
gcloud自己產生憑證設定檔
步驟 1:確認 GitLab 有公開的 OIDC 資訊
OIDC 規定發行者要在 /.well-known/openid-configuration 放一份公開的說明:
GL_URL=https://35-229-139-139.sslip.io; curl -s $GL_URL/.well-known/openid-configuration | jq '{issuer, jwks_uri, id_token_signing_alg_values_supported}'
{
"issuer": "https://35-229-139-139.sslip.io",
"jwks_uri": "https://35-229-139-139.sslip.io/oauth/discovery/keys",
"id_token_signing_alg_values_supported": [
"RS256"
]
}
issuer 是發行者、jwks_uri 是簽名鑰匙的位置。從 Cloud Shell 打得到,Google 就打得到。
步驟 2:在同一個集區加 GitLab 提供者
gcloud iam workload-identity-pools providers create-oidc do-14-gitlab --location=global --workload-identity-pool=do-14-pool --display-name="Self-managed GitLab" --issuer-uri="$GL_URL/" --allowed-audiences="$GL_URL" --attribute-mapping="google.subject=assertion.sub,attribute.project_path=assertion.project_path,attribute.project_id=assertion.project_id,attribute.ref=assertion.ref" --attribute-condition="assertion.project_path=='root/do-14-gitlab-ci' && assertion.ref=='main'"
Created workload identity pool provider [do-14-gitlab].
跟 GitHub 不一樣的地方,照 GitLab 官方文件(2026 年 12 月查):
| 設定 | GitLab 要怎麼填 | 為什麼 |
|---|---|---|
--issuer-uri | GitLab 網址,結尾要加 / | GitLab 文件規定 |
--allowed-audiences | GitLab 網址,結尾不加 / | 通行證的 aud(發給誰)要跟這裡一樣才收 |
| 屬性條件 | project_path(專案路徑)+ref(分支或標籤的名稱) | 只收 root/do-14-gitlab-ci 專案、名稱是 main 的 ref |
這篇實測的條件為了好讀做了簡化,正式環境要再補兩個地方:
- 加上
ref_type=='branch':GitLab 通行證裡的ref只是名稱,分支和標籤(tag,替某個版本貼的名牌)都可能叫main;ref_type欄位才分得出是branch還是tag(GitLab 官方文件,2026 年 12 月查)。只比ref=='main'的話,有人建一個叫main的標籤,從標籤跑的 job 也會通過 - 改用數字的
project_id:Google 官方文件建議 GitLab 用數字的project_id、namespace_id,原因跟 GitHub 用 repo ID 一樣,專案刪掉後,路徑可能被別人重新建立
另外把 main 設成受保護分支(protected branch,只有指定的人能 push)。條件寫起來像下面這樣,12345 換成你的專案 ID(專案 Settings → General 看得到)。提供者已經建好的話,用 update-oidc 改條件就好,不用刪掉重建。這行我沒有實測,下一步授權那行的 attribute.project_path/root/do-14-gitlab-ci 也要跟著換成 attribute.project_id/12345:
gcloud iam workload-identity-pools providers update-oidc do-14-gitlab --location=global --workload-identity-pool=do-14-pool --attribute-condition="assertion.project_id=='12345' && assertion.ref=='main' && assertion.ref_type=='branch'"
步驟 3:建 GitLab 專用的部署帳戶
官方建議每條管線一個服務帳戶,GitLab 另外建 do-14-gl-deployer,給角色、允許 GitLab 專案扮演它:
GL_DEPLOYER=do-14-gl-deployer@$PROJECT_ID.iam.gserviceaccount.com
gcloud iam service-accounts create do-14-gl-deployer --display-name="do-14 GitLab CI 部署用"
gcloud projects add-iam-policy-binding $PROJECT_ID --member=serviceAccount:$GL_DEPLOYER --role=roles/run.developer --condition=None --format=none
gcloud iam service-accounts add-iam-policy-binding $RUNTIME --member=serviceAccount:$GL_DEPLOYER --role=roles/iam.serviceAccountUser --format=none
gcloud iam service-accounts add-iam-policy-binding $GL_DEPLOYER --role=roles/iam.workloadIdentityUser --member="principalSet://iam.googleapis.com/projects/$PROJECT_NUMBER/locations/global/workloadIdentityPools/do-14-pool/attribute.project_path/root/do-14-gitlab-ci" --format=none
Created service account [do-14-gl-deployer].
Service account email: do-14-gl-deployer@dong-dong-gcp-3.iam.gserviceaccount.com
ERROR: Policy modification failed. For a binding with condition, run "gcloud alpha iam policies lint-condition" to identify issues in condition.
ERROR: (gcloud.projects.add-iam-policy-binding) INVALID_ARGUMENT: Service account do-14-gl-deployer@dong-dong-gcp-3.iam.gserviceaccount.com does not exist.
ERROR: Policy modification failed. For a binding with condition, run "gcloud alpha iam policies lint-condition" to identify issues in condition.
ERROR: (gcloud.iam.service-accounts.add-iam-policy-binding) INVALID_ARGUMENT: Service account do-14-gl-deployer@dong-dong-gcp-3.iam.gserviceaccount.com does not exist.
Updated IAM policy for serviceAccount [do-14-gl-deployer@dong-dong-gcp-3.iam.gserviceaccount.com].

服務帳戶剛建好,其他服務還「看不到」它(IAM 的變更要一點時間傳到各處),所以馬上綁角色的兩條失敗了,綁在服務帳戶自己身上的那條成功。等幾秒、重跑失敗的兩條就好:
gcloud projects add-iam-policy-binding $PROJECT_ID --member=serviceAccount:$GL_DEPLOYER --role=roles/run.developer --condition=None --format=none
gcloud iam service-accounts add-iam-policy-binding $RUNTIME --member=serviceAccount:$GL_DEPLOYER --role=roles/iam.serviceAccountUser --format=none
Updated IAM policy for project [dong-dong-gcp-3].
Updated IAM policy for serviceAccount [do-14-run@dong-dong-gcp-3.iam.gserviceaccount.com].
步驟 4:裝 GitLab Runner、註冊到專案
Runner 用 shell 執行器(executor):job 直接在 Runner 那台機器的 bash 裡跑,最簡單,但機器上要先有 job 會用到的工具(這台有 gcloud 和 python3)。安裝照 GitLab 官方文件加套件庫再 apt-get install gitlab-runner,裝好的版本是 19.6.2。
註冊的做法:專案的 Settings → CI/CD → Runners → Create project runner,GitLab 會給一串 glrt- 開頭的 Runner 驗證權杖,再到機器上跑:
sudo gitlab-runner register --non-interactive --url "https://你的 GitLab 網址" --token "glrt-你拿到的權杖" --executor shell --description do-14-shell-runner
這串 Runner 權杖是秘密,拿到的人可以冒充你的 Runner 接 job,不要貼到截圖、聊天群組或 log 裡。註冊好之後,專案的 Runners 頁會看到它在線上(截圖裡 Runner 編號後面的短代碼是權杖的開頭,我遮掉了):

Runner 裝在 GCE(Compute Engine)的 VM 上,本來也可以直接用 VM 自己的服務帳戶。但那樣同一台 Runner 上所有專案的 job 都拿到同一個身分;用 WIF 才能做到「只有 root/do-14-gitlab-ci 的 main 分支能部署」。
步驟 5:寫 .gitlab-ci.yml
這台 Runner 沒裝 Docker,所以 GitLab 這條不建映像檔,直接部署 GitHub 那條建好的同一個映像檔(6976a9f),只把版本文字改成 gitlab- 開頭,好分辨是哪邊部署的:
# push 到 main 就自動測試、部署到 Cloud Run。
# 全程沒有服務帳戶金鑰:GitLab 發的 ID 權杖 → Workload Identity Federation → Google 短效憑證。
# 這台 Runner 沒有 Docker,所以部署 GitHub 那條建好的同一個映像檔,只換 APP_VERSION。
stages: [test, deploy]
variables:
PROJECT_ID: dong-dong-gcp-3
REGION: asia-east1
SERVICE: do-14-hello
IMAGE: asia-east1-docker.pkg.dev/dong-dong-gcp-3/do-14-repo/do-14-hello:6976a9f
WIF_PROVIDER: projects/600195576280/locations/global/workloadIdentityPools/do-14-pool/providers/do-14-gitlab
DEPLOYER_SA: do-14-gl-deployer@dong-dong-gcp-3.iam.gserviceaccount.com
RUNTIME_SA: do-14-run@dong-dong-gcp-3.iam.gserviceaccount.com
test:
stage: test
script:
- python3 -m unittest -v
deploy:
stage: deploy
rules:
- if: $CI_COMMIT_BRANCH == "main"
id_tokens:
GITLAB_OIDC_TOKEN: # GitLab 只在這個 job 發 ID 權杖(通行證)
aud: https://35-229-139-139.sslip.io
script:
- echo "$GITLAB_OIDC_TOKEN" > .gitlab_oidc_token
- |
# 看通行證寫了什麼(只印欄位,不印權杖)
python3 - <<'PY'
import json, base64
p = open(".gitlab_oidc_token").read().strip().split(".")[1]; p += "=" * (-len(p) % 4)
c = json.loads(base64.urlsafe_b64decode(p))
out = {k: c.get(k) for k in ["iss", "sub", "aud", "project_path", "ref", "ref_type"]}
out["valid_seconds"] = c["exp"] - c["iat"]
print(json.dumps(out, indent=2))
PY
- gcloud iam workload-identity-pools create-cred-config "$WIF_PROVIDER" --service-account="$DEPLOYER_SA" --credential-source-file=.gitlab_oidc_token --output-file=.gcp_creds.json
- export CLOUDSDK_AUTH_CREDENTIAL_FILE_OVERRIDE="$PWD/.gcp_creds.json"
- gcloud run deploy "$SERVICE" --project="$PROJECT_ID" --region="$REGION" --image="$IMAGE" --service-account="$RUNTIME_SA" --update-env-vars="APP_VERSION=gitlab-$CI_COMMIT_SHORT_SHA"
after_script:
- rm -f .gitlab_oidc_token .gcp_creds.json
| 寫法 | 意思 |
|---|---|
rules: if: $CI_COMMIT_BRANCH == "main" | 只讓 deploy job 在 main 分支執行。這只是「不要在別的分支跑」,不是安全關卡:能改 CI 檔的人也能改掉這行,真正擋人的是提供者的屬性條件和受保護分支 |
id_tokens: | GitLab 版的 id-token: write:寫在哪個 job,GitLab 才發通行證給那個 job,放進 GITLAB_OIDC_TOKEN 變數 |
aud: | 通行證「發給誰」,要跟提供者的 --allowed-audiences 一樣 |
create-cred-config | gcloud 產生「去哪裡拿通行證、換成哪個服務帳戶」的設定檔,內容不含任何秘密 |
CLOUDSDK_AUTH_CREDENTIAL_FILE_OVERRIDE | 叫這個 job 裡的 gcloud 改用這個設定檔登入 |
after_script | 不管成功失敗都會跑,把通行證和設定檔刪掉 |
GitLab 官方文件的範例是用 curl 自己打 STS 換權杖;這篇改用 gcloud iam workload-identity-pools create-cred-config,一行就產生設定檔,後面 gcloud 會自己換。另外,舊的 CI_JOB_JWT_V2 變數在 GitLab 17.0 已經移除,網路上舊文章用它的,要改成 id_tokens。
步驟 6:push,第一次部署失敗
push 之後 test 過了,deploy 失敗:
ERROR: (gcloud.run.deploy) PERMISSION_DENIED: Permission 'artifactregistry.repositories.downloadArtifacts' denied on resource '//artifactregistry.googleapis.com/projects/dong-dong-gcp-3/locations/asia-east1/repositories/do-14-repo' (or it may not exist).
換身分是成功的(失敗的話,錯誤會出在換憑證那一步,不會走到部署),卡在讀不到映像檔。GitHub 那邊的部署帳戶有存放區的「寫入者」,寫入者本來就包含讀取,所以沒事;GitLab 這個帳戶只部署、不推映像檔,我漏給「讀取者」。這也是 Cloud Run 官方部署角色第 3 個:映像檔所在存放區的 Artifact Registry 讀取者。補上:
gcloud artifacts repositories add-iam-policy-binding do-14-repo --location=$REGION --member=serviceAccount:$GL_DEPLOYER --role=roles/artifactregistry.reader --format=none
Updated IAM policy for repository [do-14-repo].
步驟 7:重跑,成功
在 job 頁按 Retry,這次通過,整條管線 13 秒(排隊 5 秒):

deploy job 的紀錄裡可以看到 GitLab 發的通行證,和 gcloud 部署的過程:

{
"iss": "https://35-229-139-139.sslip.io",
"sub": "project_path:root/do-14-gitlab-ci:ref_type:branch:ref:main",
"aud": "https://35-229-139-139.sslip.io",
"project_path": "root/do-14-gitlab-ci",
"ref": "main",
"ref_type": "branch",
"valid_seconds": 3600
}
$ gcloud iam workload-identity-pools create-cred-config "$WIF_PROVIDER" --service-account="$DEPLOYER_SA" --credential-source-file=.gitlab_oidc_token --output-file=.gcp_creds.json
Created credential configuration file [.gcp_creds.json].
(中間省略)
Service [do-14-hello] revision [do-14-hello-00003-6bb] has been deployed and is serving 100 percent of traffic.
GitLab 的通行證有效 3600 秒,比 GitHub 的 300 秒長很多。GitLab 官方文件寫明:ID 權杖的有效時間等於 job 的逾時設定,沒設逾時才是 5 分鐘(2026 年 12 月查)。這個專案的逾時是預設的 1 小時,所以是 3600 秒。
回 Cloud Shell 確認網站和部署者:
curl -s $URL; gcloud run revisions list --service=do-14-hello --region=$REGION --format='table(metadata.name,metadata.annotations."serving.knative.dev/creator":label=DEPLOYED_BY,metadata.creationTimestamp.date("%m/%d %H:%M",tz=Asia/Taipei):label=CREATED)'
Hello from do-14-github-actions-demo (gitlab-757a3fac)
NAME DEPLOYED_BY CREATED
do-14-hello-00003-6bb do-14-gl-deployer@dong-dong-gcp-3.iam.gserviceaccount.com 12/05 00:04
do-14-hello-00002-s55 do-14-deployer@dong-dong-gcp-3.iam.gserviceaccount.com 12/04 23:37
do-14-hello-00001-nsq do-14-deployer@dong-dong-gcp-3.iam.gserviceaccount.com 12/04 23:34

網站文字變成 gitlab-757a3fac,第 3 版的部署者是 GitLab 專用的 do-14-gl-deployer。同一個服務,兩條管線各用各的身分,從部署者就分得出來。
稽核記錄只撈「有代表別人」的操作:
gcloud logging read 'logName="projects/dong-dong-gcp-3/logs/cloudaudit.googleapis.com%2Factivity" AND protoPayload.serviceName="run.googleapis.com" AND protoPayload.resourceName:"do-14-hello" AND protoPayload.authenticationInfo.serviceAccountDelegationInfo:*' --freshness=2h --limit=2 --format=json | jq -r '.[] | .protoPayload as $p | "\(.timestamp | sub("\\.[0-9]+Z$";"Z") | fromdateiso8601 + 28800 | strftime("%H:%M:%S")) \($p.methodName | split(".") | last)\n 誰:\($p.authenticationInfo.principalEmail)\n 代表:\($p.authenticationInfo.serviceAccountDelegationInfo[0].principalSubject)"'
00:04:02 ReplaceService
誰:do-14-gl-deployer@dong-dong-gcp-3.iam.gserviceaccount.com
代表:principal://iam.googleapis.com/projects/600195576280/locations/global/workloadIdentityPools/do-14-pool/subject/project_path:root/do-14-gitlab-ci:ref_type:branch:ref:main
23:59:22 ReplaceService
誰:do-14-gl-deployer@dong-dong-gcp-3.iam.gserviceaccount.com
代表:principal://iam.googleapis.com/projects/600195576280/locations/global/workloadIdentityPools/do-14-pool/subject/project_path:root/do-14-gitlab-ci:ref_type:branch:ref:main

23:59:22 那筆是步驟 6 失敗的那次(我另外查了那筆的狀態碼是 7,也就是 PERMISSION_DENIED)。稽核記錄連失敗的嘗試都會記,而且一樣寫出是哪個 GitLab 專案、哪個分支。
實測時的意外
1. 不加屬性條件,提供者建不起來:2023 年的中文教學建 GitHub 提供者只設屬性對應,現在照做會得到
INVALID_ARGUMENT: The attribute condition must reference one of the provider's claims。Google 已經把 GitHub 這類共用網址平台的屬性條件改成必填(步驟 6)。2. 綁完權限馬上 push,第一次換憑證 403:GitHub 第 1 次跑在換憑證那步失敗,
Permission 'iam.serviceAccounts.getAccessToken' denied。設定是對的,只是 IAM 綁定還沒傳開;約 1 分鐘後按 Re-run failed jobs 就過了。官方 README 寫明集區、提供者、權限要等最多 5 分鐘才會生效。3. 部署完網址是 403:部署帳戶沒有改存取權限的權限,沒辦法自己把服務設成公開,要擁有者手動關一次叫用者 IAM 檢查(步驟 11)。
4. 剛建好的服務帳戶,馬上綁角色說它不存在:
Service account ... does not exist,等幾秒重跑就好(GitLab 步驟 3)。5. GitLab 部署帳戶少了存放區讀取者:換身分成功,但
artifactregistry.repositories.downloadArtifacts被拒。只部署、不推映像檔的帳戶,也要能讀映像檔(GitLab 步驟 6)。6. GitLab 第一次 push 自己跑了一條管線:還沒放
.gitlab-ci.yml時,自架 GitLab 預設開著 Auto DevOps(自動幫你猜要怎麼建置的功能),跑了一條 build、test、code_quality 都失敗的管線。放了.gitlab-ci.yml之後就照我們的檔案跑。7.
gitlab-runner unregister不會刪掉 GitLab 上的 Runner:清理時跑了解除註冊,訊息是Unregistering runner manager from GitLab succeeded,只刪掉「這台機器」的登記,專案 Runners 頁上的 Runner 還在,要另外按刪除(做法在「用完記得刪」那節)。
金鑰、WIF+GitHub、WIF+GitLab 一張表
只想抓重點的話,看前兩列就好:用金鑰要一直保管一個永不過期的檔案,用 WIF 沒有東西要保管,通行證幾分鐘到 1 小時就失效。
| 服務帳戶金鑰(JSON 檔) | WIF+GitHub Actions | WIF+自架 GitLab CI | |
|---|---|---|---|
| 要保管的秘密 | 金鑰檔,放 Secrets | 沒有 | 沒有 |
| 通行證有效時間 | 金鑰預設永不過期 | 300 秒(實測) | 等於 job 逾時,3600 秒(實測) |
| Google 憑證有效時間 | 用金鑰隨時換 | 存取權杖 3599 秒(實測) | 預設約 1 小時(這條沒印出來量) |
| 限制誰能用 | 拿到檔案就能用 | repo ID+main 分支 | 專案路徑+main(正式環境改專案 ID、加 ref_type) |
| 管線裡怎麼寫 | 讀金鑰檔登入 | id-token: write+google-github-actions/auth@v3 | id_tokens:+gcloud iam workload-identity-pools create-cred-config |
| 稽核記錄看得到 | 只有服務帳戶名稱 | 服務帳戶+repo+分支 | 服務帳戶+專案+分支 |
| 這次實測部署 job | 沒測 | 44 秒(含建映像檔) | 11 秒(只部署) |
這次碰到的錯誤訊息對照(都是實際跑出來的):
| 情境 | 錯誤訊息 | 怎麼辦 |
|---|---|---|
| 提供者沒加屬性條件 | INVALID_ARGUMENT: The attribute condition must reference one of the provider's claims. | 加 --attribute-condition |
不是 main 分支 | unauthorized_client:The given credential is rejected by the attribute condition. | 預期中的擋下 |
| 剛綁完就跑 | Permission 'iam.serviceAccounts.getAccessToken' denied | 等幾分鐘重跑 |
| 剛建服務帳戶就綁角色 | Service account ... does not exist. | 等幾秒重跑 |
| 部署帳戶讀不到映像檔 | Permission 'artifactregistry.repositories.downloadArtifacts' denied | 給存放區讀取者 |
| 刪掉的集區 30 天內重建 | ALREADY_EXISTS: Requested entity already exists | 換名字,或用 undelete 救回 |
GKE 的 Workload Identity 跟這篇的 WIF 差在哪
名字幾乎一樣,用的地方不同。容器系列第 26 篇〈Workload Identity 是什麼?GKE 不用金鑰安全存取 GCP 服務〉講的是 GKE 叢集裡的 Pod(GKE 上跑程式的最小單位)怎麼拿身分;這篇講的是 GCP 外面的程式(GitHub、GitLab、AWS、Azure、自己的機房)怎麼拿身分。

GKE 的那個在 2024 年改名為 Workload Identity Federation for GKE,名字也有 Federation,因為底層是同一套:拿「別處發的身分」換 Google 短效憑證。考試看到「GKE 上的 Pod 要存取 Cloud Storage」選 GKE 那個;看到「GitHub Actions、其他雲、地端程式要存取 GCP」選這篇的 WIF。
用完記得刪
這篇建了:Cloud Run 服務、Artifact Registry 存放區、3 個服務帳戶、身分集區和 2 個提供者、專案層級的 2 條 IAM 授權,還有 GitLab Runner。不刪會怎麼計費:
- Cloud Run:沒人打網址時縮到 0 台,不收運算費
- Artifact Registry:每個帳單帳戶每月前 0.5 GB 免費,超過每 GB 每小時 0.000136986 美元(2026 年 12 月查官方定價)。算一次:0.000136986 × 730 小時 ≈ 每 GB 每月 0.1 美元。這篇只有一個小映像檔,但存放區不刪,每次 push 的映像檔都會一直累積
- 服務帳戶、身分集區、提供者:不收費,但留著就是「一扇沒人看管的門」,該刪
先拿掉專案層級的授權(存放區、服務帳戶上的授權會跟著資源一起刪掉):
for sa in $DEPLOYER $GL_DEPLOYER; do gcloud projects remove-iam-policy-binding $PROJECT_ID --member=serviceAccount:$sa --role=roles/run.developer --condition=None --format=none; done
Updated IAM policy for project [dong-dong-gcp-3].
Updated IAM policy for project [dong-dong-gcp-3].
為什麼先拿授權再刪帳戶?服務帳戶刪掉後,專案授權裡會留下 deleted:serviceAccount:... 的殘留項目,先拿掉比較乾淨。
刪 Cloud Run 服務和存放區(--quiet 是不要再問「確定嗎」):
gcloud run services delete do-14-hello --region=$REGION --quiet; gcloud artifacts repositories delete do-14-repo --location=$REGION --quiet
Deleting [do-14-hello]...
............done.
Deleted service [do-14-hello].
Delete request issued for: [do-14-repo]
Waiting for operation [projects/dong-dong-gcp-3/locations/asia-east1/operations/160d4f18-cba8-4f38-8f8e-92e652ced625] to complete...
.....done.
Deleted repository [do-14-repo].
刪 3 個服務帳戶:
for sa in $DEPLOYER $GL_DEPLOYER $RUNTIME; do gcloud iam service-accounts delete $sa --quiet; done
deleted service account [do-14-deployer@dong-dong-gcp-3.iam.gserviceaccount.com]
deleted service account [do-14-gl-deployer@dong-dong-gcp-3.iam.gserviceaccount.com]
deleted service account [do-14-run@dong-dong-gcp-3.iam.gserviceaccount.com]
刪提供者和集區:
for p in do-14-github do-14-gitlab; do gcloud iam workload-identity-pools providers delete $p --location=global --workload-identity-pool=do-14-pool --quiet; done; gcloud iam workload-identity-pools delete do-14-pool --location=global --quiet
Deleted workload identity pool provider [do-14-github].
Deleted workload identity pool provider [do-14-gitlab].
Deleted workload identity pool [do-14-pool].

刪掉的集區 30 天內不能用同一個名字重建。看一下刪掉的集區,再試著建同名的:
gcloud iam workload-identity-pools list --location=global --show-deleted --filter='name~do-14' --format='table(name.basename():label=POOL,state,expireTime.date("%Y-%m-%d",tz=Asia/Taipei):label=PURGE_AFTER)'; gcloud iam workload-identity-pools create do-14-pool --location=global
POOL STATE PURGE_AFTER
do-14-pool DELETED 2027-01-04
ERROR: (gcloud.iam.workload-identity-pools.create) ALREADY_EXISTS: Requested entity already exists

官方文件寫明:刪掉的集區 30 天內可以用 gcloud iam workload-identity-pools undelete 救回,30 天後才永久刪除,永久刪除前不能重用這個名字(2026 年 12 月查)。照著做第二次,名字換一個(例如 do-14-pool2)就好。
GitLab Runner:在 Runner 那台機器上解除註冊,再到專案 Settings → CI/CD → Runners 按垃圾桶刪掉 Runner:
sudo gitlab-runner unregister --name do-14-shell-runner
Unregistering runner manager from GitLab succeeded runner=(略) runner_name=do-14-shell-runner
Updated /etc/gitlab-runner/config.toml
GitHub repo:裡面沒有任何秘密,可以留著當範本;要刪就到 repo 的 Settings 最下面按 Delete this repository。
API 我沒關:sts.googleapis.com 這些 API 開著不收費,同專案別的服務也可能在用。
證照會怎麼考
Professional Cloud DevOps Engineer 考試 2 小時、50~60 題選擇題、報名費 200 美元,考試語言英文和日文(2026 年 11 月查官方考試頁)。2026 年 11 月 23 日起適用新版考綱。
| 考綱小節(新版) | 原文重點 | 這篇對應的地方 |
|---|---|---|
| 2.3 管理管線設定與秘密 | 設定與秘密管理(Secret Manager、Workload Identity Federation…)、管理短效憑證(新版新增) | 整篇:5 分鐘通行證換 1 小時權杖、0 把金鑰 |
| 1.3 設計 CI/CD 架構 | 混合雲、多雲環境;Git 等第三方工具;CI/CD 工具的安全性 | GitHub、GitLab 兩條管線接 GCP |
| 1.1 資源階層設計 | 建立與管理服務帳戶 | 部署帳戶、執行帳戶分開,每條管線一個 |
| 2.2 實作與管理管線 | 稽核和追蹤部署(Cloud Audit Logs) | 步驟 14 查出是哪個 repo、哪個分支 |
| 2.4 保護部署管線 | 依環境設計 IAM 政策 | 屬性條件只放行 main、最小權限角色 |
新版 2.3 跟舊版比,只多了最後一條「Managing short-lived credentials」,Workload Identity Federation 舊版就列在 2.3 裡了。
看到這些字,就想到這個(情境題的判斷關鍵字):
| 題目關鍵字 | 想到 |
|---|---|
| 「GitHub Actions/GitLab/Jenkins 要部署到 GCP」「不想存長期憑證」 | Workload Identity Federation+扮演服務帳戶 |
| 「組織政策禁止建立服務帳戶金鑰」 | iam.disableServiceAccountKeyCreation,改用 WIF |
| 「只允許某個 repo、某個分支部署」 | 提供者的屬性條件(attribute condition) |
| 「防止 repo 改名或刪除後被冒用」 | 條件用數字 ID(repository_id、project_id),不用名稱 |
| 「要知道是哪條管線部署的」 | Cloud Audit Logs 的 serviceAccountDelegationInfo |
| 「GKE 上的 Pod 要存取 GCP 服務」 | Workload Identity Federation for GKE(不是這篇的設定) |
| 「CI 要用資料庫密碼、第三方 API 金鑰」 | Secret Manager;WIF 解決的是「登入 GCP」,不是所有秘密 |
| 「部署帳戶權限最小化」 | run.developer+服務帳戶使用者+存放區讀取,不給 run.admin、不給編輯者 |
考試範圍完整的準備地圖在第 1 篇:GCP DevOps 證照怎麼考?2026 新版考綱、比重與準備地圖。
面試會怎麼問
- 「你們的 CI/CD 怎麼拿雲端權限?」:說「用 Workload Identity Federation,CI 平台發 OIDC 權杖,Google 驗證後換短效憑證,repo 和 Secrets 裡沒有金鑰」,再補一句「提供者有屬性條件,只放行指定 repo 的 main 分支」
- 「為什麼不用服務帳戶金鑰?」:金鑰預設永不過期、外流了誰拿到都能用,稽核記錄也查不出是誰在用;短效憑證 1 小時就失效,記錄裡看得到是哪個 repo
- 「
id-token: write是什麼?會不會很危險?」:只是允許 job 向 GitHub 要 OIDC 權杖,不給其他寫入權限;只開在需要部署的 job - 「部署帳戶要給哪些角色?」:Cloud Run 開發人員、執行身分的服務帳戶使用者、存放區讀取(要推映像檔就給寫入);不給管理員,所以管線不能改服務的公開設定
- 「GitHub 和 GitLab 的做法差在哪?」:觀念一樣,差在拿通行證的寫法(
id-token: write對id_tokens:)、通行證有效時間(5 分鐘對 job 逾時)、條件欄位(repo ID 對 project ID),GitLab 的發行者網址結尾要加斜線
常見問答
GitHub Actions 部署 GCP 一定要用 Workload Identity Federation 嗎?
不一定,但它是 Google 官方推薦的做法。舊做法是把服務帳戶金鑰(JSON 檔)放進 GitHub Secrets,金鑰預設永不過期,外流了誰拿到都能用;而且 2024 年 5 月 3 日以後建立的 GCP 機構,預設就禁止建立金鑰。用 WIF,repo 和 Secrets 裡都沒有金鑰,GitHub 每次發一張 5 分鐘的通行證,換成 1 小時就失效的 Google 憑證。
Workload Identity Federation 要錢嗎?
不用。WIF 屬於 IAM,Google 的 IAM 定價頁寫明 IAM API 全部免費(2026 年 12 月查)。要付錢的是你部署上去的服務,例如 Cloud Run、Artifact Registry 超過免費額度的部分。GitHub Actions 公開 repo 用標準 runner 也免費;私人 repo 的 GitHub Free 方案每月內含 12 美元額度,約 2,000 分鐘 Linux runner。
permissions: id-token: write 是什麼?會不會讓 workflow 有寫入權限?
它只允許那個 job 向 GitHub 要一張 OIDC 權杖(身分證明),GitHub 官方文件寫明不會給任何其他寫入權限。沒有這行,google-github-actions/auth 就拿不到通行證。建議只寫在需要部署的 job,例如這篇只有 deploy job 有,test job 沒有,所以測試程式拿不到 Google 憑證。
提供者沒設屬性條件會怎樣?
現在建不起來。實測不加 --attribute-condition 建 GitHub 提供者,gcloud 直接回 INVALID_ARGUMENT: The attribute condition must reference one of the provider's claims。原因是全世界的 GitHub repo 都用同一個發行者網址,沒有條件的話,任何人的 repo 都能拿通行證來換你的身分。條件建議用數字的 repo ID、帳號 ID,再加上分支限制。
為什麼這篇要「扮演服務帳戶」,不用官方說比較好的直接授權?
Google 官方文件和 google-github-actions/auth 的 README 都推薦優先用直接授權(把角色直接給外部身分,不經過服務帳戶)。但官方的支援服務清單寫明 Cloud Run 不支援直接授權,要用扮演服務帳戶(2026 年 12 月查)。所以部署 Cloud Run 這種情境,要建一個專用的部署帳戶,再允許你的 repo 扮演它。
GitHub 的 sub 為什麼跟舊文章寫的不一樣?
GitHub 官方文件說明,2026 年 7 月 15 日以後建立的 repo,OIDC 權杖的 sub 改成包含帳號 ID 和 repo ID 的固定格式,例如這篇實測的 repo:aaronlee700618@50737700/do-14-github-actions-demo@1483676804:ref:refs/heads/main,舊格式是 repo:帳號/repo:ref:分支。目的是防止 repo 刪除或改名後名稱被搶註。條件寫 assertion.sub 的要照新格式改;用 repository_id 當條件就不受影響。
GitLab CI 也能用嗎?跟 GitHub 差在哪?
可以,這篇用自架 GitLab 19.6.2 實測成功。差別:job 要寫 id_tokens: 才會拿到通行證;aud 要跟提供者的 allowed audiences 一樣;發行者網址結尾要加斜線、audience 不加;條件要加 ref_type=='branch',才不會被同名的標籤混過去;GitLab 通行證有效時間等於 job 逾時(實測 3600 秒);沒有官方 auth action,用 gcloud iam workload-identity-pools create-cred-config 產生設定檔。舊的 CI_JOB_JWT_V2 在 GitLab 17.0 已經移除。
刪掉的身分集區為什麼不能同名重建?
刪掉的集區會保留 30 天,這段期間可以用 gcloud iam workload-identity-pools undelete 救回,所以名字還被佔著。實測刪掉 do-14-pool 後立刻建同名的,得到 ALREADY_EXISTS: Requested entity already exists,列表顯示 2027-01-04 才永久刪除。要馬上重做的話,換一個名字就好。
重點整理
- GitHub Actions 部署 Cloud Run 不用金鑰:用 Workload Identity Federation,GitHub 發 300 秒的通行證,Google STS 驗證後換成扮演部署帳戶的權杖(實測 3599 秒),repo 和 Secrets 裡 0 把金鑰
- 屬性條件現在是必填:GitHub 提供者不加條件建不起來;條件用數字的 repo ID+
main分支,換分支跑會被rejected by the attribute condition擋下 - 最小權限:部署帳戶只給 Cloud Run 開發人員、執行身分的服務帳戶使用者、存放區寫入(或讀取);網站用另一個沒有任何角色的執行帳戶
- 稽核記錄查得到是誰:
serviceAccountDelegationInfo寫出是哪個 repo 或 GitLab 專案、哪個分支,失敗的嘗試也有記錄 - GitLab CI 同一套觀念:
id_tokens:+gcloud ... create-cred-config,通行證有效時間等於 job 逾時;證照新版考綱 2.3 新增「管理短效憑證」
延伸閱讀
本系列
- 第 1 篇:GCP DevOps 證照怎麼考?2026 新版考綱、比重與準備地圖
- 第 3 篇:CI/CD 是什麼?持續整合、持續交付、持續部署差在哪
- 第 4 篇:Git、GitHub、GitLab 差在哪?版本控制白話懂(撰寫中)
- 第 7 篇:DevSecOps 是什麼?跟 SecOps、Google SecOps 差在哪
- 第 13 篇:Cloud Build 串 GitHub/GitLab:push 就自動建置部署
- 第 15 篇:Cloud Deploy 教學:dev→staging→prod 推版、核准、回滾
- 第 18 篇:軟體供應鏈安全:Artifact Analysis、Binary Authorization、SLSA(撰寫中)
這篇用到的服務
- Workload Identity 是什麼?GKE 不用金鑰安全存取 GCP 服務
- Cloud Run 是什麼?Cloud Run 教學:部署容器、版本與流量分割
- Artifact Registry 是什麼?把 Docker 映像檔推上 GCP 教學
- Cloud Build 是什麼?用 cloudbuild.yaml 自動建映像檔、部署到 Cloud Run
站上相關文章
- GCP 的 Cloud IAM:角色與權限控管介紹
- 使用 GCP Service Account 開發程式的小技巧和注意事項
- Cloud Run vs GKE vs Compute Engine 怎麼選?一張表比較
- Docker、Kubernetes 教學地圖:從容器到 Cloud Run、GKE 全系列整理
管線能安全地拿到權限之後,下一步是把同一個版本依序推到 dev、staging、prod,第 15 篇用 Cloud Deploy 來做。可以看看東東的 GCP 課程,或加 LINE 聊聊你現在的狀況,一起找出最適合你的學習順序。


