<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Workload Identity Federation - 東東 GCP 教學 - GCP 實戰講師</title>
	<atom:link href="https://dongdonggcp.com/tag/workload-identity-federation/feed/" rel="self" type="application/rss+xml" />
	<link>https://dongdonggcp.com</link>
	<description>助你考取證照，轉職成功</description>
	<lastBuildDate>Sat, 05 Dec 2026 01:31:46 +0000</lastBuildDate>
	<language>zh-TW</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=7.1.5</generator>

<image>
	<url>https://dongdonggcp.com/wp-content/uploads/2025/04/cropped-340838097_121391010914395_5443948698124160121_n-32x32.jpg</url>
	<title>Workload Identity Federation - 東東 GCP 教學 - GCP 實戰講師</title>
	<link>https://dongdonggcp.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>GitHub Actions 教學：不用金鑰部署 Cloud Run（Workload Identity Federation）</title>
		<link>https://dongdonggcp.com/2026/12/05/github-actions-workload-identity-federation-cloud-run/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=github-actions-workload-identity-federation-cloud-run</link>
					<comments>https://dongdonggcp.com/2026/12/05/github-actions-workload-identity-federation-cloud-run/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Sat, 05 Dec 2026 01:17:22 +0000</pubDate>
				<category><![CDATA[DevOps]]></category>
		<category><![CDATA[無伺服器]]></category>
		<category><![CDATA[資訊安全]]></category>
		<category><![CDATA[CI/CD]]></category>
		<category><![CDATA[Cloud Run]]></category>
		<category><![CDATA[Github]]></category>
		<category><![CDATA[GitHub Actions]]></category>
		<category><![CDATA[GitLab]]></category>
		<category><![CDATA[IAM]]></category>
		<category><![CDATA[Service Account]]></category>
		<category><![CDATA[Workload Identity Federation]]></category>
		<guid isPermaLink="false">https://dongdonggcp.com/?p=14124</guid>

					<description><![CDATA[<p>GitHub Actions 教學：用 Workload Identity Federation 不存金鑰部署 Cloud Run，實測屬性條件擋分支、最小權限、稽核記錄查 repo，附 GitLab CI 寫法與證照考點。</p>
<p>The post <a href="https://dongdonggcp.com/2026/12/05/github-actions-workload-identity-federation-cloud-run/">GitHub Actions 教學：不用金鑰部署 Cloud Run（Workload Identity Federation）</a> first appeared on <a href="https://dongdonggcp.com">東東 GCP 教學 - GCP 實戰講師</a>.</p>]]></description>
										<content:encoded><![CDATA[<p class="wp-block-paragraph"><strong>GitHub Actions 教學：免金鑰部署 Cloud Run，靠 GitHub 5 分鐘的通行證換 Google 1 小時的憑證。</strong></p>



<p class="wp-block-paragraph">很多 GitHub Actions 教學的第一步，是叫你建一把服務帳戶金鑰（一個 JSON 檔），貼進 GitHub 的 Secrets（GitHub 存放密碼、金鑰的加密欄位，workflow 執行時才讀得到）。那把金鑰<strong>預設永不過期</strong>，誰拿到誰就能用你的 Google Cloud，直到你發現並手動停用為止。</p>



<p class="wp-block-paragraph">這篇改用 Google 官方推薦的 <strong>Workload Identity Federation</strong>（簡稱 WIF）：repo 裡、GitHub Secrets 裡都沒有任何金鑰。部署的對象是一個只回一行文字的 Python 小網站，我在 2026 年 12 月 4 日深夜實際做了一次：</p>


<ol class="wp-block-list">
<li>push 到 <code>main</code>，GitHub Actions 自動<strong>測試 → 建映像檔 → 推到 Artifact Registry → 部署到 Cloud Run</strong>，整條 57 秒</li>

<li>故意換一個分支跑，看它在「換憑證」那一步被 Google 擋下來</li>

<li>用 Cloud Audit Logs（稽核記錄）查出每次部署是<strong>哪個 repo、哪個分支</strong>做的</li>

<li>再用自架的 GitLab CI 做同一件事，比較兩邊寫法</li>
</ol>



<p class="wp-block-paragraph">這篇寫給想學 GitHub Actions、想把 CI/CD 接上 GCP、或正在準備 GCP DevOps 證照的人，指令都可以整段複製。這是「DevOps 證照＋Ops 名詞」系列第 14 篇。</p>



<figure class="wp-block-image aligncenter size-full"><img fetchpriority="high" decoding="async" width="1200" height="675" src="https://dongdonggcp.com/wp-content/uploads/2026/12/do14-cards-01-wif-flow.png" alt="GitHub Actions 部署 Cloud Run 不用金鑰的流程：GitHub 發 300 秒的 OIDC 通行證，Google STS 檢查 repo ID 和 main 分支，換成扮演 do-14-deployer 的存取權杖（3599 秒），再部署 Cloud Run；換成 try-other-branch 分支在第 2 步就被拒絕" class="wp-image-14096" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do14-cards-01-wif-flow.png 1200w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-cards-01-wif-flow-300x169.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-cards-01-wif-flow-1024x576.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-cards-01-wif-flow-768x432.png 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">為什麼你需要知道</h2>


<ul class="wp-block-list">
<li><strong>金鑰外流的代價很大</strong>：JSON 金鑰檔外流（不小心 commit 進 repo、被貼進聊天群組、CI 的 log 印出來），拿到的人不用密碼、不用手機驗證，就能用那個服務帳戶的所有權限</li>

<li><strong>新的 GCP 機構已經不讓你建金鑰</strong>：Google 官方文件寫明，2024 年 5 月 3 日以後建立的機構（organization），預設會擋「建立服務帳戶金鑰」（<code>constraints/iam.disableServiceAccountKeyCreation</code>）。照舊教學做，第一步就會卡住（2026 年 12 月查<a href="https://cloud.google.com/iam/docs/service-account-creds">官方文件</a>）</li>

<li><strong>證照新版考綱新增了這題</strong>：Professional Cloud DevOps Engineer 2026 年 11 月 23 日起的新版考綱，2.3 節多了一條「Managing short-lived credentials」（管理短效憑證），而 Workload Identity Federation 本來就列在 2.3 的設定與秘密管理裡</li>

<li><strong>面試會被問到</strong>：「你們的 CI/CD 怎麼拿雲端權限？」答「把金鑰放在 Secrets」，很容易被追問「那金鑰外流怎麼辦」</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">GitHub Actions 是什麼：放在 GitHub 上的自動化流水線</h2>



<p class="wp-block-paragraph"><strong>GitHub Actions 是 GitHub 內建的自動化服務：你在 repo 裡放一個 YAML 設定檔，寫好「發生什麼事就做哪些步驟」，GitHub 就會開一台臨時的機器幫你照做。</strong></p>


<ul class="wp-block-list">
<li><strong>白話</strong>：push 程式碼之後，自動幫你跑測試、打包、部署的機器人</li>

<li><strong>生活比喻</strong>：像餐廳的出餐流程表貼在廚房牆上。單子一進來（push），廚房照表做：洗菜（測試）、炒菜（建映像檔）、出餐（部署）。流程表就是那個 YAML 檔</li>

<li><strong>來龍去脈</strong>：GitHub 在 2019 年 8 月讓 Actions 支援 CI/CD、<a href="https://github.blog/changelog/2019-11-11-github-actions-is-generally-available/">2019 年 11 月正式推出</a>。在那之前，GitHub 上的專案要另外接 Travis CI、CircleCI、Jenkins 這些外部服務</li>

<li><strong>為什麼要學</strong>：GitHub 是最多人用的程式碼平台，很多公司的 CI/CD 直接用 Actions。會寫 workflow 檔，等於會看懂公司的部署流程</li>
</ul>



<p class="wp-block-paragraph"><strong>YAML</strong> 是一種用縮排表示層級的設定檔格式，冒號左邊是名稱、右邊是值。GitHub Actions 的設定檔都放在 repo 的 <code>.github/workflows/</code> 資料夾裡，副檔名是 <code>.yml</code>。</p>



<p class="wp-block-paragraph">這篇會一直出現 3 個 Git 基本詞：<strong>repo</strong>（repository，程式碼倉庫）是放一個專案所有程式碼和修改紀錄的地方；<strong>push</strong> 是把自己電腦上的修改上傳到 repo；<strong>分支</strong>（branch）是同一份程式碼的平行版本，<code>main</code> 通常是要上線的那一條，其他分支用來開發、試東西。</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>名詞</th><th>白話</th><th>這篇的例子</th></tr></thead><tbody><tr><td>workflow（工作流程）</td><td>一整份流程表，一個 <code>.yml</code> 檔</td><td><code>.github/workflows/deploy.yml</code></td></tr><tr><td>event（觸發事件）</td><td>什麼時候開始跑，寫在 <code>on:</code></td><td>push 到 <code>main</code>、手動按 Run workflow</td></tr><tr><td>job（工作）</td><td>流程表裡的一大段，每個 job 開一台新的臨時機器</td><td><code>test</code>、<code>deploy</code> 兩個 job</td></tr><tr><td>step（步驟）</td><td>job 裡的一行一行指令</td><td>跑測試、建映像檔、部署</td></tr><tr><td>runner（執行器）</td><td>真正跑 job 的機器</td><td>GitHub 提供的 <code>ubuntu-latest</code></td></tr><tr><td>action（現成積木）</td><td>別人寫好的步驟，用 <code>uses:</code> 呼叫</td><td><code>google-github-actions/auth@v3</code></td></tr></tbody></table></figure>



<p class="wp-block-paragraph"><strong>收費</strong>（2026 年 12 月查 <a href="https://docs.github.com/en/billing/concepts/product-billing/github-actions">GitHub 官方文件</a>）：<strong>公開 repo 用 GitHub 提供的標準 runner 免費</strong>。私人 repo 的 GitHub Free 方案每月內含 12 美元的運算額度，標準 Linux runner 每分鐘 0.006 美元，12 ÷ 0.006 = 2,000 分鐘。</p>



<p class="wp-block-paragraph">算一次：這篇的 workflow 兩個 job 加起來 51 秒（測試 7 秒、部署 44 秒）。保守抓「每個 job 算 1 分鐘、一次 2 分鐘」，2,000 ÷ 2 = 每月可以部署約 1,000 次。部署越頻繁、job 越長，額度用得越快；用不完不會累積到下個月。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">Workload Identity Federation 是什麼：拿通行證換房卡</h2>



<p class="wp-block-paragraph"><strong>Workload Identity Federation 是 Google Cloud IAM 的功能：讓 GCP 外面的程式，拿它自己平台發的身分證明，去換 Google 的短效憑證，不用下載任何金鑰檔。</strong></p>


<ul class="wp-block-list">
<li><strong>白話</strong>：GitHub 幫你的 workflow 開一張「我是某某 repo、某某分支」的證明，Google 看了證明、照你設的規則核對，發一張 1 小時後就失效的權杖</li>

<li><strong>生活比喻</strong>：飯店換房卡。你拿護照（GitHub 發的通行證）到櫃台（Google 的權杖服務），櫃台照規則核對（只收這個 repo、只收 <code>main</code> 分支），發你一張隔天就失效的房卡（存取權杖）。你不用把萬能鑰匙（金鑰檔）一直放在背包裡</li>

<li><strong>來龍去脈</strong>：名字拆開是 Workload（工作負載，就是程式）＋Identity（身分）＋Federation（聯盟，互相承認對方發的身分）。Console 中文介面叫「Workload Identity 聯盟」。Google Cloud 官方部落格在 <a href="https://cloud.google.com/blog/products/identity-security/enabling-keyless-authentication-from-github-actions">2021 年 12 月</a>發文介紹 GitHub Actions 用它免金鑰登入，同時推出 <code>google-github-actions/auth</code> 這個 action</li>

<li><strong>為什麼要學</strong>：它是「CI/CD 怎麼安全地拿雲端權限」的標準答案，證照、面試、實際工作都會碰到</li>
</ul>



<h3 class="wp-block-heading">先看整個流程：4 步</h3>


<ol class="wp-block-list">
<li>GitHub 在 workflow 執行時，發一張「我是哪個 repo、哪個分支」的<strong>通行證</strong></li>

<li>workflow 拿通行證到 Google 的換證櫃台（STS，Security Token Service，下面名詞表會再講）</li>

<li>櫃台照你設的規則核對，過了，就讓它「扮演」一個專門部署用的服務帳戶</li>

<li>換到 Google 的<strong>存取權杖</strong>（房卡），拿去推映像檔、部署 Cloud Run</li>
</ol>



<p class="wp-block-paragraph">這篇的說法固定這樣用：<strong>通行證</strong>＝GitHub 或 GitLab 發的 OIDC 權杖，幾分鐘就過期；<strong>存取權杖</strong>（也叫短效憑證，就是房卡）＝Google 發的，約 1 小時過期。兩個都是「一串證明身分的文字」，差在誰發的、拿去哪裡用。</p>



<h3 class="wp-block-heading">會用到的 6 個名詞</h3>



<p class="wp-block-paragraph"><strong>OIDC 權杖</strong>（OpenID Connect token）：OIDC 是一套「怎麼發身分證明」的公開標準；權杖是一段用 <code>.</code> 隔成三段的文字，中間那段寫著「誰發的、發給誰、什麼時候過期」，最後一段是簽名，偽造不了。這篇叫它「通行證」。</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>名詞</th><th>白話</th><th>這篇建的</th></tr></thead><tbody><tr><td>身分集區（Workload Identity Pool）</td><td>一個「我信任哪些外部身分」的資料夾</td><td><code>do-14-pool</code></td></tr><tr><td>提供者（Provider）</td><td>集區裡的一個發證單位，記著它的網址和規則</td><td><code>do-14-github</code>、<code>do-14-gitlab</code></td></tr><tr><td>屬性對應（attribute mapping）</td><td>從通行證裡挑哪些欄位出來用</td><td>repo ID、分支名稱</td></tr><tr><td>屬性條件（attribute condition）</td><td>通行證要符合什麼才收，不符合直接拒絕</td><td>只收這個 repo ID 的 <code>main</code> 分支</td></tr><tr><td>STS（Security Token Service，安全權杖服務）</td><td>Google 負責「驗通行證、換權杖」的櫃台</td><td><code>sts.googleapis.com</code></td></tr><tr><td>扮演服務帳戶（service account impersonation）</td><td>換到的身分去「借用」一個服務帳戶的權限</td><td>扮演 <code>do-14-deployer</code></td></tr></tbody></table></figure>



<p class="wp-block-paragraph"><strong>服務帳戶</strong>（service account）是給程式用的 Google Cloud 帳號，跟你登入用的個人帳號分開。<strong>IAM</strong>（Identity and Access Management）是 Google Cloud 管「誰能對哪個資源做什麼」的權限系統；權限是用 <strong>IAM 角色</strong>（一包權限的組合）「綁」上去的，綁一次就叫一條授權。</p>



<h3 class="wp-block-heading">為什麼要「扮演服務帳戶」，不直接給權限？</h3>



<p class="wp-block-paragraph">Google 官方文件建議優先用「直接授權」（direct resource access）：不經過服務帳戶，直接把角色給外部身分。但官方的<a href="https://cloud.google.com/iam/docs/federated-identity-supported-services">支援服務清單</a>寫明：<strong>Cloud Run 不支援直接授權，要用扮演服務帳戶</strong>（2026 年 12 月查）。</p>



<p class="wp-block-paragraph">所以這篇的做法是：GitHub 的通行證換到身分後，去扮演 <code>do-14-deployer</code> 這個專門部署用的服務帳戶，用它的權限推映像檔、部署 Cloud Run。官方也建議<strong>每條管線用一個專用的服務帳戶</strong>，這篇 GitHub 和 GitLab 各用一個。</p>



<figure class="wp-block-image aligncenter size-full"><img decoding="async" width="1200" height="675" src="https://dongdonggcp.com/wp-content/uploads/2026/12/do14-cards-02-key-vs-wif.png" alt="金鑰檔 vs Workload Identity Federation 比較：服務帳戶金鑰要保管 JSON 檔、預設永不過期、外流了誰拿到都能用；WIF 搭 GitHub Actions 或自架 GitLab CI 都不用保管秘密，通行證 5 分鐘或 1 小時、Google 憑證 1 小時，過期就沒用，並用屬性條件限制 repo 和 main 分支" class="wp-image-14097" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do14-cards-02-key-vs-wif.png 1200w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-cards-02-key-vs-wif-300x169.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-cards-02-key-vs-wif-1024x576.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-cards-02-key-vs-wif-768x432.png 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">動手做：GitHub Actions 用 WIF 部署 Cloud Run</h2>



<p class="wp-block-paragraph">這段做完會有：一個公開的 GitHub repo，push 到 <code>main</code> 就自動測試、建映像檔、部署到 Cloud Run，<strong>全程沒有任何金鑰</strong>。</p>


<ul class="wp-block-list">
<li><strong>在哪裡做</strong>：GCP 的設定在 Cloud Shell（Google 提供、開瀏覽器就能打指令的 Linux 終端機），專案 dong-dong-gcp-3，區域 <code>asia-east1</code>（台灣彰化）；程式碼放在 GitHub</li>

<li><strong>花多久</strong>：GCP 設定約 10 分鐘，GitHub 跑一次約 1 分鐘</li>

<li><strong>事前準備</strong>：一個已連結帳單帳戶的 GCP 專案、一個 GitHub 帳號。下面指令裡的 <code>dong-dong-gcp-3</code> 要換成你的專案 ID，<code>aaronlee700618/do-14-github-actions-demo</code> 要換成你的「帳號/repo 名稱」</li>

<li><strong>會不會花錢</strong>：幾乎不會。WIF 屬於 IAM，<a href="https://cloud.google.com/iam/pricing">IAM 定價頁</a>寫明 IAM API 全部免費；公開 repo 的 GitHub Actions 免費；Cloud Run 沒人用時縮到 0 台。做完照最後一段刪乾淨</li>
</ul>



<p class="wp-block-paragraph"><strong>怎麼開 Cloud Shell</strong>：登入 <a href="https://console.cloud.google.com/">Google Cloud Console</a>，左上角藍框是專案選單，右上角紅框那個 <code>&gt;_</code> 圖示就是 Cloud Shell：</p>



<figure class="wp-block-image aligncenter size-full"><img decoding="async" width="1600" height="59" src="https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-00a-console-cloudshell-button.png" alt="Google Cloud Console 上方工具列：左上藍框是專案選單，顯示專案 ID dong-dong-gcp-3；右上紅框是開啟 Cloud Shell 的按鈕" class="wp-image-14098" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-00a-console-cloudshell-button.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-00a-console-cloudshell-button-300x11.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-00a-console-cloudshell-button-1024x38.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-00a-console-cloudshell-button-768x28.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-00a-console-cloudshell-button-1536x57.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph">點下去，畫面下方會開出黑底的終端機，看到結尾是 <code>$</code> 的提示字元就能打指令（這張是容器系列拍的畫面）：</p>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="500" src="https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-00b-cloudshell-open.png" alt="Cloud Shell 開起來的樣子：黑底終端機，最後一行是 $ 提示字元，可以開始輸入指令" class="wp-image-14099" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-00b-cloudshell-open.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-00b-cloudshell-open-300x94.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-00b-cloudshell-open-1024x320.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-00b-cloudshell-open-768x240.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-00b-cloudshell-open-1536x480.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph">下面每段指令都是<strong>整段複製、貼進 Cloud Shell、按 Enter</strong>，等提示字元再出現就是跑完了。截圖裡的提示字元有縮短，你的畫面會是「你的帳號@cloudshell:~ (專案ID)$」。這篇建的東西一律 <code>do-14-</code> 開頭，刪的時候不會刪錯。</p>



<h3 class="wp-block-heading">步驟 1：設定變數，開 6 個 API</h3>



<p class="wp-block-paragraph">先把會重複用到的值存進<strong>變數</strong>（終端機暫時記住的名稱和值，後面用 <code>$名稱</code> 取出來）。<code>PROJECT_NUMBER</code> 是專案編號（一串數字，跟專案 ID 不一樣），WIF 的設定要用編號：</p>



<pre class="wp-block-code"><code>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"</code></pre>



<pre class="wp-block-code"><code>dong-dong-gcp-3 / 600195576280 / asia-east1 / aaronlee700618/do-14-github-actions-demo</code></pre>



<p class="wp-block-paragraph">變數只活在這一個 Cloud Shell 分頁裡。Cloud Shell 閒置太久斷線、或你開了新分頁，變數就不見了，指令會出現空白值而失敗；這時把這行（和步驟 3、步驟 7 開頭設變數的那行）重貼一次就好。</p>



<p class="wp-block-paragraph">接著開 API（服務對外的操作介面，要先「啟用」才能用）。<code>sts</code> 是換權杖的櫃台、<code>iamcredentials</code> 是扮演服務帳戶用的，這兩個是 WIF 一定要的：</p>



<pre class="wp-block-code"><code>gcloud services enable iam.googleapis.com iamcredentials.googleapis.com sts.googleapis.com cloudresourcemanager.googleapis.com run.googleapis.com artifactregistry.googleapis.com</code></pre>



<pre class="wp-block-code"><code>Operation "operations/acat.p2-600195576280-4ca99d37-c429-4dde-97a7-3b27e49bef24" finished successfully.</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="114" src="https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-02-enable-apis.png" alt="gcloud services enable 一次開啟 IAM、IAM Credentials、STS、Resource Manager、Cloud Run、Artifact Registry 六個 API，回 finished successfully" class="wp-image-14100" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-02-enable-apis.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-02-enable-apis-300x21.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-02-enable-apis-1024x73.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-02-enable-apis-768x55.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-02-enable-apis-1536x109.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<h3 class="wp-block-heading">步驟 2：建放映像檔的存放區</h3>



<p class="wp-block-paragraph"><strong>Artifact Registry</strong> 是 Google Cloud 放映像檔的倉庫，<strong>存放區</strong>（repository）是裡面的一個資料夾。映像檔是「程式加上執行環境」打包好的檔案，Cloud Run 照它把網站跑起來：</p>



<pre class="wp-block-code"><code>gcloud artifacts repositories create do-14-repo --repository-format=docker --location=$REGION --description="第 14 篇 GitHub Actions 示範"</code></pre>



<pre class="wp-block-code"><code>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].</code></pre>



<h3 class="wp-block-heading">步驟 3：建兩個服務帳戶，各給最小的權限</h3>



<p class="wp-block-paragraph">建兩個服務帳戶，分工很清楚：</p>


<ul class="wp-block-list">
<li><code>do-14-deployer</code>：<strong>部署用</strong>，GitHub Actions 會扮演它</li>

<li><code>do-14-run</code>：<strong>網站執行時用的身分</strong>，Cloud Run 上的程式用它的權限做事。這個小網站不用呼叫任何 Google Cloud 服務，所以它<strong>一個角色都不給</strong></li>
</ul>



<pre class="wp-block-code"><code>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 執行身分"</code></pre>



<pre class="wp-block-code"><code>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</code></pre>



<p class="wp-block-paragraph">為什麼不用預設的服務帳戶？Cloud Run 沒指定身分時，用的是專案的 Compute Engine 預設服務帳戶，很多舊專案的它有「編輯者」這種大權限。網站被打穿的話，攻擊者就拿到整個專案。</p>



<p class="wp-block-paragraph">接著給部署帳戶三個角色，<strong>每個都綁在最小的範圍</strong>：</p>



<pre class="wp-block-code"><code>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</code></pre>



<pre class="wp-block-code"><code>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].</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="190" src="https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-05-deployer-roles.png" alt="給 do-14-deployer 三個角色：專案層級的 Cloud Run 開發人員、只對 do-14-repo 的 Artifact Registry 寫入者、只對 do-14-run 的服務帳戶使用者，三行都回 Updated IAM policy" class="wp-image-14101" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-05-deployer-roles.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-05-deployer-roles-300x36.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-05-deployer-roles-1024x122.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-05-deployer-roles-768x91.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-05-deployer-roles-1536x182.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>角色</th><th>綁在哪</th><th>為什麼要</th><th>沒給會怎樣</th></tr></thead><tbody><tr><td><code>roles/run.developer</code>（Cloud Run 開發人員）</td><td>專案</td><td>建立、更新 Cloud Run 服務</td><td>部署那步 <code>PERMISSION_DENIED</code></td></tr><tr><td><code>roles/artifactregistry.writer</code>（Artifact Registry 寫入者）</td><td>只有 <code>do-14-repo</code></td><td>推映像檔進去（寫入者也包含讀取）</td><td>推映像檔被拒</td></tr><tr><td><code>roles/iam.serviceAccountUser</code>（服務帳戶使用者）</td><td>只有 <code>do-14-run</code></td><td>讓部署出來的服務「用 <code>do-14-run</code> 的身分跑」</td><td>部署時說你不能使用這個服務帳戶</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">這三個正好對上 Cloud Run 官方文件列的<a href="https://cloud.google.com/run/docs/deploying">部署所需角色</a>（開發人員、服務帳戶使用者、存放區讀取者）。官方範例常給 <code>roles/run.admin</code>（管理員），它多了「改服務的存取權限」，部署用不到，這篇不給。</p>



<p class="wp-block-paragraph"><code>run.developer</code> 綁在專案層級，代表它也能改<strong>同一個專案裡的其他 Cloud Run 服務</strong>。正式環境建議一個環境一個專案，或在服務第一次建好之後，改成只綁在那個服務上。<code>--condition=None</code> 是「這條授權沒有附加條件」，專案裡已經有條件式授權時不寫會跳出詢問。</p>



<h3 class="wp-block-heading">步驟 4：查 repo 的數字 ID</h3>



<p class="wp-block-paragraph">先在 GitHub 建一個<strong>公開</strong> repo：右上角 <code>+</code> → New repository，Repository name 填 <code>do-14-github-actions-demo</code>，Choose visibility 選 <strong>Public</strong>，下面的 README、.gitignore、license 都不用加（檔案步驟 9 會自己放），按 Create repository：</p>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1570" height="1690" src="https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-g0a-github-new-repo.png" alt="GitHub 建立新 repo 的頁面：紅框是 Repository name 欄位、visibility 選 Public、最下面的 Create repository 按鈕；Add README 關著、No .gitignore、No license" class="wp-image-14102" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-g0a-github-new-repo.png 1570w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-g0a-github-new-repo-279x300.png 279w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-g0a-github-new-repo-951x1024.png 951w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-g0a-github-new-repo-768x827.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-g0a-github-new-repo-1427x1536.png 1427w" sizes="(max-width: 1570px) 100vw, 1570px" /></figure>



<p class="wp-block-paragraph">等一下的規則要用 repo 的<strong>數字 ID</strong>，不用名稱。原因：repo 刪掉或改名後，別人可以註冊同一個名稱，名稱會被「搶註」；數字 ID 不會重複使用（<a href="https://cloud.google.com/iam/docs/workload-identity-federation-with-deployment-pipelines">Google 官方文件</a>也這樣建議）。回到 Cloud Shell，用 GitHub 的公開 API 查（<code>curl</code> 是打網址拿回應的指令，<code>jq</code> 是挑出 JSON 欄位的工具）：</p>



<pre class="wp-block-code"><code>curl -s https://api.github.com/repos/$GH_REPO | jq '{full_name, id, owner_id: .owner.id}'</code></pre>



<pre class="wp-block-code"><code>{
  "full_name": "aaronlee700618/do-14-github-actions-demo",
  "id": 1483676804,
  "owner_id": 50737700
}</code></pre>



<p class="wp-block-paragraph"><code>id</code> 是 repo 的編號、<code>owner_id</code> 是帳號的編號，下一步會寫進規則。</p>



<h3 class="wp-block-heading">步驟 5：建身分集區</h3>



<p class="wp-block-paragraph">步驟 5～8 會設好兩道關卡：第一道是提供者的<strong>屬性條件</strong>（像大樓門禁，決定這張通行證換不換得到身分），第二道是服務帳戶上的<strong>授權</strong>（像房間鑰匙，決定換到的身分能扮演哪個服務帳戶）。先建放提供者的集區：</p>



<pre class="wp-block-code"><code>gcloud iam workload-identity-pools create do-14-pool --location=global --display-name="do-14 CI/CD pool"</code></pre>



<pre class="wp-block-code"><code>Created workload identity pool [do-14-pool].</code></pre>



<p class="wp-block-paragraph"><code>--location=global</code>：身分集區只有 global（全球）一種位置。</p>



<h3 class="wp-block-heading">步驟 6：先試試看「不加條件」建提供者</h3>



<p class="wp-block-paragraph">很多舊教學建 GitHub 提供者時，只設屬性對應、不設屬性條件。現在照做會直接被拒：</p>



<pre class="wp-block-code"><code>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"</code></pre>



<pre class="wp-block-code"><code>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</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="132" src="https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-08-provider-no-condition.png" alt="沒加 --attribute-condition 建 GitHub 提供者，gcloud 回 INVALID_ARGUMENT：The attribute condition must reference one of the provider&#x27;s claims" class="wp-image-14103" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-08-provider-no-condition.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-08-provider-no-condition-300x25.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-08-provider-no-condition-1024x84.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-08-provider-no-condition-768x63.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-08-provider-no-condition-1536x127.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph">為什麼 Google 要強制？<strong>全世界的 GitHub repo 都由同一個網址 <code>https://token.actions.githubusercontent.com</code> 發通行證</strong>。如果提供者不設條件，任何人的 GitHub repo 都能拿通行證來你的集區換身分；再加上授權範圍給太寬，陌生人的 workflow 就能部署到你的專案。<a href="https://cloud.google.com/iam/docs/workload-identity-federation-with-deployment-pipelines#conditions">官方文件</a>寫明：GitHub、GitLab SaaS、HCP Terraform 這類共用網址的平台，<strong>一定要</strong>用屬性條件限制成自己的組織或 repo（2026 年 12 月查）。</p>



<h3 class="wp-block-heading">步驟 7：加上條件，建 GitHub 提供者</h3>



<p class="wp-block-paragraph">這次加上三個條件，<strong>全部符合才收</strong>：帳號 ID、repo ID 對得上，而且是 <code>main</code> 分支：</p>



<pre class="wp-block-code"><code>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' &amp;&amp; assertion.repository_id=='$GH_REPO_ID' &amp;&amp; assertion.ref=='refs/heads/main'"</code></pre>



<pre class="wp-block-code"><code>Created workload identity pool provider [do-14-github].</code></pre>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>參數</th><th>意思</th></tr></thead><tbody><tr><td><code>--issuer-uri</code></td><td>發通行證的單位網址，Google 會去這裡拿公開的簽名鑰匙來驗證</td></tr><tr><td><code>--attribute-mapping</code></td><td><code>assertion.X</code> 是通行證裡的欄位，<code>attribute.X</code> 是 Google 這邊的名字；<code>google.subject</code> 是這個身分的「主名稱」，會出現在稽核記錄</td></tr><tr><td><code>--attribute-condition</code></td><td>用 CEL（Google 的條件運算式語法）寫規則，<code>&amp;&amp;</code> 是「而且」；不符合的通行證直接拒絕</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">查一下建好的樣子，<code>state: ACTIVE</code> 就是可以用了：</p>



<pre class="wp-block-code"><code>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)'</code></pre>



<pre class="wp-block-code"><code>attributeCondition: assertion.repository_owner_id=='50737700' &amp;&amp; assertion.repository_id=='1483676804'
  &amp;&amp; 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</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="205" src="https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-11-provider-describe.png" alt="gcloud providers describe 顯示 do-14-github 提供者：屬性條件限制 repository_owner_id、repository_id 和 refs/heads/main，狀態 ACTIVE" class="wp-image-14104" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-11-provider-describe.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-11-provider-describe-300x38.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-11-provider-describe-1024x131.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-11-provider-describe-768x98.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-11-provider-describe-1536x197.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph"><code>name</code> 那一長串（<code>projects/600195576280/.../providers/do-14-github</code>）等一下要寫進 workflow。</p>



<h3 class="wp-block-heading">步驟 8：允許這個 repo 扮演部署帳戶</h3>



<p class="wp-block-paragraph">最後一道授權：把「扮演 <code>do-14-deployer</code>」的權利（<code>roles/iam.workloadIdentityUser</code>，Workload Identity 使用者）給這個 repo：</p>



<pre class="wp-block-code"><code>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</code></pre>



<pre class="wp-block-code"><code>Updated IAM policy for serviceAccount [do-14-deployer@dong-dong-gcp-3.iam.gserviceaccount.com].</code></pre>



<p class="wp-block-paragraph"><code>principalSet://...attribute.repository_id/1483676804</code> 拆開看：前面 <code>projects/專案編號/.../workloadIdentityPools/do-14-pool</code> 是集區的位置，最後的 <code>attribute.repository_id/1483676804</code> 是「repo ID 等於這個數字」，合起來就是「集區裡、repo ID 是 1483676804 的<strong>所有</strong>身分」。這樣就有兩道關卡：</p>


<ol class="wp-block-list">
<li><strong>提供者的屬性條件</strong>（步驟 7）：不是這個 repo 的 <code>main</code> 分支，連換身分都換不到</li>

<li><strong>服務帳戶的授權</strong>（這步）：換到身分之後，也只有這個 repo 能扮演 <code>do-14-deployer</code></li>
</ol>



<p class="wp-block-paragraph"><strong>做完先等 1～5 分鐘再 push</strong>。<code>google-github-actions/auth</code> 的 README 寫明集區、提供者、IAM 權限要最多 5 分鐘才會生效；我實測綁完馬上跑，第一次就失敗了（「實測時的意外」第 2 條）。</p>



<p class="wp-block-paragraph">用 Console 看（IAM 與管理 → Workload Identity 聯盟 → <code>do-14-pool</code>），右邊是提供者清單，左邊的圖是每秒成功換權杖的次數。這張是後面加上 GitLab 提供者之後拍的：</p>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="848" src="https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-c1-console-pool.png" alt="Console 的 Workload Identity 聯盟頁面：do-14 CI/CD pool 集區詳細資料，右邊提供者清單有 GitHub Actions 和 Self-managed GitLab 兩個 OIDC 提供者，左邊是成功交換權杖次數的用量圖" class="wp-image-14105" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-c1-console-pool.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-c1-console-pool-300x159.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-c1-console-pool-1024x543.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-c1-console-pool-768x407.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-c1-console-pool-1536x814.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<h3 class="wp-block-heading">步驟 9：寫 workflow 檔</h3>



<p class="wp-block-paragraph">repo 裡除了說明用的 <code>README.md</code>，要放 6 個檔案：小網站、測試、Dockerfile、兩個排除清單，加上最重要的 workflow 檔。</p>



<p class="wp-block-paragraph"><strong>檔案怎麼放進 repo，兩種方法選一種</strong>：</p>


<ul class="wp-block-list">
<li><strong>不會 git，用網頁</strong>：在 repo 首頁按 <strong>Add file → Create new file</strong>，上面的檔名欄打檔名，下面貼內容，按右上角 <strong>Commit changes</strong> 存進 <code>main</code>。檔名欄可以直接打路徑，例如 <code>.github/workflows/deploy.yml</code>，打到 <code>/</code> 會自動變成資料夾</li>

<li><strong>會 git</strong>：在自己電腦建好這些檔案，<code>git commit</code> 後 <code>git push</code> 到 <code>main</code>（我是用這個方法）</li>
</ul>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="439" src="https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-g0b-github-new-file.png" alt="GitHub 網頁新增檔案的畫面：紅框是上方的檔名欄（Name your file）和右上角的 Commit changes 按鈕，中間是貼檔案內容的編輯區" class="wp-image-14106" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-g0b-github-new-file.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-g0b-github-new-file-300x82.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-g0b-github-new-file-1024x281.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-g0b-github-new-file-768x211.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-g0b-github-new-file-1536x421.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph">6 個檔案都放好之後，repo 首頁長這樣（紅框是檔案清單，<code>.github/workflows</code> 資料夾裡就是 <code>deploy.yml</code>）：</p>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="612" src="https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-g0c-github-repo-files.png" alt="do-14-github-actions-demo repo 首頁：紅框是 Add file 按鈕和檔案清單，有 .github/workflows 資料夾、.dockerignore、.gitignore、Dockerfile、README.md、app.py、test_app.py" class="wp-image-14107" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-g0c-github-repo-files.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-g0c-github-repo-files-300x115.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-g0c-github-repo-files-1024x392.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-g0c-github-repo-files-768x294.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-g0c-github-repo-files-1536x588.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph">要注意：用網頁新增時，每存一個檔案就是一次 commit。<code>deploy.yml</code> 一進到 <code>main</code>，那次和之後的每次存檔都會觸發 workflow，所以<strong>最後才建 <code>.github/workflows/deploy.yml</code></strong>，而且要在步驟 8 做完、等幾分鐘之後再存。</p>



<p class="wp-block-paragraph">前 5 個檔案都很短，以下是這次實際用的內容（也可以直接看<a href="https://github.com/aaronlee700618/do-14-github-actions-demo">示範 repo</a>）。</p>



<p class="wp-block-paragraph"><code>app.py</code>：用 Python 內建模組寫的小網站，回一行 <code>Hello from do-14-github-actions-demo (版本)</code>，版本從環境變數 <code>APP_VERSION</code> 讀（<strong>環境變數</strong>是程式啟動時從外面傳進去的設定值）：</p>



<pre class="wp-block-code"><code>"""DevOps 系列示範用的小網站：不用任何套件，Cloud Run 會給 PORT 環境變數。"""
import os
from http.server import BaseHTTPRequestHandler, HTTPServer

VERSION = os.environ.get("APP_VERSION", "v1")


def message(version: str = VERSION) -&gt; 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()</code></pre>



<p class="wp-block-paragraph"><code>test_app.py</code>：1 個測試，檢查回傳的文字對不對：</p>



<pre class="wp-block-code"><code>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()</code></pre>



<p class="wp-block-paragraph"><code>Dockerfile</code>：建映像檔的食譜，從 <code>python:3.12-slim</code> 開始，複製 <code>app.py</code>、啟動它：</p>



<pre class="wp-block-code"><code>FROM python:3.12-slim
WORKDIR /app
COPY app.py .
ENV PORT=8080
CMD ["python", "app.py"]</code></pre>



<p class="wp-block-paragraph"><code>.gitignore</code>（不要 commit 進 repo 的檔案）和 <code>.dockerignore</code>（不要包進映像檔的檔案）：兩個是各自獨立的檔案，檔名開頭都有一個點，都寫了 <code>gha-creds-*.json</code>。這是 <code>google-github-actions/auth</code> 執行時寫在工作目錄的憑證設定檔，它在 job 結束時會被自動刪掉，但同一個 job 裡後面的步驟（例如 <code>docker build</code>）還看得到它，所以要排除，才不會被 commit 或包進映像檔。</p>



<p class="wp-block-paragraph"><code>.gitignore</code> 的內容：</p>



<pre class="wp-block-code"><code>gha-creds-*.json
__pycache__/</code></pre>



<p class="wp-block-paragraph"><code>.dockerignore</code> 的內容：</p>



<pre class="wp-block-code"><code>gha-creds-*.json
.git
.github
__pycache__</code></pre>



<p class="wp-block-paragraph">重點是第 6 個檔案 <code>.github/workflows/deploy.yml</code>。照做時<strong>只要改 <code>env:</code> 底下那 7 行的值</strong>：專案 ID、<code>WIF_PROVIDER</code> 裡的專案編號（步驟 7 查到的 <code>name</code>），還有映像檔路徑、兩個服務帳戶 email 裡的專案 ID；其他照抄：</p>



<pre class="wp-block-code"><code># 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&amp;audience=https://iam.googleapis.com/$WIF_PROVIDER" | jq -r .value)
          python3 - "$JWT" &lt;&lt;'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" &gt;&gt; "$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 }}"</code></pre>



<p class="wp-block-paragraph">逐段看重點：</p>


<ul class="wp-block-list">
<li><strong><code>permissions: id-token: write</code></strong>：允許這個 job 向 GitHub 要 OIDC 通行證。沒有這行，要通行證那步就會失敗。<a href="https://docs.github.com/en/actions/reference/security/oidc">GitHub 官方文件</a>寫明：<strong>它只開放「拿通行證」，不會給任何其他寫入權限</strong>（2026 年 12 月查）</li>

<li><strong>只在 <code>deploy</code> 開，<code>test</code> 不開</strong>：job 裡只要寫了 <code>permissions</code>，沒寫到的權限就是「沒有」。<code>test</code> 只有 <code>contents: read</code>（讀程式碼），測試程式就算被改壞，也拿不到 Google 憑證</li>

<li><strong><code>needs: test</code></strong>：<code>deploy</code> 要等 <code>test</code> 成功才跑，測試沒過就不會部署</li>

<li><strong><code>env:</code> 裡的提供者名稱和服務帳戶 email 不是秘密</strong>：看到它們的人也換不到權杖，因為條件只認你的 repo ID。<a href="https://github.com/google-github-actions/auth">google-github-actions/auth 官方 README</a> 的範例也是直接寫在 YAML 裡，不用放 Secrets</li>

<li><strong><code>google-github-actions/auth@v3</code></strong>：拿通行證去 STS 換身分、扮演 <code>do-14-deployer</code>，寫出一個憑證設定檔給後面的 <code>gcloud</code> 用。<code>token_format: access_token</code> 是多要一張存取權杖，給 <code>docker login</code> 推映像檔用</li>

<li><strong><code>gha-creds-*.json</code></strong>：auth 寫出來的憑證設定檔會放在工作目錄裡，job 結束才自動刪（官方 README 提醒），所以 <code>.gitignore</code> 和 <code>.dockerignore</code> 都要排除，免得被 commit 或包進映像檔</li>

<li><strong>映像檔標記用 commit 編號前 7 碼</strong>（<code>${GITHUB_SHA::7}</code>）：看映像檔名稱就知道是哪一版程式碼</li>

<li><strong><code>deploy-cloudrun@v3</code></strong> 的 <code>flags: --service-account=...</code>：指定網站用 <code>do-14-run</code> 的身分跑，這就是步驟 3 要給「服務帳戶使用者」的原因</li>
</ul>



<p class="wp-block-paragraph">action 的版本（<code>checkout@v7</code>、<code>auth@v3</code>、<code>deploy-cloudrun@v3</code>、<code>login-action@v4</code>）是寫稿時各自 GitHub 頁面上的最新主版本（2026 年 12 月查）。網路上很多範例還是 <code>auth@v0</code>、<code>checkout@v2</code>，太舊的版本跑在已經淘汰的 Node.js 上，會跳警告或不能跑。</p>



<h3 class="wp-block-heading">步驟 10：push，看 GitHub Actions 跑起來</h3>



<p class="wp-block-paragraph">把檔案 commit、push 到 <code>main</code>（用網頁新增的話，<code>deploy.yml</code> 存進 <code>main</code> 那一刻就會觸發）。到 repo 的 <strong>Actions</strong> 分頁就會看到它在跑：</p>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="609" src="https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-g1-actions-runs.png" alt="GitHub Actions 的 Actions 分頁：deploy-cloud-run 跑了 3 次，兩次 main 分支成功（52 秒、57 秒），try-other-branch 分支手動執行失敗（20 秒）" class="wp-image-14108" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-g1-actions-runs.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-g1-actions-runs-300x114.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-g1-actions-runs-1024x390.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-g1-actions-runs-768x292.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-g1-actions-runs-1536x585.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph">點第 2 次（commit <code>6976a9f</code>）進去，<code>test</code> 7 秒、<code>deploy</code> 44 秒，整條 57 秒：</p>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="514" src="https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-g2-run-summary.png" alt="GitHub Actions 執行摘要：commit 6976a9f push 到 main 觸發，狀態 Success，總共 57 秒，test job 7 秒接 deploy job 44 秒" class="wp-image-14109" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-g2-run-summary.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-g2-run-summary-300x96.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-g2-run-summary-1024x329.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-g2-run-summary-768x247.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-g2-run-summary-1536x493.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph">點 <code>deploy</code> 展開兩個檢查步驟，可以看到<strong>通行證寫了什麼</strong>和<strong>換到的憑證長什麼樣</strong>：</p>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="1412" src="https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-g3-token-claims.png" alt="deploy job 的紀錄：GitHub 通行證的 sub 是 repo:aaronlee700618@50737700/do-14-github-actions-demo@1483676804:ref:refs/heads/main、有效 300 秒；換到的憑證類型 external_account，透過 sts.googleapis.com 換、扮演 do-14-deployer，存取權杖 scope 是 cloud-platform、剩 3599 秒" class="wp-image-14110" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-g3-token-claims.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-g3-token-claims-300x265.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-g3-token-claims-1024x904.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-g3-token-claims-768x678.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-g3-token-claims-1536x1356.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<pre class="wp-block-code"><code>{
  "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"
}</code></pre>



<p class="wp-block-paragraph">這三段輸出，正好是換憑證的三個階段：</p>


<ol class="wp-block-list">
<li><strong>通行證</strong>：GitHub 發的，<code>iss</code> 是發行者，<code>sub</code> 寫著帳號、repo 和分支，<strong>有效 300 秒（5 分鐘）</strong></li>

<li><strong>憑證設定檔</strong>：<code>type</code> 是 <code>external_account</code>（外部身分），先到 <code>sts.googleapis.com</code> 換身分，再到 <code>iamcredentials</code> 扮演 <code>do-14-deployer</code></li>

<li><strong>存取權杖</strong>：<code>expires_in</code> 3599 秒，大約 1 小時後失效</li>
</ol>



<p class="wp-block-paragraph"><code>sub</code> 的格式是 <code>repo:帳號@帳號ID/repo@repoID:ref:分支</code>，跟很多舊文章寫的 <code>repo:帳號/repo:ref:分支</code> 不一樣。<a href="https://docs.github.com/en/actions/reference/security/oidc">GitHub 官方文件</a>說明：2026 年 7 月 15 日以後建立的 repo，<code>sub</code> 改成包含帳號 ID 和 repo ID 的固定格式，就是為了防 repo 名稱被搶註（2026 年 12 月查）。這篇的條件用的是 <code>repository_id</code>，不受影響；如果你的條件寫的是 <code>assertion.sub</code>，要照新格式改。</p>



<p class="wp-block-paragraph"><code>google-github-actions/auth</code> 的官方 README 在 WIF 那節警告：GitHub 通行證 5 分鐘過期，<strong>由它衍生的憑證也會在 5 分鐘後過期</strong>（2026 年 12 月查）。這篇用 <code>token_format: access_token</code> 另外產生的存取權杖，實測剩 3599 秒；但 deploy job 44 秒就跑完，兩種都碰不到期限。如果你的 job 會跑超過 5 分鐘，換憑證那步要放在真正用到之前，不要一開頭就換。</p>



<h3 class="wp-block-heading">步驟 11：打開網址</h3>



<p class="wp-block-paragraph">部署好的服務一開始打開是 <strong>403</strong>（拒絕存取）：</p>



<pre class="wp-block-code"><code>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</code></pre>



<pre class="wp-block-code"><code>https://do-14-hello-b5j2wtbgca-de.a.run.app
403</code></pre>



<p class="wp-block-paragraph">這是故意的。Cloud Run 預設只讓有權限的人呼叫；要變成公開網站，要關掉「叫用者 IAM 檢查」（Invoker IAM check），而這個動作需要 <code>run.services.setIamPolicy</code> 權限，<a href="https://cloud.google.com/run/docs/securing/managing-access">官方文件</a>寫在 Cloud Run 管理員（<code>roles/run.admin</code>）裡。部署帳戶只有開發人員，<strong>它沒辦法自己把服務改成公開</strong>，這正是最小權限想要的效果：管線只能「換版本」，不能「改誰看得到」。</p>



<p class="wp-block-paragraph">所以這步由專案擁有者（你自己）在 Cloud Shell 做一次就好，之後的部署會保留這個設定。公司的專案如果有組織政策 <code>constraints/run.managed.requireInvokerIam</code>（預設沒開），這個指令會被拒絕，不是你打錯，要找組織管理員處理：</p>



<pre class="wp-block-code"><code>gcloud run services update do-14-hello --region=$REGION --no-invoker-iam-check
curl -s $URL</code></pre>



<pre class="wp-block-code"><code>Updating...
Done.
Service [do-14-hello] has been updated.
Hello from do-14-github-actions-demo (7b153d9)</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="837" height="177" src="https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-16-curl-ok.png" alt="關掉 Cloud Run 叫用者 IAM 檢查之後，curl 網址回 Hello from do-14-github-actions-demo (7b153d9)，括號裡是第 1 次部署的 commit 編號" class="wp-image-14111" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-16-curl-ok.png 837w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-16-curl-ok-300x63.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-16-curl-ok-768x162.png 768w" sizes="(max-width: 837px) 100vw, 837px" /></figure>



<p class="wp-block-paragraph">括號裡的 <code>7b153d9</code> 就是第 1 次 push 的 commit 編號前 7 碼。再看每個版本是誰部署的：</p>



<pre class="wp-block-code"><code>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)'</code></pre>



<pre class="wp-block-code"><code>NAME                   DEPLOYED_BY                                             CREATED
do-14-hello-00001-nsq  do-14-deployer@dong-dong-gcp-3.iam.gserviceaccount.com  12/04 23:34</code></pre>



<p class="wp-block-paragraph">部署者是 <code>do-14-deployer</code>，不是我的個人帳號。</p>



<h3 class="wp-block-heading">步驟 12：確認真的沒有金鑰</h3>



<pre class="wp-block-code"><code>gcloud iam service-accounts keys list --iam-account=$DEPLOYER --managed-by=user; gcloud iam service-accounts keys list --iam-account=$DEPLOYER</code></pre>



<pre class="wp-block-code"><code>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</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="133" src="https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-18-keys-list.png" alt="gcloud keys list：使用者管理的金鑰 Listed 0 items；不加篩選時只看到一把 Google 自己管理的金鑰" class="wp-image-14112" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-18-keys-list.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-18-keys-list-300x25.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-18-keys-list-1024x85.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-18-keys-list-768x64.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-18-keys-list-1536x128.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>


<ul class="wp-block-list">
<li>第一行 <code>--managed-by=user</code>（使用者自己建立、可以下載的金鑰）：<strong>0 把</strong></li>

<li>不加篩選看到的那一把是 <strong>Google 自己管理的金鑰</strong>，用來簽發短效憑證。<a href="https://cloud.google.com/iam/docs/service-account-creds">官方文件</a>寫明：這種金鑰的私鑰一直由 Google 保管，任何人都拿不到，而且 Google 會定期自動換（2026 年 12 月查）</li>
</ul>



<h3 class="wp-block-heading">步驟 13：換一個分支跑，看它被擋下</h3>



<p class="wp-block-paragraph">建一個 <code>try-other-branch</code> 分支 push 上去，在 Actions 分頁選 deploy-cloud-run → Run workflow → 選這個分支手動執行（<code>workflow_dispatch</code> 就是允許手動執行）：</p>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="706" src="https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-g4-rejected-branch.png" alt="try-other-branch 分支執行失敗：通行證的 ref 是 refs/heads/try-other-branch，換 Google 短效憑證那步錯誤 unauthorized_client：The given credential is rejected by the attribute condition，後面的步驟都沒跑" class="wp-image-14113" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-g4-rejected-branch.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-g4-rejected-branch-300x132.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-g4-rejected-branch-1024x452.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-g4-rejected-branch-768x339.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-g4-rejected-branch-1536x678.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<pre class="wp-block-code"><code>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."}</code></pre>



<p class="wp-block-paragraph">同一個 repo、同一份 workflow，只是分支不同，<strong>在 STS 那關就被屬性條件拒絕</strong>，建映像檔、部署都沒跑。這就是「只有 <code>main</code> 能上線」：開發中的分支、別人送來的 PR 分支，都碰不到正式環境。</p>



<h3 class="wp-block-heading">步驟 14：用稽核記錄查「是哪個 repo 部署的」</h3>



<p class="wp-block-paragraph"><strong>Cloud Audit Logs</strong>（稽核記錄）是 Google Cloud 記錄「誰在什麼時候對哪個資源做了什麼」的服務。其中「管理活動」記錄（Admin Activity）預設就開著、不能關，部署 Cloud Run 會記在這裡。下面這段把最近 1 小時對 <code>do-14-hello</code> 的操作撈出來，換成台灣時間，<code>sed</code> 那段只是把我的 email 遮掉。指令很長，是因為 <code>jq</code> 要把記錄排成好讀的格式，照貼就好，重點看輸出：</p>



<pre class="wp-block-code"><code>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'</code></pre>



<pre class="wp-block-code"><code>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</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="333" src="https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-19-audit-log.png" alt="Cloud Audit Logs 查 do-14-hello 的操作：23:34:41 建立服務、23:37:00 更新服務，都是 do-14-deployer 代表 GitHub repo do-14-github-actions-demo 的 main 分支做的；23:35:52 那次是自己的帳號手動操作" class="wp-image-14114" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-19-audit-log.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-19-audit-log-300x62.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-19-audit-log-1024x213.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-19-audit-log-768x160.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-19-audit-log-1536x320.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>


<ul class="wp-block-list">
<li><strong>23:34:41 CreateService</strong>：第 1 次部署，建立服務</li>

<li><strong>23:35:52 ReplaceService</strong>：我手動關掉叫用者 IAM 檢查（步驟 11）</li>

<li><strong>23:37:00 ReplaceService</strong>：第 2 次部署</li>
</ul>



<p class="wp-block-paragraph">「代表」那欄來自 <code>serviceAccountDelegationInfo</code>（服務帳戶代理資訊），<strong>直接寫出是哪個 repo、哪個分支扮演了部署帳戶</strong>。用金鑰檔的話，記錄只會看到服務帳戶的名字，查不出是哪條管線、哪台機器用了那把金鑰。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">動手做：GitLab CI 用 WIF 部署同一個服務</h2>



<p class="wp-block-paragraph">GitLab 是另一個常見的程式碼平台，CI/CD 叫 <strong>GitLab CI</strong>，設定檔是 repo 根目錄的 <code>.gitlab-ci.yml</code>；跑 job 的機器叫 <strong>GitLab Runner</strong>，要自己裝。這個系列在 GCP 開了一台 VM（虛擬機器，在雲端租的一台電腦）自架 GitLab（<code>gitlab-ee</code> 套件、版本 19.6.2，網址 <code>https://35-229-139-139.sslip.io</code>），Runner 也裝在同一台。</p>


<ul class="wp-block-list">
<li><strong>沒有自架 GitLab 的話，這段可以只看不做</strong>：GitHub 那段已經是完整流程，這段是給公司用 GitLab 的人對照寫法；只想學 GitHub 的話，直接跳到「金鑰、WIF＋GitHub、WIF＋GitLab 一張表」</li>

<li><strong>自己架的話會花錢</strong>：這台 VM 是 e2-standard-4（4 vCPU、16 GB 記憶體）加 50 GB 開機磁碟，開著就按秒計費。我建立時加了 <code>--max-run-duration=8h --instance-termination-action=DELETE</code>，8 小時後自動刪除；你自己架的話，用完一定要刪 VM 和磁碟</li>

<li><strong>sslip.io</strong> 是一個免費的網域服務，網址裡寫 IP，就會解析到那個 IP，不用買網域；再用 Let&#8217;s Encrypt 申請免費的 HTTPS 憑證</li>

<li><strong>為什麼 GitLab 一定要能從網路上連到</strong>：Google STS 驗通行證時，會去 GitLab 拿公開的簽名鑰匙。GitLab 在公司內網、外面連不到的話，可以改成把鑰匙檔上傳給提供者（<code>--jwk-json-path</code>）</li>

<li><strong>流程跟 GitHub 一樣</strong>：GitLab 發通行證 → STS 驗證、看條件 → 扮演服務帳戶 → 部署。差別在 GitLab 沒有官方的「auth action」，要用 <code>gcloud</code> 自己產生憑證設定檔</li>
</ul>



<h3 class="wp-block-heading">步驟 1：確認 GitLab 有公開的 OIDC 資訊</h3>



<p class="wp-block-paragraph">OIDC 規定發行者要在 <code>/.well-known/openid-configuration</code> 放一份公開的說明：</p>



<pre class="wp-block-code"><code>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}'</code></pre>



<pre class="wp-block-code"><code>{
  "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"
  ]
}</code></pre>



<p class="wp-block-paragraph"><code>issuer</code> 是發行者、<code>jwks_uri</code> 是簽名鑰匙的位置。從 Cloud Shell 打得到，Google 就打得到。</p>



<h3 class="wp-block-heading">步驟 2：在同一個集區加 GitLab 提供者</h3>



<pre class="wp-block-code"><code>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' &amp;&amp; assertion.ref=='main'"</code></pre>



<pre class="wp-block-code"><code>Created workload identity pool provider [do-14-gitlab].</code></pre>



<p class="wp-block-paragraph">跟 GitHub 不一樣的地方，照 <a href="https://docs.gitlab.com/ci/cloud_services/google_cloud/">GitLab 官方文件</a>（2026 年 12 月查）：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>設定</th><th>GitLab 要怎麼填</th><th>為什麼</th></tr></thead><tbody><tr><td><code>--issuer-uri</code></td><td>GitLab 網址，<strong>結尾要加 <code>/</code></strong></td><td>GitLab 文件規定</td></tr><tr><td><code>--allowed-audiences</code></td><td>GitLab 網址，<strong>結尾不加 <code>/</code></strong></td><td>通行證的 <code>aud</code>（發給誰）要跟這裡一樣才收</td></tr><tr><td>屬性條件</td><td><code>project_path</code>（專案路徑）＋<code>ref</code>（分支或標籤的名稱）</td><td>只收 <code>root/do-14-gitlab-ci</code> 專案、名稱是 <code>main</code> 的 ref</td></tr></tbody></table></figure>



<p class="wp-block-paragraph"><strong>這篇實測的條件為了好讀做了簡化，正式環境要再補兩個地方</strong>：</p>


<ul class="wp-block-list">
<li><strong>加上 <code>ref_type=='branch'</code></strong>：GitLab 通行證裡的 <code>ref</code> 只是名稱，分支和標籤（tag，替某個版本貼的名牌）都可能叫 <code>main</code>；<code>ref_type</code> 欄位才分得出是 <code>branch</code> 還是 <code>tag</code>（<a href="https://docs.gitlab.com/ci/secrets/id_token_authentication/">GitLab 官方文件</a>，2026 年 12 月查）。只比 <code>ref=='main'</code> 的話，有人建一個叫 <code>main</code> 的標籤，從標籤跑的 job 也會通過</li>

<li><strong>改用數字的 <code>project_id</code></strong>：Google 官方文件建議 GitLab 用數字的 <code>project_id</code>、<code>namespace_id</code>，原因跟 GitHub 用 repo ID 一樣，專案刪掉後，路徑可能被別人重新建立</li>
</ul>



<p class="wp-block-paragraph">另外把 <code>main</code> 設成受保護分支（protected branch，只有指定的人能 push）。條件寫起來像下面這樣，<code>12345</code> 換成你的專案 ID（專案 Settings → General 看得到）。提供者已經建好的話，用 <code>update-oidc</code> 改條件就好，不用刪掉重建。<strong>這行我沒有實測</strong>，下一步授權那行的 <code>attribute.project_path/root/do-14-gitlab-ci</code> 也要跟著換成 <code>attribute.project_id/12345</code>：</p>



<pre class="wp-block-code"><code>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' &amp;&amp; assertion.ref=='main' &amp;&amp; assertion.ref_type=='branch'"</code></pre>



<h3 class="wp-block-heading">步驟 3：建 GitLab 專用的部署帳戶</h3>



<p class="wp-block-paragraph">官方建議每條管線一個服務帳戶，GitLab 另外建 <code>do-14-gl-deployer</code>，給角色、允許 GitLab 專案扮演它：</p>



<pre class="wp-block-code"><code>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</code></pre>



<pre class="wp-block-code"><code>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].</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="297" src="https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-22-gitlab-sa-roles.png" alt="剛建好服務帳戶就馬上綁角色，兩條回 INVALID_ARGUMENT：Service account does not exist，最後一條綁在服務帳戶本身的成功" class="wp-image-14115" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-22-gitlab-sa-roles.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-22-gitlab-sa-roles-300x56.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-22-gitlab-sa-roles-1024x190.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-22-gitlab-sa-roles-768x143.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-22-gitlab-sa-roles-1536x285.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph">服務帳戶剛建好，其他服務還「看不到」它（IAM 的變更要一點時間傳到各處），所以馬上綁角色的兩條失敗了，綁在服務帳戶自己身上的那條成功。<strong>等幾秒、重跑失敗的兩條就好</strong>：</p>



<pre class="wp-block-code"><code>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</code></pre>



<pre class="wp-block-code"><code>Updated IAM policy for project [dong-dong-gcp-3].
Updated IAM policy for serviceAccount [do-14-run@dong-dong-gcp-3.iam.gserviceaccount.com].</code></pre>



<h3 class="wp-block-heading">步驟 4：裝 GitLab Runner、註冊到專案</h3>



<p class="wp-block-paragraph">Runner 用 <strong>shell 執行器</strong>（executor）：job 直接在 Runner 那台機器的 bash 裡跑，最簡單，但機器上要先有 job 會用到的工具（這台有 <code>gcloud</code> 和 <code>python3</code>）。安裝照 <a href="https://docs.gitlab.com/runner/install/linux-repository/">GitLab 官方文件</a>加套件庫再 <code>apt-get install gitlab-runner</code>，裝好的版本是 19.6.2。</p>



<p class="wp-block-paragraph">註冊的做法：專案的 <strong>Settings → CI/CD → Runners → Create project runner</strong>，GitLab 會給一串 <code>glrt-</code> 開頭的 Runner 驗證權杖，再到機器上跑：</p>



<pre class="wp-block-code"><code>sudo gitlab-runner register --non-interactive --url "https://你的 GitLab 網址" --token "glrt-你拿到的權杖" --executor shell --description do-14-shell-runner</code></pre>



<p class="wp-block-paragraph"><strong>這串 Runner 權杖是秘密</strong>，拿到的人可以冒充你的 Runner 接 job，不要貼到截圖、聊天群組或 log 裡。註冊好之後，專案的 Runners 頁會看到它在線上（截圖裡 Runner 編號後面的短代碼是權杖的開頭，我遮掉了）：</p>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="601" src="https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-l1-gitlab-runner.png" alt="GitLab 專案 do-14-gitlab-ci 的 CI/CD 設定頁，Runners 區塊有一個綠色 Online 的專案 Runner，版本 19.6.2，名稱 do-14-shell-runner" class="wp-image-14116" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-l1-gitlab-runner.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-l1-gitlab-runner-300x113.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-l1-gitlab-runner-1024x385.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-l1-gitlab-runner-768x288.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-l1-gitlab-runner-1536x577.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph">Runner 裝在 GCE（Compute Engine）的 VM 上，本來也可以直接用 VM 自己的服務帳戶。但那樣<strong>同一台 Runner 上所有專案的 job 都拿到同一個身分</strong>；用 WIF 才能做到「只有 <code>root/do-14-gitlab-ci</code> 的 <code>main</code> 分支能部署」。</p>



<h3 class="wp-block-heading">步驟 5：寫 <code>.gitlab-ci.yml</code></h3>



<p class="wp-block-paragraph">這台 Runner 沒裝 Docker，所以 GitLab 這條不建映像檔，直接部署 GitHub 那條建好的同一個映像檔（<code>6976a9f</code>），只把版本文字改成 <code>gitlab-</code> 開頭，好分辨是哪邊部署的：</p>



<pre class="wp-block-code"><code># 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" &gt; .gitlab_oidc_token
    - |
      # 看通行證寫了什麼（只印欄位，不印權杖）
      python3 - &lt;&lt;'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</code></pre>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>寫法</th><th>意思</th></tr></thead><tbody><tr><td><code>rules: if: $CI_COMMIT_BRANCH == "main"</code></td><td>只讓 <code>deploy</code> job 在 <code>main</code> 分支執行。這只是「不要在別的分支跑」，<strong>不是安全關卡</strong>：能改 CI 檔的人也能改掉這行，真正擋人的是提供者的屬性條件和受保護分支</td></tr><tr><td><code>id_tokens:</code></td><td>GitLab 版的 <code>id-token: write</code>：寫在哪個 job，GitLab 才發通行證給那個 job，放進 <code>GITLAB_OIDC_TOKEN</code> 變數</td></tr><tr><td><code>aud:</code></td><td>通行證「發給誰」，要跟提供者的 <code>--allowed-audiences</code> 一樣</td></tr><tr><td><code>create-cred-config</code></td><td>gcloud 產生「去哪裡拿通行證、換成哪個服務帳戶」的設定檔，內容不含任何秘密</td></tr><tr><td><code>CLOUDSDK_AUTH_CREDENTIAL_FILE_OVERRIDE</code></td><td>叫這個 job 裡的 gcloud 改用這個設定檔登入</td></tr><tr><td><code>after_script</code></td><td>不管成功失敗都會跑，把通行證和設定檔刪掉</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">GitLab 官方文件的範例是用 <code>curl</code> 自己打 STS 換權杖；這篇改用 <code>gcloud iam workload-identity-pools create-cred-config</code>，一行就產生設定檔，後面 gcloud 會自己換。另外，舊的 <code>CI_JOB_JWT_V2</code> 變數<a href="https://docs.gitlab.com/ci/cloud_services/google_cloud/">在 GitLab 17.0 已經移除</a>，網路上舊文章用它的，要改成 <code>id_tokens</code>。</p>



<h3 class="wp-block-heading">步驟 6：push，第一次部署失敗</h3>



<p class="wp-block-paragraph">push 之後 <code>test</code> 過了，<code>deploy</code> 失敗：</p>



<pre class="wp-block-code"><code>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).</code></pre>



<p class="wp-block-paragraph">換身分是成功的（失敗的話，錯誤會出在換憑證那一步，不會走到部署），卡在<strong>讀不到映像檔</strong>。GitHub 那邊的部署帳戶有存放區的「寫入者」，寫入者本來就包含讀取，所以沒事；GitLab 這個帳戶只部署、不推映像檔，我漏給「讀取者」。這也是 Cloud Run <a href="https://cloud.google.com/run/docs/deploying">官方部署角色</a>第 3 個：映像檔所在存放區的 Artifact Registry 讀取者。補上：</p>



<pre class="wp-block-code"><code>gcloud artifacts repositories add-iam-policy-binding do-14-repo --location=$REGION --member=serviceAccount:$GL_DEPLOYER --role=roles/artifactregistry.reader --format=none</code></pre>



<pre class="wp-block-code"><code>Updated IAM policy for repository [do-14-repo].</code></pre>



<h3 class="wp-block-heading">步驟 7：重跑，成功</h3>



<p class="wp-block-paragraph">在 job 頁按 Retry，這次通過，整條管線 13 秒（排隊 5 秒）：</p>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="604" src="https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-l2-gitlab-pipeline.png" alt="GitLab 管線 #4：commit 757a3fac 在 main 分支，Passed，test 和 deploy 兩個 stage 都通過，13 秒、排隊 5 秒" class="wp-image-14117" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-l2-gitlab-pipeline.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-l2-gitlab-pipeline-300x113.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-l2-gitlab-pipeline-1024x387.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-l2-gitlab-pipeline-768x290.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-l2-gitlab-pipeline-1536x580.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph">deploy job 的紀錄裡可以看到 GitLab 發的通行證，和 gcloud 部署的過程：</p>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="1622" src="https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-l3-gitlab-deploy-job.png" alt="GitLab deploy job #23 紀錄：通行證 sub 是 project_path:root/do-14-gitlab-ci:ref_type:branch:ref:main、aud 是 GitLab 網址、有效 3600 秒；gcloud create-cred-config 產生 .gcp_creds.json，接著 gcloud run deploy 部署出修訂版本 do-14-hello-00003-6bb，job 11 秒成功" class="wp-image-14118" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-l3-gitlab-deploy-job.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-l3-gitlab-deploy-job-296x300.png 296w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-l3-gitlab-deploy-job-1010x1024.png 1010w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-l3-gitlab-deploy-job-768x779.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-l3-gitlab-deploy-job-1515x1536.png 1515w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<pre class="wp-block-code"><code>{
  "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.</code></pre>



<p class="wp-block-paragraph">GitLab 的通行證有效 <strong>3600 秒</strong>，比 GitHub 的 300 秒長很多。<a href="https://docs.gitlab.com/ci/secrets/id_token_authentication/">GitLab 官方文件</a>寫明：ID 權杖的有效時間等於 job 的逾時設定，沒設逾時才是 5 分鐘（2026 年 12 月查）。這個專案的逾時是預設的 1 小時，所以是 3600 秒。</p>



<p class="wp-block-paragraph">回 Cloud Shell 確認網站和部署者：</p>



<pre class="wp-block-code"><code>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)'</code></pre>



<pre class="wp-block-code"><code>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</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="187" src="https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-25-gitlab-deployed.png" alt="curl 網址回 Hello from do-14-github-actions-demo (gitlab-757a3fac)；revisions list 顯示第 3 版由 do-14-gl-deployer 部署，前兩版由 do-14-deployer 部署" class="wp-image-14119" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-25-gitlab-deployed.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-25-gitlab-deployed-300x35.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-25-gitlab-deployed-1024x120.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-25-gitlab-deployed-768x90.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-25-gitlab-deployed-1536x180.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph">網站文字變成 <code>gitlab-757a3fac</code>，第 3 版的部署者是 GitLab 專用的 <code>do-14-gl-deployer</code>。同一個服務，兩條管線各用各的身分，從部署者就分得出來。</p>



<p class="wp-block-paragraph">稽核記錄只撈「有代表別人」的操作：</p>



<pre class="wp-block-code"><code>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)"'</code></pre>



<pre class="wp-block-code"><code>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</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="279" src="https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-26-audit-log-gitlab.png" alt="稽核記錄：23:59:22 和 00:04:02 兩次 ReplaceService 都是 do-14-gl-deployer 代表 GitLab 專案 root/do-14-gitlab-ci 的 main 分支做的" class="wp-image-14120" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-26-audit-log-gitlab.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-26-audit-log-gitlab-300x52.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-26-audit-log-gitlab-1024x179.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-26-audit-log-gitlab-768x134.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-26-audit-log-gitlab-1536x268.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph">23:59:22 那筆是步驟 6 <strong>失敗</strong>的那次（我另外查了那筆的狀態碼是 7，也就是 <code>PERMISSION_DENIED</code>）。稽核記錄連失敗的嘗試都會記，而且一樣寫出是哪個 GitLab 專案、哪個分支。</p>



<h3 class="wp-block-heading">實測時的意外</h3>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph"><strong>1. 不加屬性條件，提供者建不起來</strong>：2023 年的中文教學建 GitHub 提供者只設屬性對應，現在照做會得到 <code>INVALID_ARGUMENT: The attribute condition must reference one of the provider's claims</code>。Google 已經把 GitHub 這類共用網址平台的屬性條件改成必填（步驟 6）。</p>



<p class="wp-block-paragraph"><strong>2. 綁完權限馬上 push，第一次換憑證 403</strong>：GitHub 第 1 次跑在換憑證那步失敗，<code>Permission 'iam.serviceAccounts.getAccessToken' denied</code>。設定是對的，只是 IAM 綁定還沒傳開；約 1 分鐘後按 Re-run failed jobs 就過了。官方 README 寫明集區、提供者、權限要等最多 5 分鐘才會生效。</p>



<p class="wp-block-paragraph"><strong>3. 部署完網址是 403</strong>：部署帳戶沒有改存取權限的權限，沒辦法自己把服務設成公開，要擁有者手動關一次叫用者 IAM 檢查（步驟 11）。</p>



<p class="wp-block-paragraph"><strong>4. 剛建好的服務帳戶，馬上綁角色說它不存在</strong>：<code>Service account ... does not exist</code>，等幾秒重跑就好（GitLab 步驟 3）。</p>



<p class="wp-block-paragraph"><strong>5. GitLab 部署帳戶少了存放區讀取者</strong>：換身分成功，但 <code>artifactregistry.repositories.downloadArtifacts</code> 被拒。只部署、不推映像檔的帳戶，也要能讀映像檔（GitLab 步驟 6）。</p>



<p class="wp-block-paragraph"><strong>6. GitLab 第一次 push 自己跑了一條管線</strong>：還沒放 <code>.gitlab-ci.yml</code> 時，自架 GitLab 預設開著 Auto DevOps（自動幫你猜要怎麼建置的功能），跑了一條 build、test、code_quality 都失敗的管線。放了 <code>.gitlab-ci.yml</code> 之後就照我們的檔案跑。</p>



<p class="wp-block-paragraph"><strong>7. <code>gitlab-runner unregister</code> 不會刪掉 GitLab 上的 Runner</strong>：清理時跑了解除註冊，訊息是 <code>Unregistering runner manager from GitLab succeeded</code>，只刪掉「這台機器」的登記，專案 Runners 頁上的 Runner 還在，要另外按刪除（做法在「用完記得刪」那節）。</p>
</blockquote>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">金鑰、WIF＋GitHub、WIF＋GitLab 一張表</h2>



<p class="wp-block-paragraph">只想抓重點的話，看前兩列就好：用金鑰要一直保管一個永不過期的檔案，用 WIF 沒有東西要保管，通行證幾分鐘到 1 小時就失效。</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th></th><th>服務帳戶金鑰（JSON 檔）</th><th>WIF＋GitHub Actions</th><th>WIF＋自架 GitLab CI</th></tr></thead><tbody><tr><td>要保管的秘密</td><td>金鑰檔，放 Secrets</td><td>沒有</td><td>沒有</td></tr><tr><td>通行證有效時間</td><td>金鑰預設永不過期</td><td>300 秒（實測）</td><td>等於 job 逾時，3600 秒（實測）</td></tr><tr><td>Google 憑證有效時間</td><td>用金鑰隨時換</td><td>存取權杖 3599 秒（實測）</td><td>預設約 1 小時（這條沒印出來量）</td></tr><tr><td>限制誰能用</td><td>拿到檔案就能用</td><td>repo ID＋<code>main</code> 分支</td><td>專案路徑＋<code>main</code>（正式環境改專案 ID、加 <code>ref_type</code>）</td></tr><tr><td>管線裡怎麼寫</td><td>讀金鑰檔登入</td><td><code>id-token: write</code>＋<code>google-github-actions/auth@v3</code></td><td><code>id_tokens:</code>＋<code>gcloud iam workload-identity-pools create-cred-config</code></td></tr><tr><td>稽核記錄看得到</td><td>只有服務帳戶名稱</td><td>服務帳戶＋repo＋分支</td><td>服務帳戶＋專案＋分支</td></tr><tr><td>這次實測部署 job</td><td>沒測</td><td>44 秒（含建映像檔）</td><td>11 秒（只部署）</td></tr></tbody></table></figure>



<p class="wp-block-paragraph"><strong>這次碰到的錯誤訊息對照</strong>（都是實際跑出來的）：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>情境</th><th>錯誤訊息</th><th>怎麼辦</th></tr></thead><tbody><tr><td>提供者沒加屬性條件</td><td><code>INVALID_ARGUMENT: The attribute condition must reference one of the provider's claims.</code></td><td>加 <code>--attribute-condition</code></td></tr><tr><td>不是 <code>main</code> 分支</td><td><code>unauthorized_client</code>：<code>The given credential is rejected by the attribute condition.</code></td><td>預期中的擋下</td></tr><tr><td>剛綁完就跑</td><td><code>Permission 'iam.serviceAccounts.getAccessToken' denied</code></td><td>等幾分鐘重跑</td></tr><tr><td>剛建服務帳戶就綁角色</td><td><code>Service account ... does not exist.</code></td><td>等幾秒重跑</td></tr><tr><td>部署帳戶讀不到映像檔</td><td><code>Permission 'artifactregistry.repositories.downloadArtifacts' denied</code></td><td>給存放區讀取者</td></tr><tr><td>刪掉的集區 30 天內重建</td><td><code>ALREADY_EXISTS: Requested entity already exists</code></td><td>換名字，或用 <code>undelete</code> 救回</td></tr></tbody></table></figure>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">GKE 的 Workload Identity 跟這篇的 WIF 差在哪</h2>



<p class="wp-block-paragraph">名字幾乎一樣，用的地方不同。<a href="https://dongdonggcp.com/2026/11/21/gke-workload-identity-federation-without-service-account-keys/">容器系列第 26 篇〈Workload Identity 是什麼？GKE 不用金鑰安全存取 GCP 服務〉</a>講的是 <strong>GKE 叢集裡的 Pod</strong>（GKE 上跑程式的最小單位）怎麼拿身分；這篇講的是 <strong>GCP 外面的程式</strong>（GitHub、GitLab、AWS、Azure、自己的機房）怎麼拿身分。</p>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1200" height="675" src="https://dongdonggcp.com/wp-content/uploads/2026/12/do14-cards-03-gke-wi-vs-wif.png" alt="GKE 的 Workload Identity 和 Workload Identity Federation 比較：前者給 GKE 叢集裡的 Pod 用，集區由 GKE 自動建、固定叫專案 ID.svc.id.goog；後者給 GCP 外面的程式用，集區、提供者、屬性條件都要自己建；共同點是拿別處發的身分換 Google 短效憑證" class="wp-image-14121" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do14-cards-03-gke-wi-vs-wif.png 1200w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-cards-03-gke-wi-vs-wif-300x169.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-cards-03-gke-wi-vs-wif-1024x576.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-cards-03-gke-wi-vs-wif-768x432.png 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<p class="wp-block-paragraph">GKE 的那個在 2024 年改名為 <strong>Workload Identity Federation for GKE</strong>，名字也有 Federation，因為底層是同一套：拿「別處發的身分」換 Google 短效憑證。考試看到「GKE 上的 Pod 要存取 Cloud Storage」選 GKE 那個；看到「GitHub Actions、其他雲、地端程式要存取 GCP」選這篇的 WIF。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">用完記得刪</h2>



<p class="wp-block-paragraph">這篇建了：Cloud Run 服務、Artifact Registry 存放區、3 個服務帳戶、身分集區和 2 個提供者、專案層級的 2 條 IAM 授權，還有 GitLab Runner。<strong>不刪會怎麼計費</strong>：</p>


<ul class="wp-block-list">
<li><strong>Cloud Run</strong>：沒人打網址時縮到 0 台，不收運算費</li>

<li><strong>Artifact Registry</strong>：每個帳單帳戶每月前 0.5 GB 免費，超過每 GB 每小時 0.000136986 美元（2026 年 12 月查<a href="https://cloud.google.com/artifact-registry/pricing">官方定價</a>）。算一次：0.000136986 × 730 小時 ≈ <strong>每 GB 每月 0.1 美元</strong>。這篇只有一個小映像檔，但存放區不刪，每次 push 的映像檔都會一直累積</li>

<li><strong>服務帳戶、身分集區、提供者</strong>：不收費，但留著就是「一扇沒人看管的門」，該刪</li>
</ul>



<p class="wp-block-paragraph">先拿掉專案層級的授權（存放區、服務帳戶上的授權會跟著資源一起刪掉）：</p>



<pre class="wp-block-code"><code>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</code></pre>



<pre class="wp-block-code"><code>Updated IAM policy for project [dong-dong-gcp-3].
Updated IAM policy for project [dong-dong-gcp-3].</code></pre>



<p class="wp-block-paragraph">為什麼先拿授權再刪帳戶？服務帳戶刪掉後，專案授權裡會留下 <code>deleted:serviceAccount:...</code> 的殘留項目，先拿掉比較乾淨。</p>



<p class="wp-block-paragraph">刪 Cloud Run 服務和存放區（<code>--quiet</code> 是不要再問「確定嗎」）：</p>



<pre class="wp-block-code"><code>gcloud run services delete do-14-hello --region=$REGION --quiet; gcloud artifacts repositories delete do-14-repo --location=$REGION --quiet</code></pre>



<pre class="wp-block-code"><code>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].</code></pre>



<p class="wp-block-paragraph">刪 3 個服務帳戶：</p>



<pre class="wp-block-code"><code>for sa in $DEPLOYER $GL_DEPLOYER $RUNTIME; do gcloud iam service-accounts delete $sa --quiet; done</code></pre>



<pre class="wp-block-code"><code>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]</code></pre>



<p class="wp-block-paragraph">刪提供者和集區：</p>



<pre class="wp-block-code"><code>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</code></pre>



<pre class="wp-block-code"><code>Deleted workload identity pool provider [do-14-github].
Deleted workload identity pool provider [do-14-gitlab].
Deleted workload identity pool [do-14-pool].</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="993" height="211" src="https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-30-cleanup-pool.png" alt="清理：刪掉 do-14-github、do-14-gitlab 兩個提供者和 do-14-pool 集區" class="wp-image-14122" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-30-cleanup-pool.png 993w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-30-cleanup-pool-300x64.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-30-cleanup-pool-768x163.png 768w" sizes="(max-width: 993px) 100vw, 993px" /></figure>



<p class="wp-block-paragraph"><strong>刪掉的集區 30 天內不能用同一個名字重建</strong>。看一下刪掉的集區，再試著建同名的：</p>



<pre class="wp-block-code"><code>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</code></pre>



<pre class="wp-block-code"><code>POOL        STATE    PURGE_AFTER
do-14-pool  DELETED  2027-01-04
ERROR: (gcloud.iam.workload-identity-pools.create) ALREADY_EXISTS: Requested entity already exists</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="195" src="https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-31-pool-name-reserved.png" alt="刪掉的 do-14-pool 狀態是 DELETED、2027-01-04 才永久刪除；這段期間建同名集區回 ALREADY_EXISTS" class="wp-image-14123" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-31-pool-name-reserved.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-31-pool-name-reserved-300x37.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-31-pool-name-reserved-1024x125.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-31-pool-name-reserved-768x94.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/12/do14-shots-31-pool-name-reserved-1536x187.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph"><a href="https://cloud.google.com/iam/docs/manage-workload-identity-pools-providers">官方文件</a>寫明：刪掉的集區 30 天內可以用 <code>gcloud iam workload-identity-pools undelete</code> 救回，30 天後才永久刪除，<strong>永久刪除前不能重用這個名字</strong>（2026 年 12 月查）。照著做第二次，名字換一個（例如 <code>do-14-pool2</code>）就好。</p>



<p class="wp-block-paragraph"><strong>GitLab Runner</strong>：在 Runner 那台機器上解除註冊，再到專案 Settings → CI/CD → Runners 按垃圾桶刪掉 Runner：</p>



<pre class="wp-block-code"><code>sudo gitlab-runner unregister --name do-14-shell-runner</code></pre>



<pre class="wp-block-code"><code>Unregistering runner manager from GitLab succeeded  runner=（略） runner_name=do-14-shell-runner
Updated /etc/gitlab-runner/config.toml</code></pre>



<p class="wp-block-paragraph"><strong>GitHub repo</strong>：裡面沒有任何秘密，可以留著當範本；要刪就到 repo 的 Settings 最下面按 Delete this repository。</p>



<p class="wp-block-paragraph">API 我沒關：<code>sts.googleapis.com</code> 這些 API 開著不收費，同專案別的服務也可能在用。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">證照會怎麼考</h2>



<p class="wp-block-paragraph">Professional Cloud DevOps Engineer 考試 2 小時、50～60 題選擇題、報名費 200 美元，考試語言英文和日文（2026 年 11 月查<a href="https://cloud.google.com/learn/certification/cloud-devops-engineer">官方考試頁</a>）。2026 年 11 月 23 日起適用<a href="https://services.google.com/fh/files/misc/112326_professional_cloud_devops_engineer_exam_guide_english.pdf">新版考綱</a>。</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>考綱小節（新版）</th><th>原文重點</th><th>這篇對應的地方</th></tr></thead><tbody><tr><td><strong>2.3 管理管線設定與秘密</strong></td><td>設定與秘密管理（Secret Manager、Workload Identity Federation…）、<strong>管理短效憑證（新版新增）</strong></td><td>整篇：5 分鐘通行證換 1 小時權杖、0 把金鑰</td></tr><tr><td><strong>1.3 設計 CI/CD 架構</strong></td><td>混合雲、多雲環境；Git 等第三方工具；<strong>CI/CD 工具的安全性</strong></td><td>GitHub、GitLab 兩條管線接 GCP</td></tr><tr><td><strong>1.1 資源階層設計</strong></td><td>建立與管理服務帳戶</td><td>部署帳戶、執行帳戶分開，每條管線一個</td></tr><tr><td><strong>2.2 實作與管理管線</strong></td><td>稽核和追蹤部署（Cloud Audit Logs）</td><td>步驟 14 查出是哪個 repo、哪個分支</td></tr><tr><td><strong>2.4 保護部署管線</strong></td><td>依環境設計 IAM 政策</td><td>屬性條件只放行 <code>main</code>、最小權限角色</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">新版 2.3 跟舊版比，只多了最後一條「Managing short-lived credentials」，Workload Identity Federation 舊版就列在 2.3 裡了。</p>



<p class="wp-block-paragraph"><strong>看到這些字，就想到這個</strong>（情境題的判斷關鍵字）：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>題目關鍵字</th><th>想到</th></tr></thead><tbody><tr><td>「GitHub Actions／GitLab／Jenkins 要部署到 GCP」「不想存長期憑證」</td><td>Workload Identity Federation＋扮演服務帳戶</td></tr><tr><td>「組織政策禁止建立服務帳戶金鑰」</td><td><code>iam.disableServiceAccountKeyCreation</code>，改用 WIF</td></tr><tr><td>「只允許某個 repo、某個分支部署」</td><td>提供者的屬性條件（attribute condition）</td></tr><tr><td>「防止 repo 改名或刪除後被冒用」</td><td>條件用數字 ID（<code>repository_id</code>、<code>project_id</code>），不用名稱</td></tr><tr><td>「要知道是哪條管線部署的」</td><td>Cloud Audit Logs 的 <code>serviceAccountDelegationInfo</code></td></tr><tr><td>「GKE 上的 Pod 要存取 GCP 服務」</td><td>Workload Identity Federation for GKE（不是這篇的設定）</td></tr><tr><td>「CI 要用資料庫密碼、第三方 API 金鑰」</td><td>Secret Manager；WIF 解決的是「登入 GCP」，不是所有秘密</td></tr><tr><td>「部署帳戶權限最小化」</td><td><code>run.developer</code>＋服務帳戶使用者＋存放區讀取，不給 <code>run.admin</code>、不給編輯者</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">考試範圍完整的準備地圖在第 1 篇：<a href="https://dongdonggcp.com/2026/11/28/gcp-devops-certification-guide/">GCP DevOps 證照怎麼考？2026 新版考綱、比重與準備地圖</a>。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">面試會怎麼問</h2>


<ul class="wp-block-list">
<li><strong>「你們的 CI/CD 怎麼拿雲端權限？」</strong>：說「用 Workload Identity Federation，CI 平台發 OIDC 權杖，Google 驗證後換短效憑證，repo 和 Secrets 裡沒有金鑰」，再補一句「提供者有屬性條件，只放行指定 repo 的 main 分支」</li>

<li><strong>「為什麼不用服務帳戶金鑰？」</strong>：金鑰預設永不過期、外流了誰拿到都能用，稽核記錄也查不出是誰在用；短效憑證 1 小時就失效，記錄裡看得到是哪個 repo</li>

<li><strong>「<code>id-token: write</code> 是什麼？會不會很危險？」</strong>：只是允許 job 向 GitHub 要 OIDC 權杖，不給其他寫入權限；只開在需要部署的 job</li>

<li><strong>「部署帳戶要給哪些角色？」</strong>：Cloud Run 開發人員、執行身分的服務帳戶使用者、存放區讀取（要推映像檔就給寫入）；不給管理員，所以管線不能改服務的公開設定</li>

<li><strong>「GitHub 和 GitLab 的做法差在哪？」</strong>：觀念一樣，差在拿通行證的寫法（<code>id-token: write</code> 對 <code>id_tokens:</code>）、通行證有效時間（5 分鐘對 job 逾時）、條件欄位（repo ID 對 project ID），GitLab 的發行者網址結尾要加斜線</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">常見問答</h2>



<h3 class="wp-block-heading">GitHub Actions 部署 GCP 一定要用 Workload Identity Federation 嗎？</h3>



<p class="wp-block-paragraph">不一定，但它是 Google 官方推薦的做法。舊做法是把服務帳戶金鑰（JSON 檔）放進 GitHub Secrets，金鑰預設永不過期，外流了誰拿到都能用；而且 2024 年 5 月 3 日以後建立的 GCP 機構，預設就禁止建立金鑰。用 WIF，repo 和 Secrets 裡都沒有金鑰，GitHub 每次發一張 5 分鐘的通行證，換成 1 小時就失效的 Google 憑證。</p>



<h3 class="wp-block-heading">Workload Identity Federation 要錢嗎？</h3>



<p class="wp-block-paragraph">不用。WIF 屬於 IAM，Google 的 IAM 定價頁寫明 IAM API 全部免費（2026 年 12 月查）。要付錢的是你部署上去的服務，例如 Cloud Run、Artifact Registry 超過免費額度的部分。GitHub Actions 公開 repo 用標準 runner 也免費；私人 repo 的 GitHub Free 方案每月內含 12 美元額度，約 2,000 分鐘 Linux runner。</p>



<h3 class="wp-block-heading"><code>permissions: id-token: write</code> 是什麼？會不會讓 workflow 有寫入權限？</h3>



<p class="wp-block-paragraph">它只允許那個 job 向 GitHub 要一張 OIDC 權杖（身分證明），GitHub 官方文件寫明不會給任何其他寫入權限。沒有這行，<code>google-github-actions/auth</code> 就拿不到通行證。建議只寫在需要部署的 job，例如這篇只有 <code>deploy</code> job 有，<code>test</code> job 沒有，所以測試程式拿不到 Google 憑證。</p>



<h3 class="wp-block-heading">提供者沒設屬性條件會怎樣？</h3>



<p class="wp-block-paragraph">現在建不起來。實測不加 <code>--attribute-condition</code> 建 GitHub 提供者，gcloud 直接回 <code>INVALID_ARGUMENT: The attribute condition must reference one of the provider's claims</code>。原因是全世界的 GitHub repo 都用同一個發行者網址，沒有條件的話，任何人的 repo 都能拿通行證來換你的身分。條件建議用數字的 repo ID、帳號 ID，再加上分支限制。</p>



<h3 class="wp-block-heading">為什麼這篇要「扮演服務帳戶」，不用官方說比較好的直接授權？</h3>



<p class="wp-block-paragraph">Google 官方文件和 <code>google-github-actions/auth</code> 的 README 都推薦優先用直接授權（把角色直接給外部身分，不經過服務帳戶）。但官方的支援服務清單寫明 Cloud Run 不支援直接授權，要用扮演服務帳戶（2026 年 12 月查）。所以部署 Cloud Run 這種情境，要建一個專用的部署帳戶，再允許你的 repo 扮演它。</p>



<h3 class="wp-block-heading">GitHub 的 <code>sub</code> 為什麼跟舊文章寫的不一樣？</h3>



<p class="wp-block-paragraph">GitHub 官方文件說明，2026 年 7 月 15 日以後建立的 repo，OIDC 權杖的 <code>sub</code> 改成包含帳號 ID 和 repo ID 的固定格式，例如這篇實測的 <code>repo:aaronlee700618@50737700/do-14-github-actions-demo@1483676804:ref:refs/heads/main</code>，舊格式是 <code>repo:帳號/repo:ref:分支</code>。目的是防止 repo 刪除或改名後名稱被搶註。條件寫 <code>assertion.sub</code> 的要照新格式改；用 <code>repository_id</code> 當條件就不受影響。</p>



<h3 class="wp-block-heading">GitLab CI 也能用嗎？跟 GitHub 差在哪？</h3>



<p class="wp-block-paragraph">可以，這篇用自架 GitLab 19.6.2 實測成功。差別：job 要寫 <code>id_tokens:</code> 才會拿到通行證；<code>aud</code> 要跟提供者的 allowed audiences 一樣；發行者網址結尾要加斜線、audience 不加；條件要加 <code>ref_type=='branch'</code>，才不會被同名的標籤混過去；GitLab 通行證有效時間等於 job 逾時（實測 3600 秒）；沒有官方 auth action，用 <code>gcloud iam workload-identity-pools create-cred-config</code> 產生設定檔。舊的 <code>CI_JOB_JWT_V2</code> 在 GitLab 17.0 已經移除。</p>



<h3 class="wp-block-heading">刪掉的身分集區為什麼不能同名重建？</h3>



<p class="wp-block-paragraph">刪掉的集區會保留 30 天，這段期間可以用 <code>gcloud iam workload-identity-pools undelete</code> 救回，所以名字還被佔著。實測刪掉 <code>do-14-pool</code> 後立刻建同名的，得到 <code>ALREADY_EXISTS: Requested entity already exists</code>，列表顯示 2027-01-04 才永久刪除。要馬上重做的話，換一個名字就好。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">重點整理</h2>


<ul class="wp-block-list">
<li><strong>GitHub Actions 部署 Cloud Run 不用金鑰</strong>：用 Workload Identity Federation，GitHub 發 300 秒的通行證，Google STS 驗證後換成扮演部署帳戶的權杖（實測 3599 秒），repo 和 Secrets 裡 0 把金鑰</li>

<li><strong>屬性條件現在是必填</strong>：GitHub 提供者不加條件建不起來；條件用數字的 repo ID＋<code>main</code> 分支，換分支跑會被 <code>rejected by the attribute condition</code> 擋下</li>

<li><strong>最小權限</strong>：部署帳戶只給 Cloud Run 開發人員、執行身分的服務帳戶使用者、存放區寫入（或讀取）；網站用另一個沒有任何角色的執行帳戶</li>

<li><strong>稽核記錄查得到是誰</strong>：<code>serviceAccountDelegationInfo</code> 寫出是哪個 repo 或 GitLab 專案、哪個分支，失敗的嘗試也有記錄</li>

<li><strong>GitLab CI 同一套觀念</strong>：<code>id_tokens:</code>＋<code>gcloud ... create-cred-config</code>，通行證有效時間等於 job 逾時；證照新版考綱 2.3 新增「管理短效憑證」</li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">延伸閱讀</h2>



<p class="wp-block-paragraph"><strong>本系列</strong></p>


<ul class="wp-block-list">
<li>第 1 篇：<a href="https://dongdonggcp.com/2026/11/28/gcp-devops-certification-guide/">GCP DevOps 證照怎麼考？2026 新版考綱、比重與準備地圖</a></li>

<li>第 3 篇：<a href="https://dongdonggcp.com/2026/11/28/what-is-ci-cd-continuous-integration-delivery-deployment/">CI/CD 是什麼？持續整合、持續交付、持續部署差在哪</a></li>

<li>第 4 篇：Git、GitHub、GitLab 差在哪？版本控制白話懂（撰寫中）</li>

<li>第 7 篇：<a href="https://dongdonggcp.com/2026/11/28/what-is-devsecops-vs-secops-google-secops/">DevSecOps 是什麼？跟 SecOps、Google SecOps 差在哪</a></li>

<li>第 13 篇：<a href="https://dongdonggcp.com/2026/12/05/cloud-build-github-gitlab-trigger/">Cloud Build 串 GitHub／GitLab：push 就自動建置部署</a></li>

<li>第 15 篇：<a href="https://dongdonggcp.com/2024/12/03/gcp-devops-what-is-cloud-deploy-release/">Cloud Deploy 教學：dev→staging→prod 推版、核准、回滾</a></li>

<li>第 18 篇：軟體供應鏈安全：Artifact Analysis、Binary Authorization、SLSA（撰寫中）</li>
</ul>



<p class="wp-block-paragraph"><strong>這篇用到的服務</strong></p>


<ul class="wp-block-list">
<li><a href="https://dongdonggcp.com/2026/11/21/gke-workload-identity-federation-without-service-account-keys/">Workload Identity 是什麼？GKE 不用金鑰安全存取 GCP 服務</a></li>

<li><a href="https://dongdonggcp.com/2025/07/20/cloud-run-tutorials/">Cloud Run 是什麼？Cloud Run 教學：部署容器、版本與流量分割</a></li>

<li><a href="https://dongdonggcp.com/2025/07/20/artifact-registry-tutorials/">Artifact Registry 是什麼？把 Docker 映像檔推上 GCP 教學</a></li>

<li><a href="https://dongdonggcp.com/2026/11/21/cloud-build-tutorial-cloudbuild-yaml-cloud-run/">Cloud Build 是什麼？用 cloudbuild.yaml 自動建映像檔、部署到 Cloud Run</a></li>
</ul>



<p class="wp-block-paragraph"><strong>站上相關文章</strong></p>


<ul class="wp-block-list">
<li><a href="https://dongdonggcp.com/2024/12/10/what-is-gcp-cloud-iam-role-and-permission-introduction/">GCP 的 Cloud IAM：角色與權限控管介紹</a></li>

<li><a href="https://dongdonggcp.com/2025/04/14/tips-when-developing-with-gcp-service-account/">使用 GCP Service Account 開發程式的小技巧和注意事項</a></li>

<li><a href="https://dongdonggcp.com/2026/11/21/cloud-run-vs-gke-vs-compute-engine/">Cloud Run vs GKE vs Compute Engine 怎麼選？一張表比較</a></li>

<li><a href="https://dongdonggcp.com/2026/11/21/docker-kubernetes-learning-map/">Docker、Kubernetes 教學地圖：從容器到 Cloud Run、GKE 全系列整理</a></li>
</ul>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<p class="wp-block-paragraph">管線能安全地拿到權限之後，下一步是把同一個版本依序推到 dev、staging、prod，第 15 篇用 Cloud Deploy 來做。可以看看<a href="https://dongdonggcp.com/">東東的 GCP 課程</a>，或<a href="https://line.me/R/ti/p/@754xlakm">加 LINE 聊聊</a>你現在的狀況，一起找出最適合你的學習順序。</p>



<style>.wp-block-code{overflow-x:auto}.wp-block-code code{white-space:pre !important;overflow-wrap:normal !important;word-break:normal !important}</style>



<script type="application/ld+json">
{
  "@context": "https://schema.org",
  "@type": "FAQPage",
  "mainEntity": [
    {
      "@type": "Question",
      "name": "GitHub Actions 部署 GCP 一定要用 Workload Identity Federation 嗎？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "不一定，但它是 Google 官方推薦的做法。舊做法是把服務帳戶金鑰（JSON 檔）放進 GitHub Secrets，金鑰預設永不過期，外流了誰拿到都能用；而且 2024 年 5 月 3 日以後建立的 GCP 機構，預設就禁止建立金鑰。用 WIF，repo 和 Secrets 裡都沒有金鑰，GitHub 每次發一張 5 分鐘的通行證，換成 1 小時就失效的 Google 憑證。"
      }
    },
    {
      "@type": "Question",
      "name": "Workload Identity Federation 要錢嗎？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "不用。WIF 屬於 IAM，Google 的 IAM 定價頁寫明 IAM API 全部免費（2026 年 12 月查）。要付錢的是你部署上去的服務，例如 Cloud Run、Artifact Registry 超過免費額度的部分。GitHub Actions 公開 repo 用標準 runner 也免費；私人 repo 的 GitHub Free 方案每月內含 12 美元額度，約 2,000 分鐘 Linux runner。"
      }
    },
    {
      "@type": "Question",
      "name": "`permissions: id-token: write` 是什麼？會不會讓 workflow 有寫入權限？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "它只允許那個 job 向 GitHub 要一張 OIDC 權杖（身分證明），GitHub 官方文件寫明不會給任何其他寫入權限。沒有這行，`google-github-actions/auth` 就拿不到通行證。建議只寫在需要部署的 job，例如這篇只有 `deploy` job 有，`test` job 沒有，所以測試程式拿不到 Google 憑證。"
      }
    },
    {
      "@type": "Question",
      "name": "提供者沒設屬性條件會怎樣？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "現在建不起來。實測不加 `--attribute-condition` 建 GitHub 提供者，gcloud 直接回 `INVALID_ARGUMENT: The attribute condition must reference one of the provider's claims`。原因是全世界的 GitHub repo 都用同一個發行者網址，沒有條件的話，任何人的 repo 都能拿通行證來換你的身分。條件建議用數字的 repo ID、帳號 ID，再加上分支限制。"
      }
    },
    {
      "@type": "Question",
      "name": "為什麼這篇要「扮演服務帳戶」，不用官方說比較好的直接授權？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "Google 官方文件和 `google-github-actions/auth` 的 README 都推薦優先用直接授權（把角色直接給外部身分，不經過服務帳戶）。但官方的支援服務清單寫明 Cloud Run 不支援直接授權，要用扮演服務帳戶（2026 年 12 月查）。所以部署 Cloud Run 這種情境，要建一個專用的部署帳戶，再允許你的 repo 扮演它。"
      }
    },
    {
      "@type": "Question",
      "name": "GitHub 的 `sub` 為什麼跟舊文章寫的不一樣？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "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` 當條件就不受影響。"
      }
    },
    {
      "@type": "Question",
      "name": "GitLab CI 也能用嗎？跟 GitHub 差在哪？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "可以，這篇用自架 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 已經移除。"
      }
    },
    {
      "@type": "Question",
      "name": "刪掉的身分集區為什麼不能同名重建？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "刪掉的集區會保留 30 天，這段期間可以用 `gcloud iam workload-identity-pools undelete` 救回，所以名字還被佔著。實測刪掉 `do-14-pool` 後立刻建同名的，得到 `ALREADY_EXISTS: Requested entity already exists`，列表顯示 2027-01-04 才永久刪除。要馬上重做的話，換一個名字就好。"
      }
    }
  ]
}
</script><p>The post <a href="https://dongdonggcp.com/2026/12/05/github-actions-workload-identity-federation-cloud-run/">GitHub Actions 教學：不用金鑰部署 Cloud Run（Workload Identity Federation）</a> first appeared on <a href="https://dongdonggcp.com">東東 GCP 教學 - GCP 實戰講師</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://dongdonggcp.com/2026/12/05/github-actions-workload-identity-federation-cloud-run/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
