<?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>Terraform - 東東 GCP 教學 - GCP 實戰講師</title>
	<atom:link href="https://dongdonggcp.com/tag/terraform/feed/" rel="self" type="application/rss+xml" />
	<link>https://dongdonggcp.com</link>
	<description>助你考取證照，轉職成功</description>
	<lastBuildDate>Sat, 05 Dec 2026 01:31:45 +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>Terraform - 東東 GCP 教學 - GCP 實戰講師</title>
	<link>https://dongdonggcp.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Terraform 進階：state 放 Cloud Storage、modules、Infrastructure Manager</title>
		<link>https://dongdonggcp.com/2026/12/05/terraform-state-gcs-modules-infrastructure-manager/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=terraform-state-gcs-modules-infrastructure-manager</link>
					<comments>https://dongdonggcp.com/2026/12/05/terraform-state-gcs-modules-infrastructure-manager/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Sat, 05 Dec 2026 01:21:47 +0000</pubDate>
				<category><![CDATA[DevOps]]></category>
		<category><![CDATA[Cloud Storage]]></category>
		<category><![CDATA[GCP 證照]]></category>
		<category><![CDATA[Service Account]]></category>
		<category><![CDATA[Terraform]]></category>
		<guid isPermaLink="false">https://dongdonggcp.com/?p=14235</guid>

					<description><![CDATA[<p>Terraform state 放 Cloud Storage 實測：搬 state、兩人搶鎖、force-unlock、自寫與官方模組、Infra Manager 部署與計費，附證照考點。</p>
<p>The post <a href="https://dongdonggcp.com/2026/12/05/terraform-state-gcs-modules-infrastructure-manager/">Terraform 進階：state 放 Cloud Storage、modules、Infrastructure Manager</a> first appeared on <a href="https://dongdonggcp.com">東東 GCP 教學 - GCP 實戰講師</a>.</p>]]></description>
										<content:encoded><![CDATA[<p class="wp-block-paragraph"><strong>Terraform state 放 Cloud Storage 多人共用又加鎖，模組重用設定，Google 也能代跑。</strong></p>



<p class="wp-block-paragraph">Terraform 是把雲端資源寫成文字檔、交給它去建的工具；<strong>state（狀態檔）是 Terraform 記住「我建了哪些東西」的記帳本</strong>，預設是你下指令那個資料夾裡的 <code>terraform.tfstate</code>。第 10 篇：<a href="https://dongdonggcp.com/2026/12/05/terraform-tutorial-gcp-init-plan-apply-state/">Terraform 教學：用程式碼建 GCP 資源（init、plan、apply、state）</a>已經把基本功走過一次：provider、resource、變數、output，<code>init</code>、<code>plan</code>、<code>apply</code>、<code>destroy</code> 四個指令。不熟的話，先把 plan 當成「預覽會改什麼」、apply 當成「真的去改」就夠了。這篇接著處理一個人練完之後一定會遇到的三個問題：<strong>同事也要改同一套環境，記帳本放哪？同樣的設定一直複製貼上怎麼辦？能不能不要自己按 apply？</strong></p>



<p class="wp-block-paragraph">我在 2026 年 12 月 5 日凌晨，用 Cloud Shell 實際做了一次：</p>


<ol class="wp-block-list">
<li>用 gcloud 建一個開了版本控管的 bucket，再用 <code>terraform init -migrate-state</code> 把本機的 terraform state 搬上 Cloud Storage</li>

<li>開兩個終端機模擬兩個人：A 的 apply 停在等 yes，B 一跑 plan 就被 <strong>state lock（狀態鎖）</strong>擋下，畫面是 <code>Error 412</code>，意思是「有人正在用，請等一下」</li>

<li>把 A 的程式強制砍掉，留下一把沒人拿著、也不會自己消失的鎖，再用 <code>terraform force-unlock</code> 解開，發現<strong>要用錯誤訊息裡的數字 ID</strong>，鎖檔裡那串英數字 ID 會失敗</li>

<li>自己寫一個 bucket 模組叫兩次，再用 Google 維護的官方 Registry 模組建第三個</li>

<li>把一份設定交給 <strong>Infrastructure Manager</strong>（Google 代管的 Terraform 執行服務），從下指令到建好 3 分 46 秒，預設用的 Terraform 是 1.5.7</li>
</ol>



<p class="wp-block-paragraph">這篇寫給已經會 Terraform 基本指令、要開始跟同事一起用的人，也寫給準備 GCP DevOps 證照的人。指令都可以整段複製，最後全部刪乾淨。</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/do11-cards-01-remote-state-lock.png" alt="terraform state 放 Cloud Storage 的鎖定流程：A 先 apply 停在等 yes，bucket 裡多一個 default.tflock 鎖檔，B 同時 plan 得到 Error acquiring the state lock（Error 412）；A 打 no 鎖就消失；程式被砍掉時鎖會留著，要用錯誤訊息裡的數字 ID force-unlock；開了版本控管實測留下 serial 1、4、5 三個版本" class="wp-image-14201" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do11-cards-01-remote-state-lock.png 1200w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-cards-01-remote-state-lock-300x169.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-cards-01-remote-state-lock-1024x576.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-cards-01-remote-state-lock-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>：第 10 篇的 <code>terraform.tfstate</code> 放在 Cloud Shell 的練習資料夾。同事在自己電腦跑同一份設定，Terraform 看不到你的記帳本，會當成什麼都還沒建，plan 出來全是 <code>+</code> 新增</li>

<li><strong>兩個人同時改，會改到同一本帳</strong>：這篇實測 A 正在 apply 時，B 跑 plan 直接被擋下來。看懂這個錯誤訊息，才知道該等、還是該解鎖</li>

<li><strong>鎖卡住時不會解，整個團隊都動不了</strong>：apply 跑到一半被中斷，鎖不會自己消失。這篇實測第一次用錯 ID 解鎖失敗，第二次才成功</li>

<li><strong>同樣的設定複製貼上 10 次，規定一改就要改 10 個地方</strong>：模組（module）把「公司規定的 bucket 長什麼樣」寫一次，到處叫它</li>

<li><strong>上班第一週就會碰到</strong>：公司的 Terraform 幾乎都是多人共用、state 放遠端，新人報到先拿到的就是 backend 設定和模組資料夾。面試也常問「state 放哪」「鎖卡住怎麼辦」，文末整理了題目</li>

<li><strong>證照會考</strong>：Professional Cloud DevOps Engineer 2026 年 11 月 23 日起的新版考綱，1.2 點名 Infrastructure Manager，也新增了「Terraform modules and blueprints」</li>
</ul>



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



<h2 class="wp-block-heading">先懂 4 個名詞</h2>



<h3 class="wp-block-heading">backend 和遠端 state 是什麼</h3>



<p class="wp-block-paragraph"><strong>backend（後端）是 Terraform 存放 state 的地方。沒設定時用 local，state 是你資料夾裡的 <code>terraform.tfstate</code>；改成 <code>gcs</code>，state 就變成 Cloud Storage bucket 裡的一個檔案，大家讀寫同一份。放在遠端的 state 就叫遠端 state（remote state）。</strong></p>


<ul class="wp-block-list">
<li><strong>白話</strong>：記帳本從你的抽屜，搬到辦公室有鎖的公用櫃子</li>

<li><strong>生活比喻</strong>：第 10 篇把 state 比喻成工頭的進貨單。一個工地有三個工頭，進貨單如果各自放口袋，誰也不知道別人買過什麼；放在工地辦公室的櫃子，每個人進貨前先翻同一本</li>

<li><strong>來龍去脈</strong>：團隊要共用 state，最直覺是放進 Git（版本控制工具），但 state 是明文，第 10 篇實測裡面就存著建立者的 email，而且兩個人各改一份會互相蓋掉。所以 Terraform 提供 backend 設定，把 state 存到有權限控管的地方，Cloud Storage 的 <code>gcs</code>、AWS 的 S3 都是其中一種</li>

<li><strong>為什麼要學</strong>：團隊一起用 Terraform 的第一步就是設好 backend。證照題目看到「state 檔衝突、遺失、多人協作」，答案都從這裡開始</li>
</ul>



<p class="wp-block-paragraph">HashiCorp 的 <a href="https://developer.hashicorp.com/terraform/language/backend/gcs">gcs backend 說明</a>寫了三個重點（2026 年 12 月查官方文件）：bucket 要<strong>事先建好</strong>、這個 backend <strong>支援鎖定</strong>、強烈建議 bucket <strong>開版本控管</strong>，誤刪或寫壞時才救得回來。</p>



<h3 class="wp-block-heading">state lock（狀態鎖）是什麼</h3>



<p class="wp-block-paragraph"><strong>state lock 是 Terraform 要動 state 之前，先在旁邊放一塊「使用中」的牌子；別人看到牌子就不能動，等你做完拿走牌子，才輪到下一個人。</strong></p>


<ul class="wp-block-list">
<li><strong>白話</strong>：廁所門上的「使用中」</li>

<li><strong>生活比喻</strong>：同一本帳簿，兩個會計同時寫，數字一定亂掉。規定只有拿到那支筆的人可以寫，寫完把筆放回去</li>

<li><strong>來龍去脈</strong>：gcs backend 的做法是在 state 旁邊寫一個 <code>default.tflock</code> 檔。這篇的錯誤訊息看得出來：Terraform 寫鎖檔時附了「這個檔案不存在才寫」的條件，鎖檔已經存在，條件不成立，Cloud Storage 就回 <code>412</code>（HTTP 狀態碼，意思是「你給的前提條件不成立」）</li>

<li><strong>為什麼要學</strong>：apply、destroy 這類會寫 state 的指令都會先拿鎖，實測連 plan 也被擋。鎖被擋下來是保護你，不是壞掉；真正要處理的是「拿著鎖的人已經不在了」那一種</li>
</ul>



<h3 class="wp-block-heading">module（模組）是什麼</h3>



<p class="wp-block-paragraph"><strong>module（模組）是一包可以重複使用的 Terraform 設定：把幾個資源和公司的規定寫在一個資料夾，其他地方用 <code>module</code> 區塊叫它，只要傳幾個參數。</strong></p>


<ul class="wp-block-list">
<li><strong>白話</strong>：公司的標準表單範本，大家照填，不用每次重畫表格</li>

<li><strong>生活比喻</strong>：系統家具的標準櫃。尺寸、板材、防撞角都先定好，每個房間只要說「放 2 個、白色」。哪天規定改成全部加門擋，改型錄一次，之後訂的櫃子全都有</li>

<li><strong>來龍去脈</strong>：其實第 10 篇寫的那個資料夾就已經是模組，叫<strong>根模組</strong>（root module，你下指令的那個資料夾）；被它叫的叫<strong>子模組</strong>（child module）。子模組可以放在本機另一個資料夾，也可以從 <a href="https://registry.terraform.io/">Terraform Registry</a>（provider 和模組的下載站）下載。Google 自己維護的模組放在 Registry 的 <code>terraform-google-modules</code> 底下，<a href="https://docs.cloud.google.com/docs/terraform/blueprints/terraform-blueprints">官方叫它 Terraform blueprints and modules</a></li>

<li><strong>為什麼要學</strong>：bucket、網路、權限這些東西公司都有規定，寫成模組才能保證每個人建出來都一樣。新版考綱 1.2 把「Terraform modules and blueprints」寫進去了</li>
</ul>



<h3 class="wp-block-heading">Infrastructure Manager 是什麼</h3>



<p class="wp-block-paragraph"><strong>Infrastructure Manager（常簡稱 Infra Manager）是 Google Cloud 代管的 Terraform 執行服務：你把 Terraform 設定交給它，它在 Cloud Build 裡幫你跑 <code>init</code>、<code>plan</code>、<code>apply</code>，state 和每一次的執行紀錄都由它保管。</strong></p>


<ul class="wp-block-list">
<li><strong>白話</strong>：不用自己按 apply，交給 Google 按，每次按完還留一份紀錄</li>

<li><strong>生活比喻</strong>：自己記帳 vs 交給會計事務所。你把單據交出去，事務所照規矩入帳，每個月留一份底稿，帳本也是他們保管</li>

<li><strong>來龍去脈</strong>：它的 API 叫 <code>config.googleapis.com</code>。每一套環境叫一個<strong>部署</strong>（deployment），每改一次多一個<strong>修訂版本</strong>（revision，實測叫 <code>r-0</code>、<code>r-1</code>…）。底下真正執行 Terraform 的是 Cloud Build（Google 的建置服務，會開一台臨時機器照步驟跑指令，詳見<a href="https://dongdonggcp.com/2026/11/21/cloud-build-tutorial-cloudbuild-yaml-cloud-run/">容器系列的 Cloud Build 教學</a>）</li>

<li><strong>為什麼要學</strong>：新版考綱 1.2 直接點名。不想自己顧 state bucket、執行環境和 Terraform 版本的團隊，會走這條路；但它能用的 Terraform 版本有限，這篇實測預設是 1.5.7</li>
</ul>



<p class="wp-block-paragraph">下面幾個名詞先看過去，動手做時會一個一個遇到：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>名詞</th><th>白話</th><th>這篇的例子</th></tr></thead><tbody><tr><td>prefix</td><td>state 在 bucket 裡的資料夾名稱</td><td><code>app</code>，state 會是 <code>app/default.tfstate</code></td></tr><tr><td><code>default.tflock</code></td><td>鎖檔，有人在改 state 時才存在</td><td>實測 A 等 yes 的時候一直在</td></tr><tr><td>版本控管（Object Versioning）</td><td>Cloud Storage 把被蓋掉、被刪掉的檔案留成舊版本</td><td>state 留了 3 個版本</td></tr><tr><td>generation</td><td>Cloud Storage 每個檔案版本的編號</td><td><code>default.tfstate#1796406067242927</code></td></tr><tr><td>serial</td><td>state 自己的流水號，每寫一次加 1</td><td>1、4、5</td></tr><tr><td>軟刪除（soft delete）</td><td>刪掉的檔案先放回收區幾天，可以救回來</td><td>新 bucket 預設 7 天</td></tr><tr><td>服務帳戶（service account）</td><td>給程式用的帳號，不是給人登入的</td><td><code>do-11-im</code>，給 Infra Manager 用</td></tr></tbody></table></figure>



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



<h2 class="wp-block-heading">自己跑 Terraform、Infrastructure Manager、Config Connector 怎麼選</h2>



<p class="wp-block-paragraph">這三種都能「用程式碼管 GCP 資源」，差在誰來執行、state 放哪、要準備什麼環境。表格裡的 CI（持續整合，Continuous Integration）是程式一推上 Git 就自動跑檢查、部署的流程；Kubernetes 是管理大量容器的平台，GKE 是 Google 代管的 Kubernetes；YAML 是用縮排寫設定的文字格式。</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/do11-cards-03-cli-vs-infra-manager.png" alt="自己跑 Terraform 和 Infrastructure Manager 比較：誰按 apply 分別是你的終端機和 Cloud Build 加服務帳戶；state 分別放自己建的 gcs bucket 和 Google 代管；版本分別是自己裝的 1.17.3 和預設 1.5.7；實測建一個資源分別是 2 秒和 3 分 46 秒" class="wp-image-14202" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do11-cards-03-cli-vs-infra-manager.png 1200w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-cards-03-cli-vs-infra-manager-300x169.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-cards-03-cli-vs-infra-manager-1024x576.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-cards-03-cli-vs-infra-manager-768x432.png 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th></th><th>自己跑 terraform</th><th>Infrastructure Manager</th><th>Config Connector</th></tr></thead><tbody><tr><td>寫法</td><td>Terraform（<code>.tf</code>）</td><td>Terraform（<code>.tf</code>）</td><td>Kubernetes 的 YAML</td></tr><tr><td>誰執行</td><td>你的終端機或 CI，用你的帳號或 CI 的身分</td><td>Cloud Build，用你指定的服務帳戶</td><td>Kubernetes 叢集裡的控制器（一直在跑的小程式）</td></tr><tr><td>state</td><td>自己設 backend，例如這篇的 <code>gcs</code></td><td>Google 代管，設定裡<strong>不能寫</strong> backend</td><td>沒有 Terraform state，Kubernetes 裡的 YAML 就是「應該長怎樣」</td></tr><tr><td>版本</td><td>自己裝什麼就用什麼（實測 1.17.3）</td><td>只能選它支援的（實測預設 1.5.7）</td><td>跟著 Config Connector 版本</td></tr><tr><td>要先準備</td><td>state bucket、執行環境</td><td>開 API、服務帳戶和權限</td><td>一個 Kubernetes 叢集（例如 GKE）</td></tr><tr><td>適合</td><td>已經有 CI/CD、要用最新版 Terraform</td><td>不想自己顧執行環境，要每次執行都有紀錄</td><td>團隊已經用 Kubernetes、想用同一套方式管雲端資源</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">Config Connector 是 <a href="https://docs.cloud.google.com/config-connector/docs/overview">Google 官方說的</a>「Kubernetes 外掛（add-on）」，用 Kubernetes 的方式管 GCP 資源，這篇沒有實測，觀念可以看站上的〈<a href="https://dongdonggcp.com/2024/12/02/gke-what-is-config-connector-and-how-to-use/">Config Connector 是什麼東東？如何使用？</a>〉。</p>



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



<h2 class="wp-block-heading">動手做：state 搬上 Cloud Storage、兩個人搶鎖、模組、Infra Manager</h2>



<p class="wp-block-paragraph">做完之後，你的專案裡會有：一個放 state 的 bucket、三個用模組建的 bucket、一個由 Infrastructure Manager 建的 Artifact Registry 存放區（放容器映像檔的地方），最後全部刪掉。</p>


<ul class="wp-block-list">
<li><strong>在哪裡做</strong>：Cloud Shell（Google 提供、開瀏覽器就能打指令的 Linux 終端機），專案 dong-dong-gcp-3，區域 <code>asia-east1</code>（台灣彰化）。怎麼開 Cloud Shell 在<a href="https://dongdonggcp.com/2026/11/28/gcp-devops-certification-guide/">第 1 篇</a></li>

<li><strong>要先裝好 Terraform</strong>：Cloud Shell 從 2026 年 6 月 20 日起不內建 Terraform（<a href="https://docs.cloud.google.com/shell/docs/release-notes">Cloud Shell 版本資訊</a>），你的 Cloud Shell 如果還沒裝過，照步驟 1 的三行指令裝。Cloud Shell 只保留家目錄（<a href="https://docs.cloud.google.com/shell/docs/configuring-cloud-shell">官方說明</a>），用 apt 裝的 Terraform 在機器被回收、重新開一台之後就不在了，看到安裝說明就重裝一次。我的機器上第 10 篇裝的 1.17.3 剛好還在，這次直接用</li>

<li><strong>花多久</strong>：我實測從建 bucket 到刪乾淨約 23 分鐘，其中 Infrastructure Manager 建立 3 分 46 秒、刪除 41 秒；第一次邊讀邊做，預留 1 小時</li>

<li><strong>權限</strong>：最簡單是專案擁有者（Owner），自己建的練習專案，建立者預設就是 Owner；不確定的話，到 Console 的「IAM 與管理」頁面找自己的帳號看角色。不是 Owner 的話，要能建 bucket（<code>roles/storage.admin</code>）、建服務帳戶並給它權限（<code>roles/iam.serviceAccountAdmin</code>、<code>roles/resourcemanager.projectIamAdmin</code>）、用 Infrastructure Manager（<code>roles/config.admin</code>），而且要能「以那個服務帳戶的身分執行」（<code>roles/iam.serviceAccountUser</code>）（2026 年 12 月查<a href="https://docs.cloud.google.com/infrastructure-manager/docs/configure-service-account">官方文件</a>）</li>

<li><strong>API</strong>：Infrastructure Manager 要開 <code>config.googleapis.com</code>，底下會用到 Cloud Build。我的專案之前已經開好，這次沒有重跑；你的專案沒開的話，<a href="https://docs.cloud.google.com/infrastructure-manager/docs/enable-service">官方的指令</a>是 <code>gcloud services enable config.googleapis.com</code>，開法跟第 10 篇步驟 3 一樣。開 API 本身也要權限（例如 <code>roles/serviceusage.serviceUsageAdmin</code>），不是 Owner 的話請管理員先幫忙開</li>

<li><strong>會不會花錢</strong>：幾乎不會。空的 bucket 不收儲存費，state 檔只有幾 KB；Infrastructure Manager 用 1.5.7 不收管理費，只照 Cloud Build 執行時間和 Cloud Storage 用量收（實測 Cloud Build 跑 35 秒）；Artifact Registry 存放區是空的。另外 Infrastructure Manager 部署時會自動多出兩個 bucket，刪部署不會跟著刪，處理方式在「用完記得刪」最後一節</li>

<li><strong>中途斷線</strong>：重新連上後先 <code>cd ~/do-11</code>，再重跑步驟 1 的 <code>export</code> 那一行</li>
</ul>



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



<h3 class="wp-block-heading">步驟 1：建練習資料夾、確認 Terraform 版本</h3>



<p class="wp-block-paragraph">先建資料夾。第二行的 <code>TF_PLUGIN_CACHE_DIR</code> 是讓 Terraform 把下載的 provider（Terraform 跟 GCP 溝通的外掛）放在一個共用位置：第 10 篇實測 google provider 一個就 135 MB，這篇會有兩個資料夾各自 init，共用之後只下載一次。Cloud Shell 的家目錄只有 5 GB，省一點比較安全。<code>$HOME</code> 是你的家目錄。這行設定關掉 Cloud Shell 就會消失，沒重跑也不會壞，只是會多下載一次 provider：</p>



<pre class="wp-block-code"><code>mkdir -p ~/do-11/.plugin-cache &amp;&amp; cd ~/do-11
export TF_PLUGIN_CACHE_DIR=$HOME/do-11/.plugin-cache
terraform version</code></pre>



<pre class="wp-block-code"><code>Terraform v1.17.3
on linux_amd64</code></pre>



<figure class="wp-block-image aligncenter size-full"><img decoding="async" width="810" height="245" src="https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-01-terraform-version.png" alt="在 Cloud Shell 的 ~/do-11 資料夾跑 terraform version，顯示 Terraform v1.17.3 on linux_amd64" class="wp-image-14203" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-01-terraform-version.png 810w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-01-terraform-version-300x91.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-01-terraform-version-768x232.png 768w" sizes="(max-width: 810px) 100vw, 810px" /></figure>



<p class="wp-block-paragraph">如果看到的是一段安裝說明，代表這台 Cloud Shell 還沒裝 Terraform。照 Cloud Shell 印出來的說明，跑下面三行（第 10 篇步驟 2 實測過，第 1 行下載 HashiCorp 的簽章金鑰、第 2 行加入它的軟體來源、第 3 行安裝，<code>sudo</code> 是用管理員權限執行，Cloud Shell 不用輸入密碼），最後出現 <code>Setting up terraform</code> 就裝好了，再跑一次 <code>terraform version</code>：</p>



<pre class="wp-block-code"><code>wget -O - https://apt.releases.hashicorp.com/gpg | sudo gpg --dearmor -o /usr/share/keyrings/hashicorp-archive-keyring.gpg
echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/hashicorp-archive-keyring.gpg] https://apt.releases.hashicorp.com $(grep -oP '(?&lt;=UBUNTU_CODENAME=).*' /etc/os-release || lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/hashicorp.list
sudo apt update &amp;&amp; sudo apt install -y terraform</code></pre>



<h3 class="wp-block-heading">步驟 2：先用 gcloud 建放 state 的 bucket，開版本控管</h3>



<p class="wp-block-paragraph">state bucket 要<strong>在 Terraform 之外</strong>先建好，理由有兩個：HashiCorp 文件寫明 backend 用的 bucket 必須事先存在；而且這個 bucket 如果由同一份 Terraform 管，哪天有人跑 <code>terraform destroy</code>，記帳本會跟著被刪。有些網路教學用 Terraform 建 state bucket 還加上 <code>force_destroy = true</code>（destroy 時連裡面的檔案一起刪），Google 官方範例則是設 <code>false</code>，這篇乾脆用 gcloud 建。</p>



<p class="wp-block-paragraph">bucket 名稱全世界不能重複，所以把專案 ID 放進去：</p>



<pre class="wp-block-code"><code>gcloud storage buckets create gs://do-11-dong-dong-gcp-3-tfstate --location=asia-east1 --uniform-bucket-level-access --public-access-prevention
gcloud storage buckets update gs://do-11-dong-dong-gcp-3-tfstate --versioning
gcloud storage buckets describe gs://do-11-dong-dong-gcp-3-tfstate --format='yaml(name,location,versioning_enabled,soft_delete_policy)'</code></pre>


<ul class="wp-block-list">
<li><code>--uniform-bucket-level-access</code>：權限統一用 IAM（GCP 的權限系統）在 bucket 層級管，不能對單一檔案另外開權限</li>

<li><code>--public-access-prevention</code>：禁止把這個 bucket 公開到網路上。state 是明文，絕對不能公開</li>

<li><code>--versioning</code>：開版本控管，state 被蓋掉時舊的那份會留下來</li>
</ul>



<pre class="wp-block-code"><code>Creating gs://do-11-dong-dong-gcp-3-tfstate/...
Updating gs://do-11-dong-dong-gcp-3-tfstate/...
location: ASIA-EAST1
name: do-11-dong-dong-gcp-3-tfstate
soft_delete_policy:
  effectiveTime: '2026-12-04T17:39:35.711000+00:00'
  retentionDurationSeconds: '604800'
versioning_enabled: true</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/do11-shots-02-state-bucket.png" alt="用 gcloud storage buckets create 建 terraform state 專用的 bucket do-11-dong-dong-gcp-3-tfstate，開啟版本控管，describe 顯示 versioning_enabled: true、軟刪除保留 604800 秒" class="wp-image-14204" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-02-state-bucket.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-02-state-bucket-300x56.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-02-state-bucket-1024x190.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-02-state-bucket-768x143.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-02-state-bucket-1536x285.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph">我沒設軟刪除，輸出卻多了一段 <code>soft_delete_policy</code>：這是 Cloud Storage 新 bucket 的<a href="https://docs.cloud.google.com/storage/docs/soft-delete">預設行為</a>，刪掉的檔案會先留一段時間。<strong>算一次</strong>：<code>604800</code> 秒 ÷ 86,400 秒（一天）＝ <strong>7 天</strong>。這 7 天內被刪的檔案還救得回來，但也照儲存量收費。</p>



<h3 class="wp-block-heading">步驟 3：寫一個 bucket 模組，再寫要用它的根模組</h3>



<p class="wp-block-paragraph">這篇的資料夾長這樣：<code>modules/bucket/</code> 是子模組，寫「公司規定的 bucket 長什麼樣」；<code>app/</code> 是根模組，負責叫它。</p>



<p class="wp-block-paragraph">先寫子模組的 3 個檔。<code>main.tf</code> 把規定寫死：統一權限、禁止公開、一定要貼 <code>env</code> 和 <code>managed-by</code> 標籤。注意它<strong>只宣告需要 google provider，沒有寫 <code>provider</code> 區塊</strong>，provider 由叫它的根模組決定，<a href="https://developer.hashicorp.com/terraform/language/modules/develop/providers">HashiCorp 也是這樣建議的</a>：</p>



<pre class="wp-block-code"><code>cd ~/do-11
mkdir -p modules/bucket app
cat &gt; modules/bucket/main.tf &lt;&lt;'EOF'
terraform {
  required_providers {
    google = {
      source = "hashicorp/google"
    }
  }
}

# 公司標準的 bucket：統一權限、禁止公開、貼標籤
resource "google_storage_bucket" "this" {
  name                        = "do-11-${var.project_id}-${var.name}"
  location                    = var.location
  uniform_bucket_level_access = true
  public_access_prevention    = "enforced"

  versioning {
    enabled = var.versioning
  }

  labels = {
    env        = var.env
    managed-by = "terraform"
  }
}
EOF</code></pre>



<p class="wp-block-paragraph"><code>variables.tf</code> 是模組開放給外面填的欄位。有 <code>default</code> 的可以不填，<code>project_id</code> 和 <code>name</code> 沒有預設值，叫它的人一定要給：</p>



<pre class="wp-block-code"><code>cat &gt; modules/bucket/variables.tf &lt;&lt;'EOF'
variable "project_id" {
  type = string
}

variable "name" {
  description = "bucket 名稱的最後一段"
  type        = string
}

variable "location" {
  type    = string
  default = "asia-east1"
}

variable "env" {
  type    = string
  default = "dev"
}

variable "versioning" {
  type    = bool
  default = false
}
EOF</code></pre>



<p class="wp-block-paragraph"><code>outputs.tf</code> 是模組建好之後要交回去的值，根模組用 <code>module.名稱.輸出名稱</code> 拿：</p>



<pre class="wp-block-code"><code>cat &gt; modules/bucket/outputs.tf &lt;&lt;'EOF'
output "name" {
  value = google_storage_bucket.this.name
}

output "url" {
  value = google_storage_bucket.this.url
}
EOF</code></pre>



<p class="wp-block-paragraph">再寫根模組。<code>module "logs"</code> 和 <code>module "assets"</code> 叫的是同一個子模組（<code>source = "../modules/bucket"</code>，意思是「上一層的 modules/bucket 資料夾」），只差在名稱和要不要開版本控管：</p>



<pre class="wp-block-code"><code>cd ~/do-11/app
cat &gt; main.tf &lt;&lt;'EOF'
terraform {
  required_providers {
    google = {
      source  = "hashicorp/google"
      version = "~&gt; 8.0"
    }
  }
}

provider "google" {
  project = var.project_id
  region  = "asia-east1"
}

variable "project_id" {
  type = string
}

variable "env" {
  type    = string
  default = "dev"
}

# 同一個模組叫兩次，建出兩個 bucket
module "logs" {
  source     = "../modules/bucket"
  project_id = var.project_id
  name       = "logs"
  env        = var.env
}

module "assets" {
  source     = "../modules/bucket"
  project_id = var.project_id
  name       = "assets"
  env        = var.env
  versioning = true
}

output "buckets" {
  value = [module.logs.name, module.assets.name]
}
EOF
cat &gt; terraform.tfvars &lt;&lt;'EOF'
project_id = "dong-dong-gcp-3"
EOF
cd ~/do-11; find . -name '*.tf*' -not -path '*/.*' | sort; cd app</code></pre>



<pre class="wp-block-code"><code>./app/main.tf
./app/terraform.tfvars
./modules/bucket/main.tf
./modules/bucket/outputs.tf
./modules/bucket/variables.tf</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="605" height="279" src="https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-03-files.png" alt="find 列出 terraform 模組練習的 5 個檔案：app 資料夾的 main.tf、terraform.tfvars，以及 modules/bucket 資料夾的 main.tf、outputs.tf、variables.tf" class="wp-image-14205" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-03-files.png 605w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-03-files-300x138.png 300w" sizes="(max-width: 605px) 100vw, 605px" /></figure>



<h3 class="wp-block-heading">步驟 4：terraform init，多了一段 Initializing modules</h3>



<pre class="wp-block-code"><code>terraform init</code></pre>



<pre class="wp-block-code"><code>Initializing the backend...

Initializing modules...
- logs in ../modules/bucket
- assets in ../modules/bucket

Initializing provider plugins...
- Finding hashicorp/google versions matching "~&gt; 8.0"...
- Installing hashicorp/google v8.12.0...
- Installed hashicorp/google v8.12.0 (signed by HashiCorp)
（中間省略）
Terraform has been successfully initialized!</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1409" height="993" src="https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-04-init-modules.png" alt="terraform init 輸出 Initializing modules，logs 和 assets 兩個模組都指向 ../modules/bucket，並安裝 hashicorp/google v8.12.0" class="wp-image-14206" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-04-init-modules.png 1409w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-04-init-modules-300x211.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-04-init-modules-1024x722.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-04-init-modules-768x541.png 768w" sizes="(max-width: 1409px) 100vw, 1409px" /></figure>



<p class="wp-block-paragraph">跟第 10 篇比，多了 <code>Initializing modules</code>：Terraform 先找到 <code>logs</code>、<code>assets</code> 兩個模組的位置。<strong>以後加了新模組、或改了 <code>source</code>，都要重跑一次 <code>terraform init</code></strong>，輸出最後一段也這樣提醒。</p>



<h3 class="wp-block-heading">步驟 5：plan，看資源的新名字</h3>



<p class="wp-block-paragraph"><code>grep</code> 是只挑出含特定文字的行，這裡只看每個資源的標題和最後一行：</p>



<pre class="wp-block-code"><code>terraform plan | grep -E '# |Plan:'</code></pre>



<pre class="wp-block-code"><code>  # module.assets.google_storage_bucket.this will be created
  # module.logs.google_storage_bucket.this will be created
Plan: 2 to add, 0 to change, 0 to destroy.</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1181" height="245" src="https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-05-plan-modules.png" alt="terraform plan 顯示 module.assets.google_storage_bucket.this 和 module.logs.google_storage_bucket.this 兩個資源將被建立，Plan: 2 to add" class="wp-image-14207" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-05-plan-modules.png 1181w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-05-plan-modules-300x62.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-05-plan-modules-1024x212.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-05-plan-modules-768x159.png 768w" sizes="(max-width: 1181px) 100vw, 1181px" /></figure>



<p class="wp-block-paragraph">資源的名字變成 <code>module.logs.google_storage_bucket.this</code>：前面多了「從哪個模組來的」。模組裡只寫了一個 <code>this</code>，叫兩次就是兩個資源，各自有自己的地址。</p>



<h3 class="wp-block-heading">步驟 6：apply，state 還在本機</h3>



<p class="wp-block-paragraph"><code>-auto-approve</code> 是不問 yes 直接做，步驟 5 已經看過 plan 才這樣用；<code>tail -12</code> 只看最後 12 行：</p>



<pre class="wp-block-code"><code>terraform apply -auto-approve | tail -12; ls; terraform state list</code></pre>



<pre class="wp-block-code"><code>module.assets.google_storage_bucket.this: Creating...
module.logs.google_storage_bucket.this: Creation complete after 2s [id=do-11-dong-dong-gcp-3-logs]
module.assets.google_storage_bucket.this: Creation complete after 3s [id=do-11-dong-dong-gcp-3-assets]

Apply complete! Resources: 2 added, 0 changed, 0 destroyed.

Outputs:

buckets = [
  "do-11-dong-dong-gcp-3-logs",
  "do-11-dong-dong-gcp-3-assets",
]
main.tf  terraform.tfstate  terraform.tfvars
module.assets.google_storage_bucket.this
module.logs.google_storage_bucket.this</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="581" src="https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-06-apply-local.png" alt="terraform apply 用同一個模組建出 do-11-dong-dong-gcp-3-logs 和 do-11-dong-dong-gcp-3-assets 兩個 bucket，資料夾裡出現本機的 terraform.tfstate" class="wp-image-14208" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-06-apply-local.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-06-apply-local-300x109.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-06-apply-local-1024x372.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-06-apply-local-768x279.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-06-apply-local-1536x558.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph">兩個 bucket 2～3 秒建好。注意 <code>ls</code> 那一行：<code>terraform.tfstate</code> 還在本機資料夾，這就是下一步要搬走的記帳本。</p>



<h3 class="wp-block-heading">步驟 7：加上 backend，把 state 搬上 Cloud Storage</h3>



<p class="wp-block-paragraph">新增一個 <code>backend.tf</code>，寫上 bucket 和 prefix。backend 區塊<strong>不能用變數</strong>，HashiCorp <a href="https://developer.hashicorp.com/terraform/language/backend">文件</a>寫明它不能引用 variable、local 這類值，所以 bucket 名稱要直接寫死。</p>



<pre class="wp-block-code"><code>cat &gt; backend.tf &lt;&lt;'EOF'
terraform {
  backend "gcs" {
    bucket = "do-11-dong-dong-gcp-3-tfstate"
    prefix = "app"
  }
}
EOF
terraform init -migrate-state</code></pre>



<p class="wp-block-paragraph"><code>-migrate-state</code> 是「換 backend 時，把舊的 state 搬過去」。Terraform 會停下來問你：</p>



<pre class="wp-block-code"><code>Initializing the backend...
Do you want to copy existing state to the new backend?
  Pre-existing state was found while migrating the previous "local" backend to the
  newly configured "gcs" backend. No existing state was found in the newly
  configured "gcs" backend. Do you want to copy this state to the new "gcs"
  backend? Enter "yes" to copy and "no" to start with an empty state.

  Enter a value:</code></pre>



<p class="wp-block-paragraph">意思是：本機有一份 state，新的 gcs 那邊還沒有，要不要複製過去？打 <code>no</code> 會從空的記帳本開始，Terraform 就忘了那兩個 bucket。這裡打 <code>yes</code>：</p>



<pre class="wp-block-code"><code>  Enter a value: yes


Successfully configured the backend "gcs"! Terraform will automatically
use this backend unless the backend configuration changes.

Initializing modules...

Initializing provider plugins...
- Reusing version 8.12.0 of hashicorp/google from the dependency lock file
- Using previously-installed hashicorp/google v8.12.0

Terraform has been successfully initialized!</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1460" height="1265" src="https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-08-migrate-done.png" alt="terraform init -migrate-state 詢問是否把本機 local backend 的 state 複製到新的 gcs backend，輸入 yes 後顯示 Successfully configured the backend &quot;gcs&quot;" class="wp-image-14209" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-08-migrate-done.png 1460w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-08-migrate-done-300x260.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-08-migrate-done-1024x887.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-08-migrate-done-768x665.png 768w" sizes="(max-width: 1460px) 100vw, 1460px" /></figure>



<h3 class="wp-block-heading">步驟 8：本機剩什麼？雲端多了什麼？</h3>



<p class="wp-block-paragraph"><code>wc -c</code> 是算檔案有幾個位元組（bytes）：</p>



<pre class="wp-block-code"><code>ls; wc -c terraform.tfstate*; gcloud storage ls gs://do-11-dong-dong-gcp-3-tfstate/app/; terraform state list</code></pre>



<pre class="wp-block-code"><code>backend.tf  main.tf  terraform.tfstate  terraform.tfstate.backup  terraform.tfvars
   0 terraform.tfstate
5935 terraform.tfstate.backup
5935 total
gs://do-11-dong-dong-gcp-3-tfstate/app/default.tfstate
module.assets.google_storage_bucket.this
module.logs.google_storage_bucket.this</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="248" src="https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-09-state-in-gcs.png" alt="搬完 state 後本機 terraform.tfstate 變成 0 bytes、terraform.tfstate.backup 還有 5935 bytes，Cloud Storage 裡出現 app/default.tfstate，terraform state list 仍列出兩個資源" class="wp-image-14210" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-09-state-in-gcs.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-09-state-in-gcs-300x47.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-09-state-in-gcs-1024x159.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-09-state-in-gcs-768x119.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-09-state-in-gcs-1536x238.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph">三件事：</p>


<ol class="wp-block-list">
<li><strong>state 搬上去了</strong>：bucket 裡多了 <code>app/default.tfstate</code>。<code>app</code> 是 prefix，<code>default</code> 是預設的工作區（workspace，同一份設定可以有多本 state，這篇不用）</li>

<li><strong>本機的 <code>terraform.tfstate</code> 變成 0 bytes</strong>，Terraform 現在去 Cloud Storage 讀寫</li>

<li><strong>本機還留著 5,935 bytes 的 <code>terraform.tfstate.backup</code></strong>，裡面是搬家前的完整 state。第 10 篇實測 state 會明文存敏感資料，所以這個備份檔不要放進 Git，確認搬好之後自己刪掉</li>
</ol>



<p class="wp-block-paragraph">權限也要跟著想：從現在開始，<strong>能讀這個 bucket 的人就能讀到 state 全文</strong>。HashiCorp 文件寫的是，存取 state 的身分要有 bucket 的 Storage 物件管理員（<code>roles/storage.objectAdmin</code>），只給需要跑 Terraform 的人。</p>



<h3 class="wp-block-heading">步驟 9：模擬同事 B，開另一個資料夾接同一份 state</h3>



<p class="wp-block-paragraph">真實情況裡 B 在自己的電腦，從 Git 拉下同一份設定。這裡用同一台 Cloud Shell 的另一個資料夾 <code>app-b</code> 模擬。步驟 9 到 15 會有兩個人，先記住誰在哪：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>角色</th><th>在哪個分頁打指令</th><th>資料夾</th></tr></thead><tbody><tr><td>A（你）</td><td>分頁 1，就是你現在用的這個</td><td><code>~/do-11/app</code></td></tr><tr><td>B（同事）</td><td>分頁 2，步驟 11 才開</td><td><code>~/do-11/app-b</code></td></tr></tbody></table></figure>



<p class="wp-block-paragraph"><strong>在 A 的分頁</strong>，複製設定檔到 <code>app-b</code>（<strong>不複製 state</strong>），在那裡 init，再回到 <code>app</code>：</p>



<pre class="wp-block-code"><code>mkdir -p ../app-b &amp;&amp; cp main.tf backend.tf terraform.tfvars ../app-b/ &amp;&amp; cd ../app-b &amp;&amp; terraform init | grep -E 'backend|initialized' ; cd ../app</code></pre>



<pre class="wp-block-code"><code>Initializing the backend...
Successfully configured the backend "gcs"! Terraform will automatically
use this backend unless the backend configuration changes.
Terraform has been successfully initialized!
If you ever set or change modules or backend configuration for Terraform,</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/do11-shots-10-teammate-init.png" alt="同事 B 的資料夾 app-b 只複製 main.tf、backend.tf、terraform.tfvars，terraform init 後一樣接上 gcs backend" class="wp-image-14211" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-10-teammate-init.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-10-teammate-init-300x35.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-10-teammate-init-1024x120.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-10-teammate-init-768x90.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-10-teammate-init-1536x180.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph">B 沒有 state 檔，但接上了同一個 bucket，看到的是同一本記帳本。這裡沒有複製 <code>modules</code> 資料夾也能 init，是因為 <code>app-b</code> 和 <code>app</code> 在同一層，<code>../modules/bucket</code> 剛好指到同一個地方。</p>



<h3 class="wp-block-heading">步驟 10：A 開始 apply，停在等 yes</h3>



<p class="wp-block-paragraph"><strong>在 A 的分頁</strong>，把環境標籤從 <code>dev</code> 改成 <code>test</code>，跑到它問 yes 時先不要回答：</p>



<pre class="wp-block-code"><code>terraform apply -var=env=test</code></pre>



<pre class="wp-block-code"><code>  # module.assets.google_storage_bucket.this will be updated in-place
（中間省略）
  # module.logs.google_storage_bucket.this will be updated in-place
（中間省略）
Plan: 0 to add, 2 to change, 0 to destroy.

Do you want to perform these actions?
  Terraform will perform the actions described above.
  Only 'yes' will be accepted to approve.

  Enter a value:</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="983" src="https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-11-a-waiting.png" alt="A 執行 terraform apply -var=env=test，plan 顯示兩個 bucket 的 env 標籤從 dev 改成 test，Plan: 0 to add, 2 to change，停在 Enter a value 等待輸入" class="wp-image-14212" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-11-a-waiting.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-11-a-waiting-300x184.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-11-a-waiting-1024x629.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-11-a-waiting-768x472.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-11-a-waiting-1536x944.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph"><strong>重點：從這一刻起，A 就拿著鎖了。</strong> 等 yes 的這段時間，鎖一直在。所以 apply 不要開著去吃飯，同事會整個卡住。</p>



<h3 class="wp-block-heading">步驟 11：B 同時跑 plan，被鎖擋下</h3>



<p class="wp-block-paragraph">A 的分頁保持不動，按 Cloud Shell 終端機上方分頁列的「+」，開出<strong>分頁 2 當 B</strong>。兩個分頁連的是同一台 Cloud Shell 機器、同一個家目錄。（截圖裡我是用 tmux 把畫面切成上下兩格拍的，上面是 A、下面是 B，效果一樣。tmux 是在一個終端機裡切出多個視窗的工具。）</p>



<p class="wp-block-paragraph"><strong>在 B 的分頁</strong>：</p>



<pre class="wp-block-code"><code>cd ~/do-11/app-b
terraform plan</code></pre>



<pre class="wp-block-code"><code>（前面幾行捲出畫面了，完整的開頭在步驟 14）
│ Error 412: At least one of the pre-conditions you specified did not hold.,
│ conditionNotMet
│ Lock Info:
│   ID:        1796406128790709
│   Path:      gs://do-11-dong-dong-gcp-3-tfstate/app/default.tflock
│   Operation: OperationTypeApply
│   Who:       你的帳號@cloudshell
│   Version:   1.17.3
│   Created:   2026-12-04 17:42:08.734390205 +0000 UTC
│   Info:
│
│
│ Terraform acquires a state lock to protect the state from being written
│ by multiple users at the same time. Please resolve the issue above and try
│ again. For most commands, you can disable locking with the "-lock=false"
│ flag, but this is not recommended.</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="515" src="https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-12-lock-error.png" alt="terraform state lock 實測：上半格 A 的 apply 停在 Enter a value，下半格 B 的 terraform plan 出現 Error 412 conditionNotMet，Lock Info 顯示鎖 ID、鎖檔路徑 default.tflock、操作 OperationTypeApply" class="wp-image-14213" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-12-lock-error.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-12-lock-error-300x97.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-12-lock-error-1024x330.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-12-lock-error-768x247.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-12-lock-error-1536x494.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph">這段錯誤一行一行看：</p>


<ul class="wp-block-list">
<li><strong><code>Error 412 ... conditionNotMet</code></strong>：B 想寫鎖檔，但鎖檔已經存在，Cloud Storage 拒絕。完整訊息的第一行是 <code>Error acquiring the state lock</code>（拿不到鎖），B 什麼都沒改，plan 直接停</li>

<li><strong>Lock Info</strong>：誰拿著鎖。<code>Operation</code> 是 apply、<code>Version</code> 是 1.17.3、<code>Created</code> 是拿鎖的時間（<code>+0000 UTC</code> 是世界標準時間，台灣要加 8 小時，也就是凌晨 1:42）。<code>Who</code> 是 Cloud Shell 的使用者名稱加機器名稱，截圖裡我換成「你的帳號@cloudshell」</li>

<li><strong>最後一段</strong>：說你可以用 <code>-lock=false</code> 關掉鎖，但「不建議」。關掉鎖就等於拿掉「使用中」的牌子，兩個人真的會同時改</li>
</ul>



<p class="wp-block-paragraph">這時候 B 該做的是<strong>等 A 做完</strong>，或去問 A 在幹嘛。官方文件另外有 <code>-lock-timeout</code> 參數，可以讓 B 等一段時間再放棄（<a href="https://developer.hashicorp.com/terraform/cli/commands/plan">plan 指令說明</a>），這篇沒有實測。</p>



<h3 class="wp-block-heading">步驟 12：看看鎖檔長什麼樣子</h3>



<p class="wp-block-paragraph"><strong>還是在 B 的分頁</strong>，列出 bucket 裡的檔案，再印出鎖檔內容：</p>



<pre class="wp-block-code"><code>gcloud storage ls gs://do-11-dong-dong-gcp-3-tfstate/app/
gcloud storage cat gs://do-11-dong-dong-gcp-3-tfstate/app/default.tflock; echo</code></pre>



<pre class="wp-block-code"><code>gs://do-11-dong-dong-gcp-3-tfstate/app/default.tflock
gs://do-11-dong-dong-gcp-3-tfstate/app/default.tfstate
{"ID":"aa682a93-8574-5d9a-d2af-3cac8a4e55e2","Operation":"OperationTypeApply","Info":"","Who":"你的帳號@cloudshell","Version":"1.17.3","Created":"2026-12-04T17:42:08.734390205Z","Path":"gs://do-11-dong-dong-gcp-3-tfstate/app/default.tflock"}</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="185" src="https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-13-tflock-file.png" alt="Cloud Storage 裡 terraform state 旁邊多了 default.tflock 鎖檔，gcloud storage cat 印出鎖檔的 JSON，ID 是 aa682a93 開頭的一串英數字" class="wp-image-14214" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-13-tflock-file.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-13-tflock-file-300x35.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-13-tflock-file-1024x118.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-13-tflock-file-768x89.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-13-tflock-file-1536x178.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph">鎖檔是一小段 JSON（用大括號和「名稱: 值」記資料的文字格式），跟錯誤訊息的 Lock Info 幾乎一樣。<strong>但仔細看 ID</strong>：鎖檔裡是 <code>aa682a93-...</code> 這種英數字，錯誤訊息裡是 <code>1796406128790709</code> 這種純數字，兩個不一樣。步驟 15 會遇到這個差別。</p>



<h3 class="wp-block-heading">步驟 13：A 打 no，鎖就消失</h3>



<p class="wp-block-paragraph"><strong>回到 A 的分頁</strong>，打 <code>no</code> 取消：</p>



<pre class="wp-block-code"><code>  Enter a value: no

Apply cancelled.</code></pre>



<p class="wp-block-paragraph"><strong>再到 B 的分頁</strong>看一次：</p>



<pre class="wp-block-code"><code>gcloud storage ls gs://do-11-dong-dong-gcp-3-tfstate/app/; terraform plan | tail -3</code></pre>



<pre class="wp-block-code"><code>gs://do-11-dong-dong-gcp-3-tfstate/app/default.tfstate
Terraform has compared your real infrastructure against your configuration
and found no differences, so no changes are needed.</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="353" src="https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-14-unlocked.png" alt="A 輸入 no 顯示 Apply cancelled，B 再列 bucket 只剩 default.tfstate，鎖檔消失，terraform plan 顯示沒有差異" class="wp-image-14215" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-14-unlocked.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-14-unlocked-300x66.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-14-unlocked-1024x226.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-14-unlocked-768x169.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-14-unlocked-1536x339.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph">鎖檔不見了，B 的 plan 也跑得動了。正常結束（做完、取消）時，Terraform 會自己把鎖拿走。</p>



<h3 class="wp-block-heading">步驟 14：A 的程式被砍掉，鎖留下來</h3>



<p class="wp-block-paragraph">麻煩的是<strong>不正常結束</strong>：真實情況是網路斷線、電腦當機、CI 工作被取消，程式來不及把鎖拿走。這一步是<strong>故意製造這種意外</strong>，平常不會這樣做。</p>



<p class="wp-block-paragraph"><strong>在 A 的分頁</strong>再跑一次，一樣停在等 yes，不要回答：</p>



<pre class="wp-block-code"><code>terraform apply -var=env=test</code></pre>



<p class="wp-block-paragraph"><strong>到 B 的分頁</strong>貼下面這行，把 A 的 terraform 強制結束。這行只在這個練習用，不要拿去公司的機器貼（截圖時我是從另一個連線到同一台 Cloud Shell 的終端機跑的，在 B 的分頁貼效果一樣）：</p>



<pre class="wp-block-code"><code>for p in $(pgrep -x terraform); do if [ "$(readlink /proc/$p/cwd)" = "$HOME/do-11/app" ]; then kill -9 $p; echo killed $p; fi; done</code></pre>



<p class="wp-block-paragraph">這行在做的事：找出「在 <code>~/do-11/app</code> 資料夾裡跑的 terraform」，只砍它，不會動到 B 自己或其他程式。<code>kill -9</code> 是 Linux 強制結束程式的指令：平常按 Ctrl+C 是請程式自己結束，程式有機會收拾；<code>kill -9</code> 不給它收拾的機會，才做得出「鎖留下來」的情況。輸出是 <code>killed 33319</code>，33319 是那個程式的編號。A 的分頁變成：</p>



<pre class="wp-block-code"><code>  Enter a value: Killed</code></pre>



<p class="wp-block-paragraph"><strong>在 B 的分頁</strong>再跑一次 plan：</p>



<pre class="wp-block-code"><code>terraform plan</code></pre>



<pre class="wp-block-code"><code>╷
│ Error: Error acquiring the state lock
│
│ Error message: writing
│ "gs://do-11-dong-dong-gcp-3-tfstate/app/default.tflock" failed: googleapi:
│ Error 412: At least one of the pre-conditions you specified did not hold.,
│ conditionNotMet
│ Lock Info:
│   ID:        1796406284140647
│   Path:      gs://do-11-dong-dong-gcp-3-tfstate/app/default.tflock
│   Operation: OperationTypeApply
│   Who:       你的帳號@cloudshell
│   Version:   1.17.3
│   Created:   2026-12-04 17:44:44.084138095 +0000 UTC</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="498" src="https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-15-stale-lock.png" alt="A 的 terraform 被 kill -9 強制結束顯示 Killed，B 的 terraform plan 仍然出現 Error acquiring the state lock，鎖 ID 是 1796406284140647" class="wp-image-14216" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-15-stale-lock.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-15-stale-lock-300x93.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-15-stale-lock-1024x319.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-15-stale-lock-768x239.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-15-stale-lock-1536x478.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph">A 已經不在了，鎖還在。這把鎖不會自己消失，<strong>沒人處理，整個團隊都不能 apply</strong>。</p>



<h3 class="wp-block-heading">步驟 15：用 force-unlock 解鎖，第一次就用錯 ID</h3>



<p class="wp-block-paragraph"><code>terraform force-unlock</code> 是手動把鎖拿掉，<code>-force</code> 是不再問一次確認。以下都<strong>在 B 的分頁</strong>做。</p>



<p class="wp-block-paragraph">先照直覺，再看一次鎖檔裡的 ID：</p>



<pre class="wp-block-code"><code>gcloud storage cat gs://do-11-dong-dong-gcp-3-tfstate/app/default.tflock; echo</code></pre>



<p class="wp-block-paragraph">這是步驟 14 新留下的那把鎖，所以 ID 跟步驟 12 不一樣，這次是 <code>665f17a4-d69a-e4a9-7653-5ab5b3411de9</code>（其他欄位的格式跟步驟 12 一樣）。拿它來解鎖：</p>



<pre class="wp-block-code"><code>terraform force-unlock -force 665f17a4-d69a-e4a9-7653-5ab5b3411de9</code></pre>



<pre class="wp-block-code"><code>Failed to unlock state: Lock ID should be numerical value, got '665f17a4-d69a-e4a9-7653-5ab5b3411de9'</code></pre>



<p class="wp-block-paragraph">失敗了：gcs backend 要的是<strong>數字</strong>。改用錯誤訊息 Lock Info 裡的 ID，這串數字要換成你自己步驟 14 錯誤訊息裡的那個：</p>



<pre class="wp-block-code"><code>terraform force-unlock -force 1796406284140647
gcloud storage ls gs://do-11-dong-dong-gcp-3-tfstate/app/</code></pre>



<pre class="wp-block-code"><code>Terraform state has been successfully unlocked!

The state has been unlocked, and Terraform commands should now be able to
obtain a new lock on the remote state.
gs://do-11-dong-dong-gcp-3-tfstate/app/default.tfstate</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="235" src="https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-16-force-unlock.png" alt="terraform force-unlock 用鎖檔裡的英數字 ID 失敗，顯示 Lock ID should be numerical value；改用錯誤訊息裡的數字 ID 1796406284140647 成功解鎖，bucket 只剩 default.tfstate" class="wp-image-14217" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-16-force-unlock.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-16-force-unlock-300x44.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-16-force-unlock-1024x150.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-16-force-unlock-768x113.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-16-force-unlock-1536x226.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph">這個數字是什麼？到步驟 28 刪 bucket 時列出所有版本，會看到 <code>default.tflock#1796406284140647</code>：它就是那個鎖檔在 Cloud Storage 的 <strong>generation</strong>（版本編號）。所以記住：<strong>gcs backend 解鎖，用錯誤訊息裡的數字，不要去翻鎖檔</strong>。</p>



<p class="wp-block-paragraph"><a href="https://developer.hashicorp.com/terraform/cli/commands/force-unlock">force-unlock 的官方說明</a>也提醒：只有確定拿鎖的人已經不在了才能用。A 如果其實還在跑，你把鎖拿掉，兩個人就會同時改 state。實務上先在群組問一聲「誰在 apply？」再解鎖。</p>



<h3 class="wp-block-heading">步驟 16：換用官方 Registry 模組</h3>



<p class="wp-block-paragraph">自己寫的模組適合放公司規定；常見的東西也可以直接用 Google 維護的。這裡用 Registry 上的 <a href="https://registry.terraform.io/modules/terraform-google-modules/cloud-storage/google/latest"><code>terraform-google-modules/cloud-storage/google</code></a> 多建一個 bucket。新增 <code>registry.tf</code>：</p>



<pre class="wp-block-code"><code>cd ~/do-11/app
cat &gt; registry.tf &lt;&lt;'EOF'
# 官方 Registry 上 Google 維護的 Cloud Storage 模組
module "shared" {
  source  = "terraform-google-modules/cloud-storage/google"
  version = "~&gt; 12.4"

  project_id               = var.project_id
  prefix                   = "do-11-${var.project_id}"
  names                    = ["shared"]
  location                 = "asia-east1"
  public_access_prevention = "enforced"
  labels = {
    env        = var.env
    managed-by = "terraform"
  }
}
EOF
terraform init | grep -E 'Downloading|^- |Installing|Installed'; ls .terraform/modules/shared | head -8</code></pre>


<ul class="wp-block-list">
<li><code>source</code> 不是資料夾路徑，而是 Registry 上的名字（<code>組織/模組名/provider</code>）</li>

<li><code>version = "~&gt; 12.4"</code>：用 12.4 以上、13.0 以下的版本。Registry 模組<strong>一定要寫 version</strong>，不然作者改了大版本，你下次 init 就默默換掉（<a href="https://developer.hashicorp.com/terraform/language/modules/syntax">HashiCorp 建議</a>）</li>

<li><code>public_access_prevention = "enforced"</code>：這行是我特別加的，原因寫在這一步的最後</li>
</ul>



<pre class="wp-block-code"><code>Downloading registry.terraform.io/terraform-google-modules/cloud-storage/google 12.4.1 for shared...
- shared in .terraform/modules/shared
- Reusing version 8.12.0 of hashicorp/google from the dependency lock file
- Finding hashicorp/random versions matching "&gt;= 2.1.0"...
- Using previously-installed hashicorp/google v8.12.0
- Installing hashicorp/random v3.9.1...
- Installed hashicorp/random v3.9.1 (signed by HashiCorp)
build
CHANGELOG.md
CODEOWNERS
CONTRIBUTING.md
docs
examples
LICENSE
main.tf</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="561" src="https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-17-registry-init.png" alt="terraform init 從 Registry 下載 terraform-google-modules/cloud-storage/google 12.4.1 到 .terraform/modules/shared，還多安裝了 hashicorp/random v3.9.1" class="wp-image-14218" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-17-registry-init.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-17-registry-init-300x105.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-17-registry-init-1024x359.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-17-registry-init-768x269.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-17-registry-init-1536x539.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph">兩個重點：</p>


<ol class="wp-block-list">
<li><strong>抓到 12.4.1</strong>，下載到 <code>.terraform/modules/shared</code>，是一整包有文件、範例的專案</li>

<li><strong>多裝了一個 <code>hashicorp/random</code> provider</strong>：這個模組會用亂數幫 bucket 名稱加尾巴（預設 <code>randomize_suffix = false</code>，沒開），但它宣告需要 random，所以 init 就會裝</li>
</ol>



<p class="wp-block-paragraph">我看了模組的<a href="https://github.com/terraform-google-modules/terraform-google-cloud-storage">原始碼</a>：<code>public_access_prevention</code> 預設是 <code>inherited</code>（照組織的規定走，組織沒規定就允許公開），跟我自己模組寫死的 <code>enforced</code> 不一樣。<strong>用別人的模組前，先看預設值合不合你的規定</strong>，這就是我多加那一行的原因。</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/do11-cards-02-modules.png" alt="Terraform modules 比較：自己寫的模組 source 是 ../modules/bucket，三個檔把禁止公開、統一權限、貼標籤寫死，實測叫兩次建兩個 bucket；官方 Registry 模組 terraform-google-modules/cloud-storage/google 由 Google 維護，實測 12.4.1，預設 public_access_prevention 是 inherited" class="wp-image-14219" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do11-cards-02-modules.png 1200w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-cards-02-modules-300x169.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-cards-02-modules-1024x576.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-cards-02-modules-768x432.png 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<h3 class="wp-block-heading">步驟 17：plan，看 Registry 模組的資源名稱</h3>



<pre class="wp-block-code"><code>terraform plan | grep -E '# |Plan:'</code></pre>



<pre class="wp-block-code"><code>  # module.shared.google_storage_bucket.buckets["shared"] will be created
Plan: 1 to add, 0 to change, 0 to destroy.</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1307" height="211" src="https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-18-registry-plan.png" alt="terraform plan 顯示 module.shared.google_storage_bucket.buckets[&quot;shared&quot;] will be created，Plan: 1 to add" class="wp-image-14220" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-18-registry-plan.png 1307w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-18-registry-plan-300x48.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-18-registry-plan-1024x165.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-18-registry-plan-768x124.png 768w" sizes="(max-width: 1307px) 100vw, 1307px" /></figure>



<p class="wp-block-paragraph">資源叫 <code>buckets["shared"]</code>：這個模組用一份設定建很多個 bucket，<code>names</code> 裡有幾個名字就建幾個，用名字當索引。bucket 名稱是模組用 <code>-</code> 把 <code>prefix</code> 和 <code>names</code> 接起來，結果是 <code>do-11-dong-dong-gcp-3-shared</code>。</p>



<h3 class="wp-block-heading">步驟 18：apply，三個資源都在同一本帳</h3>



<pre class="wp-block-code"><code>terraform apply -auto-approve | grep -E 'Creat|Apply'; terraform state list</code></pre>



<pre class="wp-block-code"><code>module.shared.google_storage_bucket.buckets["shared"]: Creating...
module.shared.google_storage_bucket.buckets["shared"]: Creation complete after 2s [id=do-11-dong-dong-gcp-3-shared]
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
module.assets.google_storage_bucket.this
module.logs.google_storage_bucket.this
module.shared.google_storage_bucket.buckets["shared"]</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="275" src="https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-19-registry-apply.png" alt="terraform apply 用官方 Registry 模組建出 do-11-dong-dong-gcp-3-shared，terraform state list 列出 module.assets、module.logs、module.shared 三個資源" class="wp-image-14221" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-19-registry-apply.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-19-registry-apply-300x52.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-19-registry-apply-1024x176.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-19-registry-apply-768x132.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-19-registry-apply-1536x264.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph">自己寫的模組和 Registry 模組建的資源，記在同一本 state 裡。這次 apply 有寫 state，也有拿鎖、放鎖，過程很快所以看不到。</p>



<h3 class="wp-block-heading">步驟 19：看 state 留了幾個版本</h3>



<p class="wp-block-paragraph">步驟 2 開了版本控管，每次 state 被蓋掉，舊的都會留下。<code>gcloud storage ls -a</code> 會列出所有版本（<code>#</code> 後面就是 generation），再從每個版本裡挑出 <code>serial</code>（state 的流水號）：</p>



<pre class="wp-block-code"><code>for o in $(gcloud storage ls -a gs://do-11-dong-dong-gcp-3-tfstate/app/default.tfstate); do echo "$o  $(gcloud storage cat "$o" | grep -o '"serial": [0-9]*')"; done</code></pre>



<pre class="wp-block-code"><code>gs://do-11-dong-dong-gcp-3-tfstate/app/default.tfstate#1796406055619924  "serial": 1
gs://do-11-dong-dong-gcp-3-tfstate/app/default.tfstate#1796406067242927  "serial": 4
gs://do-11-dong-dong-gcp-3-tfstate/app/default.tfstate#1796406419829069  "serial": 5</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="151" src="https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-20-state-versions.png" alt="gcloud storage ls -a 列出 terraform state 的 3 個版本，serial 分別是 1、4、5，每個版本有自己的 generation 編號" class="wp-image-14222" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-20-state-versions.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-20-state-versions-300x28.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-20-state-versions-1024x97.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-20-state-versions-768x72.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-20-state-versions-1536x145.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph">三個版本，各代表一次寫入：</p>


<ul class="wp-block-list">
<li><strong>serial 1</strong>：步驟 7 的 init 一接上 gcs，就先寫了一份<strong>空的</strong> state（我另外查了大小，只有 181 bytes、0 個資源），這時我還沒打 yes</li>

<li><strong>serial 4</strong>：打 yes 之後，從本機搬上來的那份（本機是 3，搬上來加 1）。generation 的數字看起來是寫入時間（微秒），這兩個相差約 11.6 秒，正好是我讀提示、打 yes 的時間</li>

<li><strong>serial 5</strong>：步驟 18 加了 <code>shared</code> bucket 之後</li>
</ul>



<p class="wp-block-paragraph">步驟 10 和 14 的 apply 都沒有真的做（取消、被砍），所以沒有留下版本。哪天 state 被寫壞，就是從這些舊版本救回來。</p>



<h3 class="wp-block-heading">步驟 20：換 Infrastructure Manager，先看它支援哪些 Terraform 版本</h3>



<p class="wp-block-paragraph">接下來改用 Infrastructure Manager。先看它在台灣區域支援哪些 Terraform 版本：</p>



<pre class="wp-block-code"><code>gcloud infra-manager terraform-versions list --location=asia-east1</code></pre>



<pre class="wp-block-code"><code>NAME    STATE     SUPPORT_TIME                    DEPRECATE_TIME                  OBSOLETE_TIME
1.16.5  ACTIVE    2026-11-02T18:52:32.953780545Z
1.3.10  ACTIVE    2024-01-31T17:49:13.895229581Z
1.4.7   ACTIVE    2024-01-31T17:49:13.895229581Z
1.5.7   ACTIVE    2024-01-31T17:49:13.895229581Z
1.2.3   OBSOLETE  2024-01-31T17:49:13.895229581Z  2026-01-08T21:02:27.708318733Z  2026-02-09T19:10:13.105849537Z</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="281" src="https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-21-im-tf-versions.png" alt="gcloud infra-manager terraform-versions list 列出 Infrastructure Manager 支援的 Terraform 版本：1.16.5、1.3.10、1.4.7、1.5.7 是 ACTIVE，1.2.3 已經 OBSOLETE" class="wp-image-14223" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-21-im-tf-versions.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-21-im-tf-versions-300x53.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-21-im-tf-versions-1024x180.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-21-im-tf-versions-768x135.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-21-im-tf-versions-1536x270.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph">能用的只有 4 個版本，最新是 1.16.5，<strong>沒有我在 Cloud Shell 用的 1.17.3</strong>。這跟授權有關：Terraform 1.5.7 以前是開源授權（MPL 2.0），之後改成 BSL（Business Source License，一般使用免費，但限制拿來做跟 HashiCorp 競爭的商業服務）。對你來說重點只有一個：用 1.5.7 以前的版本不收管理費，新版要收；<a href="https://cloud.google.com/infrastructure-manager/pricing">計費頁</a>寫明 1.5.7 以前不收管理費，1.16.5 以後要照管理的資源數收費（2026 年 12 月查官方文件）。沒指定版本時，預設用免費的 1.5.7。</p>



<h3 class="wp-block-heading">步驟 21：建一個服務帳戶給 Infrastructure Manager 用</h3>



<p class="wp-block-paragraph">服務帳戶（service account）是給程式用的帳號，不是給人登入的；IAM 角色（role）是「這個帳號能做哪些事」的權限清單。Infrastructure Manager 不用你的帳號跑 Terraform，而是用你指定的服務帳戶，所以要先建一個，再給它兩種角色：</p>


<ul class="wp-block-list">
<li><code>roles/config.agent</code>：讓 Infrastructure Manager 能用它的身分執行（官方規定一定要有）</li>

<li>設定裡要建的資源的權限：這篇要建 Artifact Registry 存放區，所以給 <code>roles/artifactregistry.admin</code>。正式環境要照實際要建的東西給最小權限</li>
</ul>



<pre class="wp-block-code"><code>gcloud iam service-accounts create do-11-im --display-name='do-11 Infra Manager'
gcloud projects add-iam-policy-binding dong-dong-gcp-3 --member=serviceAccount:do-11-im@dong-dong-gcp-3.iam.gserviceaccount.com --role=roles/config.agent --condition=None --format=none
gcloud projects add-iam-policy-binding dong-dong-gcp-3 --member=serviceAccount:do-11-im@dong-dong-gcp-3.iam.gserviceaccount.com --role=roles/artifactregistry.admin --condition=None --format=none</code></pre>


<ul class="wp-block-list">
<li><code>--condition=None</code>：這個權限不加條件。專案裡已經有「有條件的權限」時，不寫這個 gcloud 會停下來問你</li>

<li><code>--format=none</code>：不印出整份專案權限清單，那份清單裡會有其他人的 email</li>
</ul>



<pre class="wp-block-code"><code>Created service account [do-11-im].
Service account email: do-11-im@dong-dong-gcp-3.iam.gserviceaccount.com
Updated IAM policy for project [dong-dong-gcp-3].
Updated IAM policy for project [dong-dong-gcp-3].</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/do11-shots-22-im-service-account.png" alt="gcloud 建立服務帳戶 do-11-im，並給它 roles/config.agent 和 roles/artifactregistry.admin 兩個角色，顯示 Updated IAM policy 兩次" class="wp-image-14224" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-22-im-service-account.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-22-im-service-account-300x35.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-22-im-service-account-1024x120.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-22-im-service-account-768x90.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-22-im-service-account-1536x180.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<h3 class="wp-block-heading">步驟 22：寫設定、交給 Infrastructure Manager 部署</h3>



<p class="wp-block-paragraph">開一個新資料夾放要交出去的設定。跟步驟 3、7 的設定最大的差別：<strong>這份設定裡沒有 backend 區塊</strong>。<a href="https://docs.cloud.google.com/infrastructure-manager/docs/infra-manager-terraform">官方文件</a>寫明 state 由 Infrastructure Manager 管，設定裡不要寫 backend。<strong>最後的部署指令會跑 3～4 分鐘，畫面一直印點點點是正常的，不要按 Ctrl+C 中斷。</strong></p>



<pre class="wp-block-code"><code>mkdir -p ~/do-11/im &amp;&amp; cd ~/do-11/im
cat &gt; main.tf &lt;&lt;'EOF'
terraform {
  required_providers {
    google = {
      source  = "hashicorp/google"
      version = "~&gt; 8.0"
    }
  }
}

variable "project_id" {
  type = string
}

provider "google" {
  project = var.project_id
}

# Artifact Registry 存放區：放容器映像檔的地方
resource "google_artifact_registry_repository" "repo" {
  repository_id = "do-11-im-repo"
  location      = "asia-east1"
  format        = "DOCKER"
  description   = "Infra Manager demo"

  labels = {
    managed-by = "infra-manager"
  }
}

output "repo_id" {
  value = google_artifact_registry_repository.repo.id
}
EOF
date +%T; gcloud infra-manager deployments apply projects/dong-dong-gcp-3/locations/asia-east1/deployments/do-11-im --service-account=projects/dong-dong-gcp-3/serviceAccounts/do-11-im@dong-dong-gcp-3.iam.gserviceaccount.com --local-source=. --input-values=project_id=dong-dong-gcp-3; date +%T</code></pre>



<p class="wp-block-paragraph">部署指令有點長，拆開看：</p>


<ul class="wp-block-list">
<li><code>deployments apply projects/.../locations/asia-east1/deployments/do-11-im</code>：建立（或更新）一個叫 <code>do-11-im</code> 的部署，放在台灣區域</li>

<li><code>--service-account=</code>：用步驟 21 的服務帳戶，要寫完整的 <code>projects/專案/serviceAccounts/email</code> 格式</li>

<li><code>--local-source=.</code>：把目前資料夾（<code>.</code>）的設定上傳上去。也可以改用 Git repo 或 Cloud Storage 當來源</li>

<li><code>--input-values=project_id=...</code>：幫 <code>project_id</code> 這個變數填值，等於自己跑時的 <code>terraform.tfvars</code></li>

<li>前後的 <code>date +%T</code> 是印出當下時間，算花了多久</li>
</ul>



<pre class="wp-block-code"><code>01:48:41
Uploading 1 file(s) totalling 592 bytes.
Creating the deployment...
（中間是一長串點點點，省略）
.......done.
01:52:27</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/do11-shots-23-im-apply.png" alt="gcloud infra-manager deployments apply 上傳 1 個 592 bytes 的檔案，Creating the deployment 一路印點，從 01:48:41 到 01:52:27 才 done" class="wp-image-14225" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-23-im-apply.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-23-im-apply-300x52.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-23-im-apply-1024x179.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-23-im-apply-768x134.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-23-im-apply-1536x268.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph"><strong>從 01:48:41 到 01:52:27，花了 3 分 46 秒。</strong> 自己跑 apply 建一個 bucket 只要 2 秒，這裡建一個空的存放區卻要將近 4 分鐘，原因在步驟 24。</p>



<h3 class="wp-block-heading">步驟 23：看部署的結果</h3>



<pre class="wp-block-code"><code>gcloud infra-manager deployments describe projects/dong-dong-gcp-3/locations/asia-east1/deployments/do-11-im --format='yaml(state,tfVersion,latestRevision,serviceAccount,artifactsGcsBucket)'
gcloud infra-manager revisions list --deployment=projects/dong-dong-gcp-3/locations/asia-east1/deployments/do-11-im
gcloud artifacts repositories list --location=asia-east1 --filter='name~do-11' --format='table(name.basename(),format,labels)'</code></pre>



<pre class="wp-block-code"><code>artifactsGcsBucket: gs://600195576280-asia-east1-blueprint-config
latestRevision: projects/dong-dong-gcp-3/locations/asia-east1/deployments/do-11-im/revisions/r-0
serviceAccount: projects/dong-dong-gcp-3/serviceAccounts/do-11-im@dong-dong-gcp-3.iam.gserviceaccount.com
state: ACTIVE
tfVersion: 1.5.7
NAME  STATE    TF_VERSION  CREATE_TIME                     UPDATE_TIME
r-0   APPLIED  1.5.7       2026-12-04T17:48:54.009111788Z  2026-12-04T17:52:16.074596766Z
Listing items under project dong-dong-gcp-3, location asia-east1.

REPOSITORY     FORMAT  LABELS
do-11-im-repo  DOCKER  goog-ccm=true,goog-terraform-provisioned=true,managed-by=infra-manager</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="315" src="https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-24-im-describe.png" alt="gcloud infra-manager deployments describe 顯示部署 state ACTIVE、tfVersion 1.5.7、最新修訂版本 r-0，revisions list 顯示 r-0 APPLIED，Artifact Registry 存放區 do-11-im-repo 已建立" class="wp-image-14226" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-24-im-describe.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-24-im-describe-300x59.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-24-im-describe-1024x202.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-24-im-describe-768x151.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-24-im-describe-1536x302.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>


<ul class="wp-block-list">
<li><strong><code>tfVersion: 1.5.7</code></strong>：沒指定版本，用的就是預設的免費版</li>

<li><strong><code>r-0 APPLIED</code></strong>：第一個修訂版本，套用成功。之後每改一次設定再 apply，會多一個 <code>r-1</code>、<code>r-2</code></li>

<li><strong><code>artifactsGcsBucket</code></strong>：Infrastructure Manager 自動建的 bucket，名稱是「專案編號-區域-blueprint-config」，放每次執行的紀錄和設定</li>

<li><strong>存放區的標籤多了 <code>goog-ccm=true</code></strong>：我只寫了 <code>managed-by</code>。<code>goog-terraform-provisioned</code> 是 google provider 自己加的（第 10 篇遇過），<code>goog-ccm</code> 是第 10 篇自己跑 apply 時沒出現過的，透過 Infrastructure Manager 建才多了它</li>
</ul>



<p class="wp-block-paragraph">在 Console 也看得到。上方搜尋列打「Infrastructure Manager」進去，部署清單裡有 <code>do-11-im</code>，狀態「已建立」：</p>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="322" src="https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-c1-console-im-list.png" alt="Google Cloud Console 的 Infrastructure Manager 部署清單，do-11-im 位於 asia-east1，狀態已建立" class="wp-image-14227" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-c1-console-im-list.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-c1-console-im-list-300x60.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-c1-console-im-list-1024x206.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-c1-console-im-list-768x155.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-c1-console-im-list-1536x309.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph">點進去是部署的詳細資料：State 顯示「有效」（就是 gcloud 看到的 ACTIVE），Terraform Version 是 1.5.7，下面有「總覽、資源、修訂版本、預覽、輸入內容、輸出內容」幾個分頁，右上角可以直接看 Cloud Build 記錄：</p>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="1157" src="https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-c2-console-im-deployment.png" alt="Infrastructure Manager 部署 do-11-im 的詳細資料頁，Terraform Version 1.5.7，有總覽、資源、修訂版本、預覽、輸入內容、輸出內容分頁和 Cloud Build 記錄按鈕" class="wp-image-14228" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-c2-console-im-deployment.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-c2-console-im-deployment-300x217.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-c2-console-im-deployment-1024x740.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-c2-console-im-deployment-768x555.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-c2-console-im-deployment-1536x1111.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<h3 class="wp-block-heading">步驟 24：看 Cloud Build 裡到底跑了什麼</h3>



<p class="wp-block-paragraph">每次執行的紀錄都放在 <code>artifactsGcsBucket</code> 裡，路徑是「部署名稱/修訂版本/logs」。下面的 <code>600195576280</code> 是我的專案編號（不是專案 ID），換成你步驟 23 輸出裡的那個：</p>



<pre class="wp-block-code"><code>gcloud storage cat gs://600195576280-asia-east1-blueprint-config/do-11-im/r-0/logs/log-*.txt | grep -E 'Running terraform|backend|^Terraform 1|Creation complete|Apply complete' | cut -c1-150
gcloud storage ls gs://600195576280-asia-east1-blueprint-config/do-11-im/r-0/apply_results/content/</code></pre>



<pre class="wp-block-code"><code>time="2026-12-04T17:51:39Z" level=info msg="Running terraform init in /workspace/apply/content"
Initializing the backend...
Successfully configured the backend "http"! Terraform will automatically
use this backend unless the backend configuration changes.
time="2026-12-04T17:51:41Z" level=info msg="Running terraform version"
time="2026-12-04T17:51:41Z" level=info msg="Running terraform validate in /workspace/apply/content"
time="2026-12-04T17:51:42Z" level=info msg="Running terraform plan in /workspace/apply/content"
Terraform 1.5.7
time="2026-12-04T17:51:44Z" level=info msg="Running terraform show in /workspace/apply/content on /tmp/tfplan-2770917975/plan.out"
time="2026-12-04T17:51:45Z" level=info msg="Running terraform apply in /workspace/apply/content with /tmp/tfplan-2770917975/plan.out plan"
Terraform 1.5.7
google_artifact_registry_repository.repo: Creation complete after 10s [id=projects/dong-dong-gcp-3/locations/asia-east1/repositories/do-11-im-repo]
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
time="2026-12-04T17:51:57Z" level=info msg="Running terraform show in /workspace/apply/content"
time="2026-12-04T17:51:58Z" level=info msg="Running terraform output in /workspace/apply/content"
gs://600195576280-asia-east1-blueprint-config/do-11-im/r-0/apply_results/content/.terraform.lock.hcl
gs://600195576280-asia-east1-blueprint-config/do-11-im/r-0/apply_results/content/config.auto.tfvars
gs://600195576280-asia-east1-blueprint-config/do-11-im/r-0/apply_results/content/main.tf</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="425" src="https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-25-im-cloud-build-log.png" alt="Infrastructure Manager 的 Cloud Build 執行紀錄：依序跑 terraform init、version、validate、plan、show、apply，backend 是 http，Terraform 1.5.7，Artifact Registry 存放區 Creation complete after 10s" class="wp-image-14229" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-25-im-cloud-build-log.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-25-im-cloud-build-log-300x80.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-25-im-cloud-build-log-1024x272.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-25-im-cloud-build-log-768x204.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-25-im-cloud-build-log-1536x408.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph">這份紀錄回答了三個問題：</p>


<ol class="wp-block-list">
<li><strong>它做的事跟你自己做的一樣</strong>：<code>init</code> → <code>validate</code>（檢查語法）→ <code>plan</code> 存成檔案 → <code>apply</code> 那個計畫檔。先存計畫再套用，確保套用的就是剛剛算出來的那份</li>

<li><strong>state 去哪了</strong>：<code>Successfully configured the backend "http"</code>。Infrastructure Manager 自己幫你接了一個 http backend，所以你的設定不能再寫 backend</li>

<li><strong>為什麼要等 3 分 46 秒</strong>：Terraform 從 17:51:39 跑到 17:51:58，真正建存放區只花 10 秒。我用 <code>gcloud builds list</code> 查，這次 Cloud Build 從開始到結束 35 秒，其他時間是部署建立後、建置開始前的等待</li>
</ol>



<p class="wp-block-paragraph"><code>apply_results/content/</code> 裡有 <code>.terraform.lock.hcl</code>：我設定寫 <code>~&gt; 8.0</code>，它在 Terraform 1.5.7 底下裝的也是 google provider 8.12.0，舊版 Terraform 照樣能用新版 provider。</p>



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



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



<p class="wp-block-paragraph">這篇建了四類東西：Infrastructure Manager 部署（含存放區）、服務帳戶和它的權限、三個模組建的 bucket、放 state 的 bucket。<strong>刪的順序要倒過來</strong>：state bucket 一定最後刪，不然 Terraform 就找不到記帳本，沒辦法用 destroy 刪那三個 bucket。</p>



<p class="wp-block-paragraph">不刪的話會怎麼收費：</p>


<ul class="wp-block-list">
<li><strong>bucket</strong>：空的不收錢。放了檔案，台灣 <code>asia-east1</code> 的 Standard 儲存是每 GiB 每月 0.020 美元（第 10 篇查的 <a href="https://cloud.google.com/storage/pricing">Cloud Storage 定價</a>）。<strong>算一次</strong>：state 只有幾 KB；假設一個大專案的 state 長到 1 MiB、留了 100 個舊版本，總共 100 MiB 約 0.1 GiB，0.1 × 0.020 ＝ 每月約 0.002 美元。花不了幾個錢，比較要在意的是<strong>舊版本裡也有明文的敏感資料</strong>，所以正式環境建議設<a href="https://docs.cloud.google.com/storage/docs/lifecycle">生命週期規則</a>，用 <code>daysSinceNoncurrentTime</code>（變成舊版本幾天後）或 <code>numNewerVersions</code>（後面已經有幾個新版本）自動清掉太舊的版本</li>

<li><strong>Infrastructure Manager</strong>：用 1.5.7 不收管理費。只照 Cloud Build 執行時間收，每個帳單帳戶每月有 2,500 分鐘免費建置時間（限預設集區的 e2-standard-2 機型），排隊的時間不算（<a href="https://cloud.google.com/build/pricing">Cloud Build 定價</a>，2026 年 12 月查）</li>

<li><strong>如果用付費的 1.16.5</strong>：每個帳單帳戶每月 500 個資源免費，超過的每個資源一年 1 美元，按秒計（<a href="https://cloud.google.com/infrastructure-manager/pricing">計費頁</a>）。<strong>算一次</strong>：假設公司用 1.16.5 管 800 個資源一整個月，超過的是 800 − 500 ＝ 300 個；300 × 1 美元 ÷ 12 個月 ≈ <strong>每月 25 美元</strong>。預覽（preview）不收管理費，只有真正 apply 的資源才算</li>

<li><strong>Artifact Registry 存放區</strong>：空的不收儲存費，推了映像檔才照容量收</li>

<li><strong>服務帳戶</strong>：免費，但留著一個有 <code>artifactregistry.admin</code> 權限的帳號沒人管，是資安風險</li>
</ul>



<h3 class="wp-block-heading">步驟 25：刪掉 Infrastructure Manager 部署</h3>



<pre class="wp-block-code"><code>date +%T; gcloud infra-manager deployments delete projects/dong-dong-gcp-3/locations/asia-east1/deployments/do-11-im --quiet; date +%T
gcloud artifacts repositories list --location=asia-east1 --filter='name~do-11'</code></pre>



<pre class="wp-block-code"><code>01:55:47
Delete request issued for: [do-11-im]
Waiting for operation [projects/dong-dong-gcp-3/locations/asia-east1/operations/operation-1796406949340-661d296166448-8070d9d2-48d21501] to complete...
（中間是一長串點點點，省略）
...done.
Deleted deployment [do-11-im].
01:56:28
Listing items under project dong-dong-gcp-3, location asia-east1.
Listed 0 items.</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/do11-shots-26-im-delete.png" alt="gcloud infra-manager deployments delete 刪除部署 do-11-im，從 01:55:47 到 01:56:28 完成，Artifact Registry 存放區列表變成 Listed 0 items" class="wp-image-14230" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-26-im-delete.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-26-im-delete-300x52.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-26-im-delete-1024x179.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-26-im-delete-768x134.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-26-im-delete-1536x268.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph">刪部署花了 41 秒，<strong>它建的存放區也一起刪掉了</strong>（<code>Listed 0 items</code>）。這是預設行為；<code>gcloud infra-manager deployments delete</code> 另外有 <code>--delete-policy</code> 參數，可以選 <code>abandon</code>（只刪部署紀錄、資源留著），這篇沒有用。</p>



<h3 class="wp-block-heading">步驟 26：拿掉權限、刪服務帳戶</h3>



<p class="wp-block-paragraph">先拿掉權限再刪帳號，不然專案的權限清單裡會留下「已刪除的帳號」：</p>



<pre class="wp-block-code"><code>gcloud projects remove-iam-policy-binding dong-dong-gcp-3 --member=serviceAccount:do-11-im@dong-dong-gcp-3.iam.gserviceaccount.com --role=roles/config.agent --condition=None --format=none
gcloud projects remove-iam-policy-binding dong-dong-gcp-3 --member=serviceAccount:do-11-im@dong-dong-gcp-3.iam.gserviceaccount.com --role=roles/artifactregistry.admin --condition=None --format=none
gcloud iam service-accounts delete do-11-im@dong-dong-gcp-3.iam.gserviceaccount.com --quiet</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].
deleted service account [do-11-im@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="169" src="https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-27-im-sa-delete.png" alt="gcloud projects remove-iam-policy-binding 拿掉 config.agent 和 artifactregistry.admin 兩個角色，再刪除服務帳戶 do-11-im" class="wp-image-14231" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-27-im-sa-delete.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-27-im-sa-delete-300x32.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-27-im-sa-delete-1024x108.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-27-im-sa-delete-768x81.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-27-im-sa-delete-1536x162.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<h3 class="wp-block-heading">步驟 27：terraform destroy，刪掉三個模組建的 bucket</h3>



<pre class="wp-block-code"><code>cd ~/do-11/app &amp;&amp; terraform destroy -auto-approve | grep -E 'Destr|Plan'</code></pre>



<pre class="wp-block-code"><code>Plan: 0 to add, 0 to change, 3 to destroy.
module.assets.google_storage_bucket.this: Destroying... [id=do-11-dong-dong-gcp-3-assets]
module.logs.google_storage_bucket.this: Destroying... [id=do-11-dong-dong-gcp-3-logs]
module.shared.google_storage_bucket.buckets["shared"]: Destroying... [id=do-11-dong-dong-gcp-3-shared]
module.assets.google_storage_bucket.this: Destruction complete after 1s
module.logs.google_storage_bucket.this: Destruction complete after 1s
module.shared.google_storage_bucket.buckets["shared"]: Destruction complete after 1s
Destroy complete! Resources: 3 destroyed.</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="369" src="https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-28-destroy.png" alt="terraform destroy 刪除 module.assets、module.logs、module.shared 三個 bucket，Destroy complete! Resources: 3 destroyed" class="wp-image-14232" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-28-destroy.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-28-destroy-300x69.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-28-destroy-1024x236.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-28-destroy-768x177.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-28-destroy-1536x354.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph">三個 bucket 都是空的，各 1 秒刪完。bucket 裡有檔案的話，Terraform 預設會刪不掉，這是保護，不要為了好刪就加 <code>force_destroy = true</code>。</p>



<h3 class="wp-block-heading">步驟 28：刪掉 state bucket，連舊版本一起刪</h3>



<p class="wp-block-paragraph">開了版本控管的 bucket，要加 <code>--all-versions</code> 才會連舊版本一起刪。先列一次所有版本，再刪：</p>



<pre class="wp-block-code"><code>gcloud storage ls -a gs://do-11-dong-dong-gcp-3-tfstate/app/
gcloud storage rm --recursive --all-versions gs://do-11-dong-dong-gcp-3-tfstate
gcloud storage buckets list --filter='name~^do-11-' --format='value(name)'</code></pre>



<pre class="wp-block-code"><code>gs://do-11-dong-dong-gcp-3-tfstate/app/default.tflock#1796406055519487
gs://do-11-dong-dong-gcp-3-tfstate/app/default.tflock#1796406055778959
gs://do-11-dong-dong-gcp-3-tfstate/app/default.tflock#1796406128790709
gs://do-11-dong-dong-gcp-3-tfstate/app/default.tflock#1796406251870134
gs://do-11-dong-dong-gcp-3-tfstate/app/default.tflock#1796406284140647
gs://do-11-dong-dong-gcp-3-tfstate/app/default.tflock#1796406404729716
gs://do-11-dong-dong-gcp-3-tfstate/app/default.tflock#1796406416405862
gs://do-11-dong-dong-gcp-3-tfstate/app/default.tflock#1796407030372541
gs://do-11-dong-dong-gcp-3-tfstate/app/default.tfstate#1796406055619924
gs://do-11-dong-dong-gcp-3-tfstate/app/default.tfstate#1796406067242927
gs://do-11-dong-dong-gcp-3-tfstate/app/default.tfstate#1796406419829069
gs://do-11-dong-dong-gcp-3-tfstate/app/default.tfstate#1796407033755274
Removing objects:
（中間省略）
Removing buckets:

Removing gs://do-11-dong-dong-gcp-3-tfstate/...</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="663" src="https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-29-delete-state-bucket.png" alt="gcloud storage ls -a 列出 state bucket 裡 8 個 default.tflock 和 4 個 default.tfstate 舊版本，gcloud storage rm --recursive --all-versions 全部刪除後再刪 bucket" class="wp-image-14233" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-29-delete-state-bucket.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-29-delete-state-bucket-300x124.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-29-delete-state-bucket-1024x424.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-29-delete-state-bucket-768x318.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-29-delete-state-bucket-1536x636.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph"><strong>12 個版本，其中 8 個是鎖檔。</strong> 每次拿鎖會寫一個鎖檔、放鎖會刪掉它，開了版本控管，被刪的鎖檔也留成舊版本。第三行的 <code>1796406128790709</code> 就是步驟 11 錯誤訊息裡的鎖 ID，第五行的 <code>1796406284140647</code> 是步驟 15 解掉的那把。最後一行 <code>buckets list</code> 沒有印出任何東西，代表 <code>do-11-</code> 開頭的 bucket 都刪光了。</p>



<p class="wp-block-paragraph">被刪的檔案會照步驟 2 的軟刪除設定再留 7 天，這段期間照儲存量計費，這裡只有幾 KB，可以忽略。</p>



<h3 class="wp-block-heading">步驟 29：刪掉練習資料夾</h3>



<p class="wp-block-paragraph">本機的 <code>terraform.tfstate.backup</code>（步驟 8 那份 state 全文）也在裡面，一起刪：</p>



<pre class="wp-block-code"><code>cd ~ &amp;&amp; rm -rf ~/do-11 &amp;&amp; ls -d ~/do-11</code></pre>



<pre class="wp-block-code"><code>ls: cannot access '~/do-11': No such file or directory</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="170" src="https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-30-cleanup.png" alt="刪除 Cloud Shell 家目錄的 ~/do-11 練習資料夾，ls 顯示 No such file or directory" class="wp-image-14234" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-30-cleanup.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-30-cleanup-300x32.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-30-cleanup-1024x109.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-30-cleanup-768x82.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-30-cleanup-1536x163.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<h3 class="wp-block-heading">Infrastructure Manager 自動建的兩個 bucket</h3>



<p class="wp-block-paragraph">部署時 Infrastructure Manager 和 gcloud 自動建了兩個 bucket，<strong>刪部署時不會跟著刪</strong>，名字也不是 <code>do-11-</code> 開頭：</p>


<ul class="wp-block-list">
<li><code>專案編號-asia-east1-blueprint-config</code>：放執行紀錄。刪完部署還留著 <code>archived-deployments/do-11-im_.../</code> 一包刪除時的紀錄</li>

<li><code>專案ID_infra_manager_staging</code>：<code>--local-source</code> 上傳設定用的暫存區</li>
</ul>



<p class="wp-block-paragraph">我用 <code>gcloud storage du -s</code> 看了大小：</p>



<pre class="wp-block-code"><code>27416        gs://600195576280-asia-east1-blueprint-config
0            gs://dong-dong-gcp-3_infra_manager_staging</code></pre>



<p class="wp-block-paragraph">一個 27 KB、一個是空的，儲存費可以忽略。這個專案以後還會用 Infrastructure Manager 的話，留著就好；確定不用了，可以用步驟 28 同樣的 <code>gcloud storage rm --recursive</code> 刪掉。專案裡有其他 Infrastructure Manager 部署時不要刪，那是大家共用的紀錄。</p>



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



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



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph"><strong>1. 搬完 state，本機還留一份全文</strong>：<code>-migrate-state</code> 之後 <code>terraform.tfstate</code> 變 0 bytes，但多了 5,935 bytes 的 <code>terraform.tfstate.backup</code>，就是搬家前的完整 state，要自己刪（步驟 8）。</p>



<p class="wp-block-paragraph"><strong>2. force-unlock 要用數字 ID，不是鎖檔裡的 ID</strong>：鎖檔 JSON 裡的 <code>ID</code> 是 <code>665f17a4-...</code> 這種英數字，拿去 force-unlock 會回 <code>Lock ID should be numerical value</code>；要用錯誤訊息 Lock Info 的數字，它其實是鎖檔在 Cloud Storage 的 generation（步驟 15、28）。</p>



<p class="wp-block-paragraph"><strong>3. 等 yes 的時候就拿著鎖</strong>：apply 停在 <code>Enter a value</code> 的時候，鎖已經在了，同事連 plan 都跑不了（步驟 10、11）。</p>



<p class="wp-block-paragraph"><strong>4. 版本控管也把鎖檔留下來了</strong>：刪 bucket 前列出 12 個版本，8 個是鎖檔、4 個是 state（步驟 28）。</p>



<p class="wp-block-paragraph"><strong>5. 第一個 state 版本是空的</strong>：init 一接上 gcs 就先寫了一份 181 bytes 的空 state（serial 1），打 yes 之後才寫入搬上來的那份（serial 4）（步驟 19）。</p>



<p class="wp-block-paragraph"><strong>6. 官方 Registry 模組的預設不一定是你要的</strong>：<code>public_access_prevention</code> 預設 <code>inherited</code>，不是 <code>enforced</code>；而且就算沒開隨機尾巴，init 也會多裝一個 random provider（步驟 16）。</p>



<p class="wp-block-paragraph"><strong>7. Infrastructure Manager 建一個空存放區要 3 分 46 秒</strong>：Terraform 本身只跑了約 20 秒、建資源 10 秒，大部分時間在等建置開始（步驟 22、24）。</p>



<p class="wp-block-paragraph"><strong>8. 不能用最新版 Terraform</strong>：支援清單最新是 1.16.5（要付費），預設 1.5.7；Cloud Shell 自己裝的 1.17.3 不在清單上（步驟 20）。</p>



<p class="wp-block-paragraph"><strong>9. 刪部署會連資源一起刪，但留下兩個 bucket</strong>：存放區跟著刪了，<code>blueprint-config</code> 和 <code>infra_manager_staging</code> 兩個 bucket 還在（步驟 25 之後）。</p>



<p class="wp-block-paragraph"><strong>10. 文件有的參數，gcloud 還沒有</strong>：Infrastructure Manager 官方文件提到 <code>--provider-source</code>，但 Cloud Shell 的 gcloud 594.0.1 跑 <code>gcloud infra-manager deployments apply --help</code> 找不到這個參數（2026 年 12 月 5 日實測）。</p>
</blockquote>



<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>1.2 管理基礎架構</strong></td><td>IaC 工具與代管服務（Application Design Center、<strong>Infrastructure Manager</strong>、Config Connector、GitOps、Terraform、Helm）</td><td>步驟 20～25；三種工具怎麼選</td></tr><tr><td><strong>1.2</strong></td><td>用 Google 建議的做法和藍圖改基礎架構（<strong>Terraform modules and blueprints</strong>）</td><td>步驟 3～6 自己寫模組；步驟 16～18 用 Google 維護的模組</td></tr><tr><td><strong>1.4 管理多個執行環境</strong></td><td>短暫環境（ephemeral environments）、設定與政策（configuration and policy）</td><td>同一個模組換 <code>env</code>；backend 用不同 prefix 分開各環境的 state</td></tr><tr><td><strong>2.1 建置管線</strong></td><td>應用程式<strong>和基礎架構</strong>的 CI/CD</td><td>Infrastructure Manager 用服務帳戶在 Cloud Build 跑、每次留修訂版本；CI 裡跑 Terraform 一定要遠端 state 加鎖</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></tr></thead><tbody><tr><td>「團隊多人一起改」「state 檔衝突、遺失」</td><td>遠端 state：<code>backend "gcs"</code>，bucket 開版本控管</td></tr><tr><td>「兩個人同時 apply」「避免同時修改」</td><td>state lock（gcs backend 內建）</td></tr><tr><td>「apply 中斷後一直顯示 state 被鎖住」</td><td>先確認沒人在跑，再 <code>terraform force-unlock</code></td></tr><tr><td>「state 被誤刪、寫壞要還原」</td><td>Cloud Storage 版本控管的舊版本</td></tr><tr><td>「state 有敏感資料」</td><td>bucket 禁止公開、只給需要的人權限，不放 Git</td></tr><tr><td>「同樣的資源設定在很多專案重複」「統一公司規範」</td><td>Terraform modules</td></tr><tr><td>「用 Google 建議的做法」「藍圖」</td><td>Google 維護的 Terraform blueprints and modules（<code>terraform-google-modules</code>）</td></tr><tr><td>「Google 代管」「不想自己架 Terraform 執行環境」「保留每次部署紀錄」</td><td>Infrastructure Manager</td></tr><tr><td>「用 Kubernetes 的方式管 GCP 資源」</td><td>Config Connector</td></tr><tr><td>「dev、staging、prod 各自的 state」</td><td>不同的 prefix（或不同的 bucket），同一份模組</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>「Terraform state 你們放哪？為什麼？」</strong>：放 Cloud Storage（<code>backend "gcs"</code>），因為要多人共用、要加鎖、要能還原。bucket 用 gcloud 事先建好、開版本控管、禁止公開、只給跑 Terraform 的身分權限</li>

<li><strong>「遇過 state lock 卡住嗎？怎麼處理？」</strong>：先看錯誤訊息的 Lock Info 是誰、什麼時候拿的，去問本人或看 CI 工作是不是還在跑；確定沒人在用，才用 <code>terraform force-unlock</code> 加錯誤訊息裡的 ID 解鎖。gcs backend 的 ID 是數字</li>

<li><strong>「本機的 state 怎麼搬到遠端？」</strong>：加 backend 區塊，跑 <code>terraform init -migrate-state</code>，回答 yes；搬完確認 <code>state list</code> 一樣、把本機留下的 <code>.backup</code> 刪掉</li>

<li><strong>「什麼時候該寫模組？」</strong>：同一種資源在很多地方用、而且有公司規定要統一的時候。用別人的模組要鎖版本、先看預設值</li>

<li><strong>「Infrastructure Manager 跟自己在 CI 跑 Terraform 差在哪？」</strong>：Infrastructure Manager 幫你管執行環境和 state、每次留修訂版本，但能用的 Terraform 版本有限（預設 1.5.7）、每次執行要等幾分鐘；自己跑彈性大，但 state bucket、權限、執行環境都要自己顧</li>
</ul>



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



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



<h3 class="wp-block-heading">terraform state 要放在哪裡比較好？</h3>



<p class="wp-block-paragraph">一個人練習放本機就好；團隊一起用，要放在大家都拿得到、有權限控管、能加鎖的地方。在 GCP 上最常見的是 Cloud Storage，用 <code>backend "gcs"</code> 設定。bucket 要事先建好、開版本控管、禁止公開。不建議放 Git，因為 state 是明文，而且 Git 沒有鎖定機制。</p>



<h3 class="wp-block-heading">兩個人同時 terraform apply 會怎樣？</h3>



<p class="wp-block-paragraph">用支援鎖定的 backend（例如 gcs）時，後到的人會被擋下來。實測 A 的 apply 停在等 yes 的時候，B 跑 plan 就出現 <code>Error acquiring the state lock</code> 和 <code>Error 412 ... conditionNotMet</code>，什麼都沒改。A 做完或取消後，鎖檔消失，B 就能繼續。如果 state 放在各自的本機，兩個人看到的記帳本不一樣，各改各的，雲端上的資源跟兩本帳都對不起來。</p>



<h3 class="wp-block-heading">出現 Error acquiring the state lock 怎麼辦？</h3>



<p class="wp-block-paragraph">先看錯誤訊息裡的 Lock Info：誰（Who）、什麼操作（Operation）、什麼時候（Created）。對方還在跑就等他做完。確定對方的程式已經中斷（例如被強制結束、CI 工作被取消），再用 <code>terraform force-unlock</code> 加 Lock Info 裡的 ID 解鎖。gcs backend 的 ID 是一串數字，用鎖檔 JSON 裡的英數字 ID 會失敗。</p>



<h3 class="wp-block-heading">backend 區塊可以用變數嗎？</h3>



<p class="wp-block-paragraph">不行。HashiCorp 官方文件寫明 backend 區塊不能引用變數、local 這類值，所以 bucket 名稱要直接寫死在設定檔。要讓不同環境用不同的 bucket，可以在 <code>terraform init</code> 時用 <code>-backend-config</code> 從外面帶，但不要把金鑰之類的憑證這樣傳，官方提醒它會被寫進 <code>.terraform</code> 資料夾和計畫檔。</p>



<h3 class="wp-block-heading">Terraform module 和官方 Registry 模組差在哪？</h3>



<p class="wp-block-paragraph">模組就是一包可以重複叫的 Terraform 設定。自己寫的模組放在本機資料夾，用 <code>source = "../modules/bucket"</code> 叫，適合寫公司自己的規定；Registry 模組從網路下載，例如 Google 維護的 <code>terraform-google-modules/cloud-storage/google</code>，一定要寫 <code>version</code> 鎖版本。實測這個模組的 <code>public_access_prevention</code> 預設是 <code>inherited</code>，不是禁止公開，用之前要先看預設值。</p>



<h3 class="wp-block-heading">Infrastructure Manager 要錢嗎？</h3>



<p class="wp-block-paragraph">看 Terraform 版本。用 1.5.7 以前的版本不收管理費（預設就是 1.5.7），只收底下 Cloud Build 的執行時間和 Cloud Storage 的儲存量。用 1.16.5 以後的付費版本，每個帳單帳戶每月前 500 個資源免費，超過的每個資源一年 1 美元，按秒計算；預覽不收（2026 年 12 月查官方計費頁）。</p>



<h3 class="wp-block-heading">Infrastructure Manager 可以用最新版 Terraform 嗎？</h3>



<p class="wp-block-paragraph">不行，只能用它支援的版本。2026 年 12 月 5 日在台灣區域實測，支援 1.3.10、1.4.7、1.5.7 和 1.16.5，1.2.3 已經停止支援；沒指定時預設 1.5.7。用新版語法寫的設定，搬去 Infrastructure Manager 前要先確認在 1.5.7 能不能跑。</p>



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



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


<ul class="wp-block-list">
<li><strong>terraform state 團隊用要放遠端</strong>：<code>backend "gcs"</code> 指到一個事先用 gcloud 建好、開版本控管、禁止公開的 bucket，用 <code>terraform init -migrate-state</code> 搬上去，搬完記得刪本機的 <code>.backup</code></li>

<li><strong>state lock 是保護</strong>：有人在 apply（包含停在等 yes），其他人連 plan 都會被 <code>Error 412</code> 擋下。程式被中斷留下的鎖，確認沒人在跑才 <code>force-unlock</code>，gcs 要用錯誤訊息裡的數字 ID</li>

<li><strong>版本控管救得回 state，也會留下敏感資料</strong>：實測 12 個舊版本（8 個鎖檔、4 個 state）；正式環境用生命週期規則清掉太舊的版本，刪 bucket 要加 <code>--all-versions</code></li>

<li><strong>模組讓規定只寫一次</strong>：自己寫的放公司規定、叫幾次建幾個；Registry 模組要鎖 <code>version</code>，實測 Google 的 Cloud Storage 模組預設 <code>inherited</code>，要自己改 <code>enforced</code></li>

<li><strong>Infrastructure Manager 是代管的 Terraform</strong>：用服務帳戶在 Cloud Build 跑、state 和每次紀錄它保管、設定不能寫 backend；預設 Terraform 1.5.7 免費，實測建一個資源 3 分 46 秒</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>第 7 篇：<a href="https://dongdonggcp.com/2026/11/28/what-is-devsecops-vs-secops-google-secops/">DevSecOps 是什麼？跟 SecOps、Google SecOps 差在哪</a></li>

<li>第 9 篇：<a href="https://dongdonggcp.com/2026/11/28/platform-engineering-ops-glossary-devops-sre-finops/">Ops 名詞總表：DevOps、SRE、Platform Engineering、FinOps 差在哪</a></li>

<li>第 10 篇：<a href="https://dongdonggcp.com/2026/12/05/terraform-tutorial-gcp-init-plan-apply-state/">Terraform 教學：用程式碼建 GCP 資源（init、plan、apply、state）</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>第 17 篇：<a href="https://dongdonggcp.com/2026/12/05/gcp-secret-manager-parameter-manager-cloud-kms/">Secret Manager 教學：密碼和設定怎麼管？Parameter Manager、Cloud KMS 實測</a></li>
</ul>



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


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



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


<ul class="wp-block-list">
<li>[[GKE 教學] Config Connector 是什麼東東？如何使用？](https://dongdonggcp.com/2024/12/02/gke-what-is-config-connector-and-how-to-use/)</li>

<li><a href="https://dongdonggcp.com/2024/12/02/what-is-gitops-methodolity-what-is-gitops-process/">GitOps 方法論是什麼東東？GitOps 的工作流程是什麼？</a></li>

<li><a href="https://dongdonggcp.com/2026/05/19/gcp-bill-explosion-prevention-guide/">GCP 帳單爆炸防護指南：5 個步驟讓你不再睡醒崩潰</a></li>
</ul>



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



<p class="wp-block-paragraph">state 共用、模組重用之後，下一步是讓部署跟著 Git push 自動跑，第 13 篇：<a href="https://dongdonggcp.com/2026/12/05/cloud-build-github-gitlab-trigger/">Cloud Build 串 GitHub／GitLab：push 就自動建置部署</a>會用到同一個 Cloud Build。可以看看<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": "terraform state 要放在哪裡比較好？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "一個人練習放本機就好；團隊一起用，要放在大家都拿得到、有權限控管、能加鎖的地方。在 GCP 上最常見的是 Cloud Storage，用 `backend \"gcs\"` 設定。bucket 要事先建好、開版本控管、禁止公開。不建議放 Git，因為 state 是明文，而且 Git 沒有鎖定機制。"
      }
    },
    {
      "@type": "Question",
      "name": "兩個人同時 terraform apply 會怎樣？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "用支援鎖定的 backend（例如 gcs）時，後到的人會被擋下來。實測 A 的 apply 停在等 yes 的時候，B 跑 plan 就出現 `Error acquiring the state lock` 和 `Error 412 ... conditionNotMet`，什麼都沒改。A 做完或取消後，鎖檔消失，B 就能繼續。如果 state 放在各自的本機，兩個人看到的記帳本不一樣，各改各的，雲端上的資源跟兩本帳都對不起來。"
      }
    },
    {
      "@type": "Question",
      "name": "出現 Error acquiring the state lock 怎麼辦？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "先看錯誤訊息裡的 Lock Info：誰（Who）、什麼操作（Operation）、什麼時候（Created）。對方還在跑就等他做完。確定對方的程式已經中斷（例如被強制結束、CI 工作被取消），再用 `terraform force-unlock` 加 Lock Info 裡的 ID 解鎖。gcs backend 的 ID 是一串數字，用鎖檔 JSON 裡的英數字 ID 會失敗。"
      }
    },
    {
      "@type": "Question",
      "name": "backend 區塊可以用變數嗎？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "不行。HashiCorp 官方文件寫明 backend 區塊不能引用變數、local 這類值，所以 bucket 名稱要直接寫死在設定檔。要讓不同環境用不同的 bucket，可以在 `terraform init` 時用 `-backend-config` 從外面帶，但不要把金鑰之類的憑證這樣傳，官方提醒它會被寫進 `.terraform` 資料夾和計畫檔。"
      }
    },
    {
      "@type": "Question",
      "name": "Terraform module 和官方 Registry 模組差在哪？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "模組就是一包可以重複叫的 Terraform 設定。自己寫的模組放在本機資料夾，用 `source = \"../modules/bucket\"` 叫，適合寫公司自己的規定；Registry 模組從網路下載，例如 Google 維護的 `terraform-google-modules/cloud-storage/google`，一定要寫 `version` 鎖版本。實測這個模組的 `public_access_prevention` 預設是 `inherited`，不是禁止公開，用之前要先看預設值。"
      }
    },
    {
      "@type": "Question",
      "name": "Infrastructure Manager 要錢嗎？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "看 Terraform 版本。用 1.5.7 以前的版本不收管理費（預設就是 1.5.7），只收底下 Cloud Build 的執行時間和 Cloud Storage 的儲存量。用 1.16.5 以後的付費版本，每個帳單帳戶每月前 500 個資源免費，超過的每個資源一年 1 美元，按秒計算；預覽不收（2026 年 12 月查官方計費頁）。"
      }
    },
    {
      "@type": "Question",
      "name": "Infrastructure Manager 可以用最新版 Terraform 嗎？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "不行，只能用它支援的版本。2026 年 12 月 5 日在台灣區域實測，支援 1.3.10、1.4.7、1.5.7 和 1.16.5，1.2.3 已經停止支援；沒指定時預設 1.5.7。用新版語法寫的設定，搬去 Infrastructure Manager 前要先確認在 1.5.7 能不能跑。"
      }
    }
  ]
}
</script><p>The post <a href="https://dongdonggcp.com/2026/12/05/terraform-state-gcs-modules-infrastructure-manager/">Terraform 進階：state 放 Cloud Storage、modules、Infrastructure Manager</a> first appeared on <a href="https://dongdonggcp.com">東東 GCP 教學 - GCP 實戰講師</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://dongdonggcp.com/2026/12/05/terraform-state-gcs-modules-infrastructure-manager/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Terraform 教學：用程式碼建 GCP 資源（init、plan、apply、state）</title>
		<link>https://dongdonggcp.com/2026/12/05/terraform-tutorial-gcp-init-plan-apply-state/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=terraform-tutorial-gcp-init-plan-apply-state</link>
					<comments>https://dongdonggcp.com/2026/12/05/terraform-tutorial-gcp-init-plan-apply-state/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Sat, 05 Dec 2026 01:20:11 +0000</pubDate>
				<category><![CDATA[DevOps]]></category>
		<category><![CDATA[Cloud Run]]></category>
		<category><![CDATA[Cloud Storage]]></category>
		<category><![CDATA[GCP 證照]]></category>
		<category><![CDATA[Service Account]]></category>
		<category><![CDATA[Terraform]]></category>
		<guid isPermaLink="false">https://dongdonggcp.com/?p=14200</guid>

					<description><![CDATA[<p>Terraform 教學：Cloud Shell 實測 init、plan、apply、destroy，用程式碼建 Cloud Storage、服務帳戶、Cloud Run，看懂 plan 符號、state、漂移與刪除保護，附證照考點。</p>
<p>The post <a href="https://dongdonggcp.com/2026/12/05/terraform-tutorial-gcp-init-plan-apply-state/">Terraform 教學：用程式碼建 GCP 資源（init、plan、apply、state）</a> first appeared on <a href="https://dongdonggcp.com">東東 GCP 教學 - GCP 實戰講師</a>.</p>]]></description>
										<content:encoded><![CDATA[<p class="wp-block-paragraph"><strong>Terraform 教學：用文字檔描述雲端資源，plan 預覽、apply 建立、state 記住建了什麼。</strong></p>



<p class="wp-block-paragraph">在 Google Cloud Console（GCP 的網頁管理介面）上點滑鼠建一個 bucket 只要幾個步驟，但三個月後要在另一個專案做一模一樣的環境，你多半已經忘了當初勾了哪些選項。Terraform 的做法是：把「最後要長什麼樣子」寫成文字檔，交給它去建、去改、去刪。</p>



<p class="wp-block-paragraph">我在 2026 年 12 月 5 日凌晨，用 Cloud Shell 從零做了一次：</p>


<ol class="wp-block-list">
<li>發現 <strong>Cloud Shell 從 2026 年 6 月起已經不內建 Terraform</strong>，照它自己印的指令裝好 1.17.3</li>

<li>寫 4 個檔案，用 <code>terraform apply</code> 一次建出 <strong>Cloud Storage bucket、服務帳戶、Cloud Run 服務</strong> 3 個資源</li>

<li>把 <code>terraform plan</code> 的 4 種符號（<code>+</code>、<code>~</code>、<code>-/+</code>、<code>-</code>）各實際跑出一次，包含「有人偷偷在 Console 改了設定」被 Terraform 抓到</li>

<li><code>terraform destroy</code> 第一次<strong>失敗</strong>，看懂原因再刪乾淨</li>
</ol>



<p class="wp-block-paragraph">這篇寫給想學 Terraform、想把 GCP 環境「寫成程式碼」、或正在準備 GCP DevOps 證照的人，指令都可以整段複製。這是「DevOps 證照＋Ops 名詞」系列第 10 篇，只講基礎；state 放 Cloud Storage、模組（modules）、Infrastructure Manager 留給第 11 篇。</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/do10-cards-01-terraform-workflow.png" alt="Terraform 教學四個指令：init 下載 google provider v8.12.0（135 MB），plan 預覽 3 to add，apply 打 yes 才建、實測 3 added，destroy 實測 3 destroyed；terraform.tfstate 是記帳本，3 個資源寫了 337 行" class="wp-image-14174" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do10-cards-01-terraform-workflow.png 1200w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-cards-01-terraform-workflow-300x169.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-cards-01-terraform-workflow-1024x576.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-cards-01-terraform-workflow-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>：Console 上點出來的設定（例如一個 Cloud Storage bucket，也就是雲端上放檔案的空間）沒有紀錄，換專案、換同事、出事要重建時，只能憑記憶再點一次，很容易漏掉一個勾選</li>

<li><strong>改之前看得到會發生什麼</strong>：<code>terraform plan</code> 會先列出「要新增、修改、刪除哪些東西」，不會像手動操作那樣按下去才知道後果。這篇實測把區域從台灣改成東京，plan 直接標出 bucket 會被「砍掉重建」，裡面的檔案會一起不見</li>

<li><strong>舊教學的第一步現在會卡住</strong>：Cloud Shell 以前預設就裝好 Terraform，<a href="https://docs.cloud.google.com/shell/docs/release-notes">Cloud Shell 版本資訊</a>寫明 2026 年 6 月 20 日起不再內建（2026 年 12 月查官方文件）。照「Cloud Shell 打開就能用」的教學打 <code>terraform</code>，現在只會看到一段安裝說明</li>

<li><strong>證照會考</strong>：Professional Cloud DevOps Engineer 2026 年 11 月 23 日起的新版考綱，1.2「管理基礎架構」點名 Terraform，還新增了「Terraform modules and blueprints」</li>
</ul>



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



<h2 class="wp-block-heading">先懂 4 個名詞</h2>



<h3 class="wp-block-heading">Infrastructure as Code（基礎架構即程式碼）是什麼</h3>



<p class="wp-block-paragraph"><strong>Infrastructure as Code（IaC，基礎架構即程式碼）是把伺服器、網路、儲存空間這些雲端資源，用文字檔寫下來，再交給工具照著建的做法。</strong></p>


<ul class="wp-block-list">
<li><strong>白話</strong>：不用滑鼠點，改成寫一份「清單」，工具照清單把東西建好</li>

<li><strong>生活比喻</strong>：裝潢房子時，口頭跟師傅說「這裡放櫃子、那裡裝燈」，下一間房子就得再講一次；改成畫一張設計圖，每間都照圖施工，哪裡改過也看得出來。IaC 就是那張設計圖</li>

<li><strong>來龍去脈</strong>：雲端出現之後，開一台機器只要幾秒，公司的資源從幾台變成幾百個。靠人記「當初怎麼設定的」記不住，所以業界開始把設定寫成檔案、放進 Git（版本控制工具，記錄檔案每一次修改）管理</li>

<li><strong>為什麼要學</strong>：寫成檔案之後，環境可以重複建、改動可以在合併前請同事審查（Code Review）、出事可以照檔案重建。DevOps、SRE 的工作幾乎天天碰得到</li>
</ul>



<p class="wp-block-paragraph">「基礎架構」（infrastructure）在這篇指的是程式跑起來需要的底層東西：放檔案的空間、跑程式的服務、程式用的身分，不是程式本身。</p>



<h3 class="wp-block-heading">Terraform 是什麼</h3>



<p class="wp-block-paragraph"><strong>Terraform 是 HashiCorp 公司做的 IaC 工具：你用它的語言寫下「要有哪些雲端資源」，它負責比對現況、算出要做哪些動作，再呼叫雲端的 API 去建、改、刪。</strong></p>


<ul class="wp-block-list">
<li><strong>白話</strong>：一個看得懂設計圖、會自己去跟 GCP 下單的工頭</li>

<li><strong>生活比喻</strong>：你交給工頭一張「客廳要有 1 張沙發、2 盞燈」的圖。工頭先看客廳現在有什麼，回報「要買 1 張沙發、2 盞燈」（plan），你點頭他才去買（apply）。下次你把圖改成 3 盞燈，他只會補買 1 盞，不會把整個客廳重做</li>

<li><strong>來龍去脈</strong>：Terraform 第一版 0.1 在 2014 年 7 月 28 日發布（GitHub 上的 v0.1.0 標記）。設定檔用 HashiCorp 自己設計的 <strong>HCL</strong>（HashiCorp Configuration Language，一種用大括號 <code>{}</code> 分段、<code>名稱 = 值</code> 寫設定的格式），副檔名 <code>.tf</code>。2023 年 8 月 10 日 HashiCorp <a href="https://www.hashicorp.com/en/blog/hashicorp-adopts-business-source-license">宣布</a>之後的版本從開源授權 MPL 2.0 改成 BSL 1.1（Business Source License，可以免費用，但不能拿來做跟 HashiCorp 競爭的商業服務）；社群另外分出一個開源版本 <strong>OpenTofu</strong>，<a href="https://opentofu.org/blog/opentofu-is-going-ga/">2024 年 1 月 10 日正式推出</a>。2025 年 2 月 27 日 <a href="https://newsroom.ibm.com/2025-02-27-ibm-completes-acquisition-of-hashicorp,-creates-comprehensive,-end-to-end-hybrid-cloud-platform">IBM 完成收購 HashiCorp</a></li>

<li><strong>為什麼要學</strong>：同一套寫法可以管 GCP、AWS、Azure、GitHub 和很多其他服務，學一次到處用。GCP 官方的 Terraform 範例、Infrastructure Manager（Google 代管的 Terraform 執行服務，第 11 篇講）也都用它</li>
</ul>



<p class="wp-block-paragraph">這篇實測的版本：Terraform <strong>1.17.3</strong>（2026 年 12 月 2 日發布）、GCP 的 provider <strong>8.12.0</strong>（2026 年 11 月 17 日發布），兩個都是當時的最新版（2026 年 12 月查 HashiCorp 和 Terraform Registry）。</p>



<h3 class="wp-block-heading">provider 是什麼</h3>



<p class="wp-block-paragraph"><strong>provider 是 Terraform 跟某個平台溝通的外掛程式：Terraform 本身不認識 GCP，要裝上 Google 的 provider，才知道怎麼建 bucket、Cloud Run。</strong></p>


<ul class="wp-block-list">
<li><strong>白話</strong>：翻譯官。你寫 HCL，provider 翻成 GCP 的 API 呼叫</li>

<li><strong>生活比喻</strong>：手機要裝 LINE 才能傳 LINE 訊息，要裝銀行 App 才能轉帳。Terraform 是手機，provider 是 App</li>

<li><strong>來龍去脈</strong>：HashiCorp 把「核心程式」和「各平台的知識」拆開，Google、AWS、各家廠商各自維護自己的 provider，放在 <a href="https://registry.terraform.io/">Terraform Registry</a>（provider 和模組的下載站）上</li>

<li><strong>為什麼要學</strong>：provider 有自己的版本號，大改版會換預設值。這篇會提到兩個：6.0 版起 Cloud Run 預設開「刪除保護」、7.0 版起刪資源不再順手關掉整個專案的 API。看舊教學時要先看它用的是哪一版</li>
</ul>



<h3 class="wp-block-heading">state 是什麼</h3>



<p class="wp-block-paragraph"><strong>state（狀態檔）是 Terraform 用來記住「我建了哪些東西、它們現在長怎樣」的檔案，預設叫 <code>terraform.tfstate</code>，放在你下指令的資料夾裡。</strong></p>


<ul class="wp-block-list">
<li><strong>白話</strong>：Terraform 的記帳本</li>

<li><strong>生活比喻</strong>：工頭的進貨單。沒有它，工頭走進客廳看到一張沙發，分不出是他買的、還是屋主本來就有的</li>

<li><strong>來龍去脈</strong>：雲端上的資源名稱可以重複、有些屬性要建好才知道（例如 Cloud Run 的網址），所以 Terraform 需要一個地方把「設定檔裡的名字」對應到「雲端上真正的那個資源」</li>

<li><strong>為什麼要學</strong>：state 裡是明文（沒加密的文字），HashiCorp <a href="https://developer.hashicorp.com/terraform/language/state/sensitive-data">官方文件</a>寫明它會存下設定裡的秘密值，所以<strong>不能放進 Git</strong>。一個人練習放本機就好；團隊一起用要放到大家都拿得到、又有權限控管的地方，例如 Cloud Storage，這部分在第 11 篇：<a href="https://dongdonggcp.com/2026/12/05/terraform-state-gcs-modules-infrastructure-manager/">Terraform 進階：state 放 Cloud Storage、modules、Infrastructure Manager</a></li>
</ul>



<p class="wp-block-paragraph">下面幾個名詞先看過去就好，動手做的時候會一個一個用到：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>名詞</th><th>白話</th><th>這篇的例子</th></tr></thead><tbody><tr><td>resource（資源）</td><td>一個要建的雲端東西</td><td><code>google_storage_bucket</code>、<code>google_cloud_run_v2_service</code></td></tr><tr><td>variable（變數）</td><td>可以從外面換值的欄位</td><td><code>project_id</code>、<code>region</code>、<code>env</code></td></tr><tr><td>output（輸出）</td><td>建好之後要印給你看的值</td><td>Cloud Run 的網址、bucket 名稱</td></tr><tr><td><code>terraform.tfvars</code></td><td>幫變數填值的檔案</td><td><code>project_id = "dong-dong-gcp-3"</code></td></tr><tr><td>lock 檔（<code>.terraform.lock.hcl</code>）</td><td>記下這次用的 provider 版本</td><td><code>hashicorp/google 8.12.0</code></td></tr><tr><td>漂移（drift）</td><td>雲端現況跟設定檔對不上</td><td>有人在 Console 手動改了標籤</td></tr></tbody></table></figure>



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



<h2 class="wp-block-heading">點 Console、下 gcloud、寫 Terraform 差在哪</h2>



<p class="wp-block-paragraph">gcloud 是 Google Cloud 的命令列工具，在終端機打指令操作 GCP。它是<strong>命令式</strong>（imperative）：你寫「先做這步、再做那步」。Terraform 是<strong>宣告式</strong>（declarative）：你只寫「最後要長這樣」，步驟它自己算。</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/do10-cards-03-console-gcloud-terraform.png" alt="點 Console、下 gcloud、寫 Terraform 比較：你寫的分別是沒有寫用滑鼠點、先做這步再做那步、最後要長這樣；再做一次分別要照截圖再點、自己判斷建過沒、再 plan 會顯示 No changes；有人手動改了只有 Terraform 的 plan 會列出來；全部刪掉 Terraform 用 terraform destroy" class="wp-image-14175" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do10-cards-03-console-gcloud-terraform.png 1200w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-cards-03-console-gcloud-terraform-300x169.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-cards-03-console-gcloud-terraform-1024x576.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-cards-03-console-gcloud-terraform-768x432.png 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th></th><th>點 Console</th><th>gcloud 指令</th><th>Terraform</th></tr></thead><tbody><tr><td>適合</td><td>第一次摸索、看畫面</td><td>臨時查狀態、一次性操作、排查問題</td><td>要長期維護、要重複建的環境</td></tr><tr><td>再跑一次</td><td>照截圖再點</td><td>資源已經存在要自己判斷</td><td>實測：<code>No changes</code>，什麼都不做</td></tr><tr><td>有人手動改了</td><td>不會知道</td><td>不會知道</td><td>實測：設定檔有寫的屬性，plan 列出差異、apply 改回去</td></tr><tr><td>刪乾淨</td><td>一個一個找</td><td>自己寫刪除指令</td><td><code>terraform destroy</code>，照 state 刪</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">學 Terraform 不代表不用 gcloud。這篇確認資源有沒有建出來、故意製造漂移，用的都還是 gcloud。</p>



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



<h2 class="wp-block-heading">動手做：用 Terraform 建 bucket、服務帳戶、Cloud Run</h2>



<p class="wp-block-paragraph">這段做完會有：一個 Cloud Storage bucket、一個服務帳戶、一個公開的 Cloud Run 服務，全部由 4 個 <code>.tf</code> 相關檔案描述；最後再用 Terraform 全部刪掉。</p>


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

<li><strong>花多久</strong>：我實測從安裝到刪完約 11 分鐘（裝 Terraform 不到 1 分鐘、apply 約 35 秒、destroy 約 12 秒）；第一次邊讀邊做，預留 1 小時比較從容</li>

<li><strong>事前準備</strong>：一個已連結帳單帳戶的 GCP 專案，你的帳號在專案上最簡單是擁有者（Owner）。不是 Owner 的話，要能開 API（<code>roles/serviceusage.serviceUsageAdmin</code>）、建 bucket（<code>roles/storage.admin</code>）、建服務帳戶（<code>roles/iam.serviceAccountAdmin</code>）、部署 Cloud Run（<code>roles/run.admin</code>），而且要能讓 Cloud Run 用那個服務帳戶的身分執行（<code>roles/iam.serviceAccountUser</code>）。下面的 <code>dong-dong-gcp-3</code> 要換成你的專案 ID</li>

<li><strong>會不會花錢</strong>：幾乎不會。Cloud Run 沒人連的時候會縮到 0 台（這篇沒設最小執行個體，預設是 0）、空的 bucket 不收儲存費、服務帳戶免費；Terraform CLI 本身免費下載使用。但 Cloud Run 網址是公開的，任何人都能連、連了就有請求量，做完照「用完記得刪」刪乾淨</li>

<li><strong>專案要選對</strong>：Cloud Shell 提示字元括號裡顯示的是目前的專案；不是你要用的那個，先跑 <code>gcloud config set project 你的專案ID</code></li>

<li><strong>中途斷線</strong>：Cloud Shell 重新連線後，先打 <code>cd ~/do-10</code> 回到練習資料夾。如果閒置超過 40 分鐘、機器被收掉，步驟 2 的安裝要再做一次；<code>~/do-10</code> 在家目錄裡，檔案和 state 都還在</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> 圖示（紅框）。第一次用的完整步驟在<a href="https://dongdonggcp.com/2026/11/28/gcp-devops-certification-guide/">第 1 篇</a>。</p>



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



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



<h3 class="wp-block-heading">步驟 1：確認 Cloud Shell 有沒有 Terraform</h3>



<p class="wp-block-paragraph">先建一個練習用的資料夾，再問 Terraform 的版本。預期會看到一段安裝說明，不是你做錯：</p>



<pre class="wp-block-code"><code>mkdir -p ~/do-10 &amp;&amp; cd ~/do-10
terraform version</code></pre>



<pre class="wp-block-code"><code>  Follow the instructions at https://developer.hashicorp.com/terraform/install to install terraform, or run the commands below:

  wget -O - https://apt.releases.hashicorp.com/gpg | sudo gpg --dearmor -o /usr/share/keyrings/hashicorp-archive-keyring.gpg
  echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/hashicorp-archive-keyring.gpg] https://apt.releases.hashicorp.com $(grep -oP '(?&lt;=UBUNTU_CODENAME=).*' /etc/os-release || lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/hashicorp.list
  sudo apt update &amp;&amp; sudo apt install terraform
  bash

  To persist the installation between sessions, either add the above commands to $HOME/.customize_environment, or install the terraform binary in your home directory.</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/do10-shots-01-terraform-not-installed.png" alt="在 Cloud Shell 執行 terraform version，沒有印出版本號，只印出安裝說明：Terraform 已經不是 Cloud Shell 內建工具，要自己用 apt 安裝" class="wp-image-14177" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-01-terraform-not-installed.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-01-terraform-not-installed-300x52.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-01-terraform-not-installed-1024x179.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-01-terraform-not-installed-768x134.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-01-terraform-not-installed-1536x268.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph">沒有版本號，只有一段安裝說明。Cloud Shell 裡的 <code>terraform</code> 現在是一個只會印這段字的小腳本（實測放在 <code>/google/bin/terraform</code>）。這就是 2026 年 6 月 20 日那則版本資訊說的「不再內建」。</p>



<p class="wp-block-paragraph">最後一句的意思是：<strong>照這樣裝，Cloud Shell 重開就不見了</strong>。官方文件寫明 Cloud Shell 閒置 40 分鐘就會被收掉，家目錄以外的修改都會消失，下次開的是一台新機器（<a href="https://docs.cloud.google.com/shell/docs/quotas-limits">配額與限制</a>也寫 40 分鐘）；只有家目錄（5 GB）會跨工作階段保存，但 <strong>120 天沒開 Cloud Shell，家目錄會被自動刪除、救不回來</strong>（刪除前會寄信通知，2026 年 12 月查<a href="https://docs.cloud.google.com/shell/docs/how-cloud-shell-works">官方文件</a>）。</p>



<h3 class="wp-block-heading">步驟 2：照 Cloud Shell 印的指令安裝 Terraform</h3>



<p class="wp-block-paragraph">這 3 行是從步驟 1 那段安裝說明照抄的（<code>apt install</code> 我多加了 <code>-y</code>，不用再按一次 Y）。<code>apt</code> 是 Ubuntu（Cloud Shell 用的 Linux 版本）安裝軟體的工具。第 1 行下載 HashiCorp 的簽章金鑰，第 2 行把 HashiCorp 的軟體來源加進系統，第 3 行更新清單並安裝。<code>sudo</code> 是用管理員權限執行，Cloud Shell 不用輸入密碼。這 3 行看不懂沒關係，整段貼上就好，重點是最後出現 <code>Setting up terraform (1.17.3-1)</code>：</p>



<pre class="wp-block-code"><code>wget -O - https://apt.releases.hashicorp.com/gpg | sudo gpg --dearmor -o /usr/share/keyrings/hashicorp-archive-keyring.gpg
echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/hashicorp-archive-keyring.gpg] https://apt.releases.hashicorp.com $(grep -oP '(?&lt;=UBUNTU_CODENAME=).*' /etc/os-release || lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/hashicorp.list
sudo apt update &amp;&amp; sudo apt install -y terraform</code></pre>



<pre class="wp-block-code"><code>deb [arch=amd64 signed-by=/usr/share/keyrings/hashicorp-archive-keyring.gpg] https://apt.releases.hashicorp.com noble main
Get:1 https://apt.releases.hashicorp.com noble InRelease [12.8 kB]
Get:2 https://apt.releases.hashicorp.com noble/main amd64 Packages [295 kB]
（中間省略）
Fetched 15.0 MB in 17s (890 kB/s)
（中間省略）
The following NEW packages will be installed:
  terraform
0 upgraded, 1 newly installed, 0 to remove and 47 not upgraded.
Need to get 37.7 MB of archives.
After this operation, 130 MB of additional disk space will be used.
Get:1 https://apt.releases.hashicorp.com noble/main amd64 terraform amd64 1.17.3-1 [37.7 MB]
Fetched 37.7 MB in 1s (50.1 MB/s)
（中間省略）
Setting up terraform (1.17.3-1) ...</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="1323" src="https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-02-install-terraform.png" alt="照 Cloud Shell 印的三行指令安裝 Terraform：加入 HashiCorp 的 apt 來源、apt update，最後裝好 terraform 1.17.3-1，下載 37.7 MB、安裝後佔 130 MB" class="wp-image-14178" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-02-install-terraform.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-02-install-terraform-300x248.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-02-install-terraform-1024x847.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-02-install-terraform-768x635.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-02-install-terraform-1536x1270.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph">再看一次版本。<code>hash -r</code> 是請終端機忘掉之前記住的舊 <code>terraform</code> 位置，改找新裝的那個：</p>



<pre class="wp-block-code"><code>hash -r; terraform version</code></pre>



<pre class="wp-block-code"><code>Terraform v1.17.3
on linux_amd64</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="964" height="245" src="https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-03-terraform-version.png" alt="hash -r 之後再跑 terraform version，顯示 Terraform v1.17.3 on linux_amd64，安裝成功" class="wp-image-14179" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-03-terraform-version.png 964w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-03-terraform-version-300x76.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-03-terraform-version-768x195.png 768w" sizes="(max-width: 964px) 100vw, 964px" /></figure>



<p class="wp-block-paragraph"><strong>想要重開 Cloud Shell 也還在</strong>：照說明最後一句，把這 3 行寫進家目錄的 <code>~/.customize_environment</code>（Cloud Shell 每次開機會用管理員權限跑一次，<a href="https://docs.cloud.google.com/shell/docs/configuring-cloud-shell">官方說明</a>），或把 Terraform 的執行檔放進家目錄。我的 Cloud Shell 家目錄 <code>~/bin</code> 裡就留著之前放的 1.17.2，只要 120 天內有開過 Cloud Shell 就一直在；這次為了讓畫面跟新帳號一樣，示範時先把它排除。</p>



<h3 class="wp-block-heading">步驟 3：確認要用的 API 已經開啟</h3>



<p class="wp-block-paragraph">API（服務對外的操作介面）要先「啟用」，Terraform 才能呼叫。這篇用到 Cloud Run、IAM（身分與權限管理）、Cloud Storage 三個：</p>



<pre class="wp-block-code"><code>gcloud services enable run.googleapis.com iam.googleapis.com storage.googleapis.com</code></pre>



<pre class="wp-block-code"><code>Operation "operations/acat.p2-600195576280-aad4db33-62ee-4650-af4e-459f9f15143a" finished successfully.</code></pre>



<p class="wp-block-paragraph">出現 <code>finished successfully</code> 就是開好了。</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph"><strong>為什麼不用 Terraform 開 API？</strong> 可以，用 <code>google_project_service</code> 這個資源。但舊版 provider（6.x 以前）刪掉這個資源時，預設會<strong>把整個專案的那支 API 關掉</strong>，連別人用到的服務都會壞。<a href="https://registry.terraform.io/providers/hashicorp/google/latest/docs/guides/version_7_upgrade">7.0 版升級指南</a>已經把這個預設拿掉（2026 年 12 月查官方文件）。初學練習建議先用 gcloud 開，資源跟 API 分開管。</p>
</blockquote>



<h3 class="wp-block-heading">步驟 4：寫 4 個檔案</h3>



<p class="wp-block-paragraph">Terraform 會讀資料夾裡<strong>所有</strong> <code>.tf</code> 檔，合在一起看，檔名怎麼取都可以。業界習慣分成：<code>main.tf</code> 放資源、<code>variables.tf</code> 放變數、<code>outputs.tf</code> 放輸出、<code>terraform.tfvars</code> 填變數的值。</p>



<p class="wp-block-paragraph">下面用 <code>cat &gt; 檔名 &lt;&lt;'EOF' ... EOF</code> 這種寫法建檔：中間那段文字會原封不動寫進檔案。不想用這招，也可以點 Cloud Shell 上方的「開啟編輯器」，在網頁版編輯器裡開檔、把內容貼進去。</p>



<p class="wp-block-paragraph"><strong>main.tf</strong>：最重要的檔案，分三段。</p>



<pre class="wp-block-code"><code>cat &gt; main.tf &lt;&lt;'EOF'
terraform {
  required_providers {
    google = {
      source  = "hashicorp/google"
      version = "~&gt; 8.0"
    }
  }
}

provider "google" {
  project = var.project_id
  region  = var.region
}

# 1. Cloud Storage bucket：放檔案的空間
resource "google_storage_bucket" "files" {
  name                        = "do-10-${var.project_id}-files"
  location                    = var.region
  uniform_bucket_level_access = true
  public_access_prevention    = "enforced"

  labels = {
    env        = var.env
    managed-by = "terraform"
  }
}

# 2. 服務帳戶：給 Cloud Run 用的身分
resource "google_service_account" "run" {
  account_id   = "do-10-run"
  display_name = "do-10 Cloud Run runtime"
}

# 3. Cloud Run 服務：跑 Google 的範例容器
resource "google_cloud_run_v2_service" "hello" {
  name                 = "do-10-hello"
  location             = var.region
  invoker_iam_disabled = true

  labels = {
    env        = var.env
    managed-by = "terraform"
  }

  template {
    service_account = google_service_account.run.email
    containers {
      image = "us-docker.pkg.dev/cloudrun/container/hello"
    }
  }
}
EOF</code></pre>



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


<ul class="wp-block-list">
<li><strong><code>terraform { required_providers {...} }</code></strong>：宣告要用哪個 provider。<code>source = "hashicorp/google"</code> 是 Registry 上的名字；<code>version = "~&gt; 8.0"</code> 的意思是「8.0 以上、9.0 以下都可以」（<a href="https://developer.hashicorp.com/terraform/language/expressions/version-constraints">官方說明</a>），大改版的 9.0 出來不會自動換過去</li>

<li><strong><code>provider "google" {...}</code></strong>：設定這個 provider 預設用哪個專案、哪個區域。值從變數來（<code>var.變數名</code>）。這裡<strong>沒有寫任何金鑰</strong>：Terraform 是借你目前登入的身分去跟 GCP 下單，所以你的帳號要有建立這些資源的權限。在 Cloud Shell 裡你已經登入了，不用另外設定。這個「自動找目前登入身分」的機制，官方叫應用程式預設憑證（Application Default Credentials，ADC）；在自己的電腦上要先裝好 gcloud（Google Cloud CLI），跑 <code>gcloud auth application-default login</code> 登入一次，之後 Terraform 就用你的身分做事</li>

<li><strong><code>resource "類型" "名字" {...}</code></strong>：一個要建的資源。<code>"google_storage_bucket"</code> 是類型（provider 規定的）、<code>"files"</code> 是你在 Terraform 裡給它取的小名，兩個合起來 <code>google_storage_bucket.files</code> 就是它在 Terraform 裡的地址</li>

<li><strong>bucket</strong>：Cloud Storage 裡放檔案的容器，名稱全世界不能重複，所以用 <code>"do-10-${var.project_id}-files"</code> 把專案 ID 拼進去（<code>${...}</code> 是把變數塞進字串裡）。<code>uniform_bucket_level_access</code> 是統一用 IAM 管權限、<code>public_access_prevention = "enforced"</code> 是禁止公開，兩個都是 Google 建議的安全設定。<code>labels</code> 是標籤（貼在資源上的「鍵＝值」小紙條，方便分類和看帳單）</li>

<li><strong>服務帳戶</strong>（service account）：給程式用的帳號，不是給人登入的。這裡建一個給 Cloud Run 用，讓服務不要用到預設那個權限很大的帳戶</li>

<li><strong>Cloud Run 服務</strong>：Google 代管、跑容器的服務（容器是把程式和它需要的環境打包在一起的執行單位）。<code>image</code> 用 Google 官方的範例映像檔，打開網址會看到一頁「Congratulations」。<code>invoker_iam_disabled = true</code> 等於 gcloud 的 <code>--no-invoker-iam-check</code>：不檢查呼叫者身分，誰都能打開網址。公司或學校的帳號可能有組織政策禁止公開服務，apply 這一行會失敗；個人帳號比較不會遇到</li>

<li><strong><code>service_account = google_service_account.run.email</code></strong>：這行是重點。Cloud Run 要用「<code>google_service_account.run</code> 這個服務帳戶的 email」，Terraform 看到這個引用，就知道<strong>要先建好服務帳戶、才能建 Cloud Run</strong>，順序不用你排</li>
</ul>



<p class="wp-block-paragraph"><strong>variables.tf</strong>：宣告 3 個變數。<code>project_id</code> 沒有預設值，一定要有人給；<code>region</code>、<code>env</code> 有預設值，不給就用預設。</p>



<pre class="wp-block-code"><code>cat &gt; variables.tf &lt;&lt;'EOF'
variable "project_id" {
  description = "要建立資源的 GCP 專案 ID"
  type        = string
}

variable "region" {
  description = "資源放在哪個區域"
  type        = string
  default     = "asia-east1"
}

variable "env" {
  description = "環境名稱，會變成標籤"
  type        = string
  default     = "dev"
}
EOF</code></pre>



<p class="wp-block-paragraph"><strong>outputs.tf</strong>：建好之後要印出來的 3 個值。Cloud Run 的網址要建好才知道，寫在 output 裡就不用再去 Console 找。</p>



<pre class="wp-block-code"><code>cat &gt; outputs.tf &lt;&lt;'EOF'
output "bucket_name" {
  value = google_storage_bucket.files.name
}

output "service_account_email" {
  value = google_service_account.run.email
}

output "service_url" {
  value = google_cloud_run_v2_service.hello.uri
}
EOF</code></pre>



<p class="wp-block-paragraph"><strong>terraform.tfvars</strong>：幫變數填值。Terraform 會自動讀這個檔名。你的專案 ID 不一樣，改這一行就好，其他檔案都不用動。</p>



<pre class="wp-block-code"><code>cat &gt; terraform.tfvars &lt;&lt;'EOF'
project_id = "dong-dong-gcp-3"
EOF
ls</code></pre>



<pre class="wp-block-code"><code>main.tf  outputs.tf  terraform.tfvars  variables.tf</code></pre>



<h3 class="wp-block-heading">步驟 5：terraform init，下載 provider</h3>



<p class="wp-block-paragraph"><strong><code>terraform init</code> 是每個新資料夾第一個要跑的指令：照 <code>required_providers</code> 下載 provider、建立 lock 檔。</strong> 換電腦、換資料夾、改了 provider 版本，都要重跑一次。</p>



<pre class="wp-block-code"><code>terraform init</code></pre>



<pre class="wp-block-code"><code>Initializing the backend...

Initializing provider plugins...
- Finding hashicorp/google versions matching "~&gt; 8.0"...
- Installing hashicorp/google v8.12.0...
- Installed hashicorp/google v8.12.0 (signed by HashiCorp)

Terraform has created a lock file .terraform.lock.hcl to record the provider
selections it made above. Include this file in your version control repository
so that Terraform can guarantee to make the same selections by default when
you run "terraform init" in the future.

Terraform has been successfully initialized!
（後面省略）</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1409" height="857" src="https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-05-init.png" alt="terraform init 的輸出：找到符合 ~&gt; 8.0 的 hashicorp/google，安裝 v8.12.0（HashiCorp 簽章），建立 .terraform.lock.hcl，最後顯示 Terraform has been successfully initialized" class="wp-image-14180" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-05-init.png 1409w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-05-init-300x182.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-05-init-1024x623.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-05-init-768x467.png 768w" sizes="(max-width: 1409px) 100vw, 1409px" /></figure>


<ul class="wp-block-list">
<li><code>"~&gt; 8.0"</code> 挑到當時最新的 <strong>8.12.0</strong></li>

<li>第一行 <code>Initializing the backend</code> 的 backend 是「state 檔放哪裡」。沒設定就是預設的本機資料夾，第 11 篇會改成 Cloud Storage</li>

<li>init 會產生 <code>.terraform.lock.hcl</code>，輸出建議把這個檔案放進 Git：同事 clone 下來跑 init，就會裝到一模一樣的 8.12.0，不會「我這邊可以、你那邊壞掉」</li>
</ul>



<h3 class="wp-block-heading">步驟 6：看看多了什麼，再檢查格式和語法</h3>



<pre class="wp-block-code"><code>ls -a; du -sh .terraform; terraform fmt; terraform validate</code></pre>



<pre class="wp-block-code"><code>.  ..  main.tf  outputs.tf  .terraform  .terraform.lock.hcl  terraform.tfvars  variables.tf
135M    .terraform
Success! The configuration is valid.</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="276" src="https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-06-fmt-validate.png" alt="ls -a 看到多了 .terraform 資料夾和 .terraform.lock.hcl，du 顯示 .terraform 佔 135M；terraform validate 回 Success! The configuration is valid" class="wp-image-14181" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-06-fmt-validate.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-06-fmt-validate-300x52.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-06-fmt-validate-1024x177.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-06-fmt-validate-768x132.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-06-fmt-validate-1536x265.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>


<ul class="wp-block-list">
<li><strong>4 個指令一次跑，輸出怎麼對</strong>：第 1 行是 <code>ls -a</code> 的結果（連名稱以 <code>.</code> 開頭的隱藏檔都列出來），第 2 行是 <code>du -sh</code>（看資料夾佔多少空間），<code>terraform fmt</code> 沒有印東西是正常的，最後一行是 <code>terraform validate</code></li>

<li><strong><code>.terraform</code> 資料夾 135 MB</strong>：裡面就是剛下載的 provider 程式。算一次：Cloud Shell 家目錄 5 GB ≈ 5,120 MB，一個資料夾 135 MB 約佔 2.6%；開 10 個練習資料夾各自 init，就吃掉約 1.3 GB。這個資料夾不用放進 Git，要用時 init 會重新下載</li>

<li><strong><code>terraform fmt</code></strong>：把縮排、等號對齊整理成官方格式。檔案本來就整齊時什麼都不印（這次就是）；有改的話會印出改了哪個檔</li>

<li><strong><code>terraform validate</code></strong>：檢查語法和欄位有沒有寫錯，不會連到 GCP</li>
</ul>



<h3 class="wp-block-heading">步驟 7：terraform plan，先預覽</h3>



<p class="wp-block-paragraph"><strong><code>terraform plan</code> 是「預演」：讀設定檔、讀 state、問 GCP 現況，三邊比對後列出要做的事，但完全不動手。</strong></p>



<pre class="wp-block-code"><code>terraform plan</code></pre>



<pre class="wp-block-code"><code>Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
  + create

Terraform will perform the following actions:

  # google_cloud_run_v2_service.hello will be created
  + resource "google_cloud_run_v2_service" "hello" {
      + conditions              = (known after apply)
（中間省略）
      + deletion_protection     = true
      + effective_annotations   = (known after apply)
      + effective_labels        = {
          + "env"                        = "dev"
          + "goog-terraform-provisioned" = "true"
          + "managed-by"                 = "terraform"
        }
（中間省略）
      + invoker_iam_disabled    = true
      + labels                  = {
          + "env"        = "dev"
          + "managed-by" = "terraform"
        }
（中間省略）
      + location                = "asia-east1"
      + name                    = "do-10-hello"
（中間省略）
      + uri                     = (known after apply)
（中間省略）
  # google_service_account.run will be created
  + resource "google_service_account" "run" {
      + account_id      = "do-10-run"
（中間省略）
      + email           = "do-10-run@dong-dong-gcp-3.iam.gserviceaccount.com"
（中間省略）
  # google_storage_bucket.files will be created
  + resource "google_storage_bucket" "files" {
（中間省略）
      + force_destroy               = false
（中間省略）
      + location                    = "ASIA-EAST1"
      + name                        = "do-10-dong-dong-gcp-3-files"
（中間省略）
      + public_access_prevention    = "enforced"
（中間省略）
Plan: 3 to add, 0 to change, 0 to destroy.

Changes to Outputs:
  + bucket_name           = "do-10-dong-dong-gcp-3-files"
  + service_account_email = "do-10-run@dong-dong-gcp-3.iam.gserviceaccount.com"
  + service_url           = (known after apply)

（分隔線省略）

Note: You didn't use the -out option to save this plan, so Terraform can't guarantee to take exactly these actions if you run "terraform apply" now.</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="983" src="https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-07-plan.png" alt="terraform plan 輸出的最後一段：bucket 的屬性前面都是綠色加號，最後一行 Plan: 3 to add, 0 to change, 0 to destroy，Changes to Outputs 列出 bucket 名稱、服務帳戶 email，service_url 是 known after apply" class="wp-image-14182" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-07-plan.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-07-plan-300x184.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-07-plan-1024x629.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-07-plan-768x472.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-07-plan-1536x944.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph">怎麼讀：</p>


<ul class="wp-block-list">
<li><strong><code>+ create</code></strong>：最上面的符號說明。這次 3 個資源都是 <code>+</code>，全部新增</li>

<li><strong><code>Plan: 3 to add, 0 to change, 0 to destroy.</code></strong>：最重要的一行，apply 前一定要看。數字跟你預期的不一樣，就停下來</li>

<li><strong><code>(known after apply)</code></strong>：建好才知道的值，例如 Cloud Run 的網址 <code>uri</code></li>

<li><strong><code>goog-terraform-provisioned = "true"</code></strong>：我沒寫這個標籤，是 provider 自動加的。<a href="https://registry.terraform.io/providers/hashicorp/google/latest/docs/guides/provider_reference">官方說明</a>：6.0 版起預設幫新資源加上它，方便在 Console、gcloud 認出「這是 Terraform 建的」。你寫的 <code>labels</code> 只有 2 個，<code>effective_labels</code>（實際會貼在資源上的）有 3 個</li>

<li><strong><code>deletion_protection = true</code></strong>：我也沒寫這行。先記住它，「用完記得刪」那段會被它擋下來</li>
</ul>



<p class="wp-block-paragraph">輸出最後還有一行提醒：沒用 <code>-out</code> 存下這份計畫，之後 apply 時 Terraform 會重新算一次，不保證跟現在一模一樣。一個人練習沒關係；CI/CD 自動化時，常見做法是 <code>terraform plan -out=tfplan</code> 存檔、審過再 <code>terraform apply tfplan</code>。</p>



<h3 class="wp-block-heading">步驟 8：terraform apply，真的建出來</h3>



<p class="wp-block-paragraph"><strong><code>terraform apply</code> 會先再算一次 plan、印出來，等你打 <code>yes</code> 才動手。</strong>打別的字（包括 <code>y</code>）都會取消。</p>



<p class="wp-block-paragraph">apply 的工作是「讓雲端變得跟設定檔一樣」：設定檔寫了、雲端沒有的就建，設定檔還寫著的東西就算被刪掉，下次 apply 也會補回來。這點在步驟 17 會實際撞到一次。</p>



<pre class="wp-block-code"><code>terraform apply</code></pre>



<pre class="wp-block-code"><code>（前面跟 plan 一樣，省略）
Plan: 3 to add, 0 to change, 0 to destroy.

Changes to Outputs:
  + bucket_name           = "do-10-dong-dong-gcp-3-files"
  + service_account_email = "do-10-run@dong-dong-gcp-3.iam.gserviceaccount.com"
  + service_url           = (known after apply)

Do you want to perform these actions?
  Terraform will perform the actions described above.
  Only 'yes' will be accepted to approve.

  Enter a value:</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="983" src="https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-08-apply-confirm.png" alt="terraform apply 印完計畫後停在 Do you want to perform these actions? Only &#x27;yes&#x27; will be accepted to approve. Enter a value:，等使用者輸入 yes" class="wp-image-14183" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-08-apply-confirm.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-08-apply-confirm-300x184.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-08-apply-confirm-1024x629.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-08-apply-confirm-768x472.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-08-apply-confirm-1536x944.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph">打 <code>yes</code>、按 Enter：</p>



<pre class="wp-block-code"><code>  Enter a value: yes

google_service_account.run: Creating...
google_storage_bucket.files: Creating...
google_storage_bucket.files: Creation complete after 2s [id=do-10-dong-dong-gcp-3-files]
google_service_account.run: Still creating... [00m10s elapsed]
google_service_account.run: Still creating... [00m20s elapsed]
google_service_account.run: Creation complete after 23s [id=projects/dong-dong-gcp-3/serviceAccounts/do-10-run@dong-dong-gcp-3.iam.gserviceaccount.com]
google_cloud_run_v2_service.hello: Creating...
google_cloud_run_v2_service.hello: Still creating... [00m10s elapsed]
google_cloud_run_v2_service.hello: Creation complete after 11s [id=projects/dong-dong-gcp-3/locations/asia-east1/services/do-10-hello]

Apply complete! Resources: 3 added, 0 changed, 0 destroyed.

Outputs:

bucket_name = "do-10-dong-dong-gcp-3-files"
service_account_email = "do-10-run@dong-dong-gcp-3.iam.gserviceaccount.com"
service_url = "https://do-10-hello-b5j2wtbgca-de.a.run.app"</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="983" src="https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-09-apply-complete.png" alt="輸入 yes 後的建立過程：bucket 2 秒建好，服務帳戶 23 秒，服務帳戶好了 Cloud Run 才開始建、11 秒完成，最後 Apply complete! Resources: 3 added，並印出 3 個 outputs" class="wp-image-14184" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-09-apply-complete.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-09-apply-complete-300x184.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-09-apply-complete-1024x629.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-09-apply-complete-768x472.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-09-apply-complete-1536x944.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph">看建立順序：</p>


<ul class="wp-block-list">
<li><strong>bucket 和服務帳戶同時開始</strong>：兩個互不相干，Terraform 會平行建</li>

<li><strong>Cloud Run 等服務帳戶建好才開始</strong>：因為 <code>main.tf</code> 寫了 <code>service_account = google_service_account.run.email</code>，Terraform 自己排出先後。這叫<strong>隱含相依</strong>（implicit dependency）</li>

<li>算一次總時間：服務帳戶 23 秒＋Cloud Run 11 秒 ≈ 34 秒；bucket 的 2 秒跟服務帳戶重疊，不用加。資源越多、相依越長，平行的好處越明顯</li>
</ul>



<h3 class="wp-block-heading">步驟 9：用 output 拿網址，打開看看</h3>



<pre class="wp-block-code"><code>terraform output; curl -s "$(terraform output -raw service_url)" | grep -o '&lt;title&gt;.*&lt;/title&gt;'</code></pre>



<pre class="wp-block-code"><code>bucket_name = "do-10-dong-dong-gcp-3-files"
service_account_email = "do-10-run@dong-dong-gcp-3.iam.gserviceaccount.com"
service_url = "https://do-10-hello-b5j2wtbgca-de.a.run.app"
&lt;title&gt;Congratulations | Cloud Run&lt;/title&gt;</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="210" src="https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-10-output-curl.png" alt="terraform output 列出三個輸出值，再用 curl 打開 service_url，抓到網頁標題 Congratulations，是 Cloud Run 範例頁，服務已經可以公開連線" class="wp-image-14185" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-10-output-curl.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-10-output-curl-300x39.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-10-output-curl-1024x134.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-10-output-curl-768x101.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-10-output-curl-1536x202.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph"><code>terraform output -raw service_url</code> 只印出網址本身（不加引號），方便塞進其他指令。<code>curl</code> 是在終端機開網頁的工具，抓到標題「Congratulations | Cloud Run」，代表服務真的跑起來、而且不用登入就能看。</p>



<p class="wp-block-paragraph">到 Console 的 Cloud Run 頁面看，<code>do-10-hello</code> 就在那裡，跟手動建的服務長得一模一樣。網址欄顯示的是 <code>https://do-10-hello-600195576280.asia-east1.run.app</code>（服務名稱＋專案編號＋區域），跟 Terraform 印的 <code>...-b5j2wtbgca-de.a.run.app</code> 不一樣：Cloud Run 的服務有新、舊兩種網址，Console 顯示新式的，provider 的 <code>uri</code> 欄位給的是舊式的。步驟 9 的 curl 測的是舊式那個：</p>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="816" src="https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-c1-console-cloud-run-created-by-terraform.png" alt="Google Cloud Console 的 Cloud Run 服務詳細資料頁：服務 do-10-hello 綠色勾勾、地區 asia-east1，修訂版本 do-10-hello-00001-8sx 拿 100% 流量，映像檔是 us-docker.pkg.dev/cloudrun/container/hello" class="wp-image-14186" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-c1-console-cloud-run-created-by-terraform.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-c1-console-cloud-run-created-by-terraform-300x153.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-c1-console-cloud-run-created-by-terraform-1024x522.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-c1-console-cloud-run-created-by-terraform-768x392.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-c1-console-cloud-run-created-by-terraform-1536x783.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<h3 class="wp-block-heading">步驟 10：用 gcloud 確認，順便看標籤</h3>



<pre class="wp-block-code"><code>gcloud run services describe do-10-hello --region=asia-east1 --format='value(metadata.labels)'; gcloud storage buckets describe gs://do-10-dong-dong-gcp-3-files --format='value(labels)'; gcloud iam service-accounts list --filter='email~^do-10-' --format='value(email)'</code></pre>



<pre class="wp-block-code"><code>cloud.googleapis.com/location=asia-east1;env=dev;goog-terraform-provisioned=true;managed-by=terraform
env=dev;goog-terraform-provisioned=true;managed-by=terraform
do-10-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="150" src="https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-11-gcloud-verify.png" alt="用 gcloud 查 Cloud Run 和 bucket 的標籤，兩個都有 env=dev、goog-terraform-provisioned=true、managed-by=terraform；服務帳戶 do-10-run 也查得到" class="wp-image-14187" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-11-gcloud-verify.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-11-gcloud-verify-300x28.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-11-gcloud-verify-1024x96.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-11-gcloud-verify-768x72.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-11-gcloud-verify-1536x144.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph">3 個資源都在。<code>goog-terraform-provisioned=true</code> 真的貼上去了，之後在帳單報表、資源清單裡，用這個標籤就能篩出「哪些是 Terraform 管的」。</p>



<h3 class="wp-block-heading">步驟 11：看 state 記了什麼</h3>



<pre class="wp-block-code"><code>terraform state list; head -8 terraform.tfstate; grep -o '"creator": "[^"]*"' terraform.tfstate | sed -E 's/[a-z0-9.]+@gmail[.]com/你的帳號/'</code></pre>



<pre class="wp-block-code"><code>google_cloud_run_v2_service.hello
google_service_account.run
google_storage_bucket.files
{
  "version": 4,
  "terraform_version": "1.17.3",
  "serial": 4,
  "lineage": "a1fec9c5-72ee-23d0-f15a-44987346aedd",
  "outputs": {
    "bucket_name": {
      "value": "do-10-dong-dong-gcp-3-files",
"creator": "你的帳號"</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="301" src="https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-12-state.png" alt="terraform state list 列出 3 個資源地址；head 看 terraform.tfstate 開頭是 JSON，有 version 4、terraform_version 1.17.3、serial 4、lineage；grep 找到 creator 欄位存著建立者帳號（截圖裡已遮成你的帳號）" class="wp-image-14188" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-12-state.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-12-state-300x56.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-12-state-1024x193.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-12-state-768x144.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-12-state-1536x289.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>


<ul class="wp-block-list">
<li><strong><code>terraform state list</code></strong>：state 裡記了 3 個資源，名字就是 <code>main.tf</code> 裡的「類型.小名」</li>

<li><strong><code>terraform.tfstate</code> 是 JSON</strong>（一種用大括號和「&#8221;名稱&#8221;: 值」記資料的文字格式）。<code>serial</code> 是改版次數，每次 apply 改到 state 就加 1；<code>lineage</code> 是這份 state 的身分證號碼，防止拿錯檔案</li>

<li><strong>state 存了你的帳號</strong>：Cloud Run 的 <code>creator</code> 欄位原原本本寫著建立者的 email（最後那個 <code>sed</code> 只是把畫面上的 email 換成「你的帳號」，檔案裡是真的 email）。這就是不能把 state 放進 Git 的原因之一；如果資源裡有資料庫密碼，也會一起寫進來</li>

<li>只有 3 個資源，這個檔案就有 <strong>337 行</strong>（步驟 12 用 <code>wc -l</code> 數行數量的）</li>
</ul>



<h3 class="wp-block-heading">步驟 12：再跑一次 plan，什麼都不會做</h3>



<pre class="wp-block-code"><code>wc -l terraform.tfstate; terraform plan</code></pre>



<pre class="wp-block-code"><code>337 terraform.tfstate
google_service_account.run: Refreshing state... [id=projects/dong-dong-gcp-3/serviceAccounts/do-10-run@dong-dong-gcp-3.iam.gserviceaccount.com]
google_storage_bucket.files: Refreshing state... [id=do-10-dong-dong-gcp-3-files]
google_cloud_run_v2_service.hello: Refreshing state... [id=projects/dong-dong-gcp-3/locations/asia-east1/services/do-10-hello]

No changes. Your infrastructure matches the configuration.

Terraform has compared your real infrastructure against your configuration and found no differences, so no changes are needed.</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="266" src="https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-13-plan-no-changes.png" alt="再跑一次 terraform plan：先 Refreshing state 向 GCP 查 3 個資源的現況，結果 No changes. Your infrastructure matches the configuration" class="wp-image-14189" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-13-plan-no-changes.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-13-plan-no-changes-300x50.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-13-plan-no-changes-1024x170.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-13-plan-no-changes-768x128.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-13-plan-no-changes-1536x255.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph"><code>Refreshing state</code> 是 Terraform 去 GCP 問每個資源現在長怎樣。設定檔、state、雲端三邊一致，就是 <code>No changes</code>。這個「同樣的設定跑幾次結果都一樣」的特性叫<strong>冪等</strong>（idempotent），是 IaC 很重要的性質之一：你可以放心每天跑 plan，沒事它就不動。前提是沒人在外面改過設定，而且 provider 版本被 lock 檔鎖住，不會自己換新版、換預設值。</p>



<h3 class="wp-block-heading">步驟 13：換一個變數值，看 <code>~</code> 原地修改</h3>



<p class="wp-block-paragraph">不改檔案，用 <code>-var</code> 臨時把 <code>env</code> 換成 <code>test</code>：</p>



<pre class="wp-block-code"><code>terraform plan -var="env=test"</code></pre>



<pre class="wp-block-code"><code>（Refreshing state 3 行省略）
Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
  ~ update in-place

Terraform will perform the following actions:

  # google_cloud_run_v2_service.hello will be updated in-place
  ~ resource "google_cloud_run_v2_service" "hello" {
（中間省略）
      ~ labels                  = {
          ~ "env"        = "dev" -&gt; "test"
            # (1 unchanged element hidden)
        }
        name                    = "do-10-hello"
（中間省略）
  # google_storage_bucket.files will be updated in-place
  ~ resource "google_storage_bucket" "files" {
（中間省略）
      ~ labels                      = {
          ~ "env"        = "dev" -&gt; "test"
            # (1 unchanged element hidden)
        }
（中間省略）
Plan: 0 to add, 2 to change, 0 to destroy.</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="983" src="https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-14-plan-var-env-test.png" alt="terraform plan -var=&quot;env=test&quot;：Cloud Run 和 bucket 都標 will be updated in-place，labels 裡 env 從 dev 改成 test，最後 Plan: 0 to add, 2 to change, 0 to destroy" class="wp-image-14190" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-14-plan-var-env-test.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-14-plan-var-env-test-300x184.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-14-plan-var-env-test-1024x629.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-14-plan-var-env-test-768x472.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-14-plan-var-env-test-1536x944.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>


<ul class="wp-block-list">
<li><strong><code>~ update in-place</code></strong>：原地修改，資源不用刪掉重建</li>

<li><strong><code>"dev" -&gt; "test"</code></strong>：箭頭左邊是現在、右邊是改完</li>

<li>只有用到 <code>var.env</code> 的 2 個資源會變，服務帳戶沒用到，所以不在清單裡</li>

<li>這次只 plan、不 apply。同一份設定檔，換不同的變數值就能建出 dev、test 兩套環境，這是變數最常見的用法</li>
</ul>



<h3 class="wp-block-heading">步驟 14：有人在 Console 偷改了，Terraform 抓得到嗎</h3>



<p class="wp-block-paragraph">模擬同事沒經過 Terraform、直接用 gcloud 把 bucket 的 <code>env</code> 標籤改成 <code>hotfix</code>，然後馬上 plan：</p>



<pre class="wp-block-code"><code>gcloud storage buckets update gs://do-10-dong-dong-gcp-3-files --update-labels=env=hotfix; terraform plan</code></pre>



<pre class="wp-block-code"><code>Updating gs://do-10-dong-dong-gcp-3-files/...
（Refreshing state 3 行省略）
Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
  ~ update in-place

Terraform will perform the following actions:

  # google_storage_bucket.files will be updated in-place
  ~ resource "google_storage_bucket" "files" {
      ~ effective_labels            = {
          ~ "env"                        = "hotfix" -&gt; "dev"
            # (2 unchanged elements hidden)
        }
        id                          = "do-10-dong-dong-gcp-3-files"
      ~ labels                      = {
          ~ "env"        = "hotfix" -&gt; "dev"
            # (1 unchanged element hidden)
        }
（中間省略）
Plan: 0 to add, 1 to change, 0 to destroy.</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="778" src="https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-15-drift-plan.png" alt="先用 gcloud 把 bucket 的 env 標籤改成 hotfix，再跑 terraform plan：bucket will be updated in-place，env 從 hotfix 改回 dev，Plan: 0 to add, 1 to change" class="wp-image-14191" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-15-drift-plan.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-15-drift-plan-300x146.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-15-drift-plan-1024x498.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-15-drift-plan-768x373.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-15-drift-plan-1536x747.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph">抓到了。雲端現況（<code>hotfix</code>）跟設定檔（<code>dev</code>）對不上，這就是<strong>漂移</strong>（drift）。對設定檔裡<strong>有寫的屬性</strong>，Terraform 以設定檔為準，所以計畫是把它改回 <code>dev</code>。</p>



<p class="wp-block-paragraph">要注意兩個例外：設定檔<strong>沒寫</strong>的欄位被手動改了，plan 通常不會列出來，也不會改回去；另外設定檔可以用 <code>lifecycle { ignore_changes = [...] }</code>（<a href="https://developer.hashicorp.com/terraform/language/meta-arguments/lifecycle">官方說明</a>）刻意叫 Terraform 不管某些欄位。</p>



<p class="wp-block-paragraph">套用，改回來：</p>



<pre class="wp-block-code"><code>terraform apply -auto-approve; gcloud storage buckets describe gs://do-10-dong-dong-gcp-3-files --format='value(labels)'</code></pre>



<pre class="wp-block-code"><code>（plan 內容省略）
Plan: 0 to add, 1 to change, 0 to destroy.
google_storage_bucket.files: Modifying... [id=do-10-dong-dong-gcp-3-files]
google_storage_bucket.files: Modifications complete after 0s [id=do-10-dong-dong-gcp-3-files]

Apply complete! Resources: 0 added, 1 changed, 0 destroyed.
（Outputs 省略）
env=dev;goog-terraform-provisioned=true;managed-by=terraform</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="978" src="https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-16-drift-fixed.png" alt="terraform apply -auto-approve 把 bucket 的 env 標籤改回 dev，Apply complete! Resources: 0 added, 1 changed，gcloud 再查標籤已經是 env=dev" class="wp-image-14192" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-16-drift-fixed.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-16-drift-fixed-300x183.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-16-drift-fixed-1024x626.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-16-drift-fixed-768x469.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-16-drift-fixed-1536x939.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph"><code>-auto-approve</code> 是跳過打 <code>yes</code> 的確認，CI/CD 自動化常用；自己手動操作時<strong>不建議</strong>，因為你就看不到計畫了。</p>



<p class="wp-block-paragraph">這個例子也說明一件事：<strong>用 Terraform 管的資源，就不要再到 Console 手動改</strong>。手動改的東西，下次有人跑 apply 就會被蓋回去。真的要改，改設定檔。</p>



<h3 class="wp-block-heading">步驟 15：改區域看 <code>-/+</code>，這次只看不做</h3>



<p class="wp-block-paragraph">如果把 <code>region</code> 從台灣換成東京（<code>asia-northeast1</code>）會怎樣：</p>



<pre class="wp-block-code"><code>terraform plan -var="region=asia-northeast1"</code></pre>



<pre class="wp-block-code"><code>Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
-/+ destroy and then create replacement

Terraform will perform the following actions:

  # google_cloud_run_v2_service.hello must be replaced
-/+ resource "google_cloud_run_v2_service" "hello" {
（中間省略）
      ~ location                = "asia-east1" -&gt; "asia-northeast1" # forces replacement
（中間省略）
  # google_storage_bucket.files must be replaced
-/+ resource "google_storage_bucket" "files" {
（中間省略）
      ~ location                    = "ASIA-EAST1" -&gt; "ASIA-NORTHEAST1" # forces replacement
（中間省略）
Plan: 2 to add, 0 to change, 2 to destroy.</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="983" src="https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-17-plan-replace.png" alt="terraform plan -var=&quot;region=asia-northeast1&quot;：bucket 標紅字 must be replaced，location 從 ASIA-EAST1 改 ASIA-NORTHEAST1 後面註明 forces replacement，最後 Plan: 2 to add, 0 to change, 2 to destroy" class="wp-image-14193" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-17-plan-replace.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-17-plan-replace-300x184.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-17-plan-replace-1024x629.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-17-plan-replace-768x472.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-17-plan-replace-1536x944.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>


<ul class="wp-block-list">
<li><strong><code>-/+ destroy and then create replacement</code></strong>：先刪掉、再建新的。有些屬性建好就不能改（bucket 的位置就是），要改只能整個重建</li>

<li><strong><code># forces replacement</code></strong>：標出是哪一行逼它重建</li>

<li><strong>這是最危險的一種</strong>：bucket 被刪掉，<strong>裡面的檔案會一起不見</strong>。這次 bucket 是空的而且我只 plan，沒有 apply</li>

<li>服務帳戶不分區域，所以不受影響：2 個重建、1 個不動</li>
</ul>



<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/do10-cards-02-plan-symbols.png" alt="terraform plan 的 4 種符號對照：+ 新增，第一次 plan 3 to add；~ 原地修改，env 從 dev 改 test 是 2 to change、手動改標籤是 1 to change；-/+ 砍掉重建，區域改 asia-northeast1 是 2 to add 2 to destroy；- 刪除，terraform destroy 是 3 to destroy" class="wp-image-14194" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do10-cards-02-plan-symbols.png 1200w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-cards-02-plan-symbols-300x169.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-cards-02-plan-symbols-1024x576.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-cards-02-plan-symbols-768x432.png 768w" sizes="(max-width: 1200px) 100vw, 1200px" /></figure>



<p class="wp-block-paragraph">看 plan 的習慣：<strong>先看最後一行的數字，再找有沒有 <code>-/+</code> 和 <code>-</code></strong>。有的話，確認那個資源裡有沒有不能丟的資料。</p>



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



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



<p class="wp-block-paragraph">這篇建了：Cloud Storage bucket、服務帳戶、Cloud Run 服務，還有 Cloud Shell 裡的 <code>~/do-10</code> 資料夾和裝好的 Terraform。<strong>不刪會怎麼計費</strong>：</p>


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

<li><strong>Cloud Storage bucket</strong>：空的不收錢；放了檔案，台灣 <code>asia-east1</code> 的 Standard 儲存是每 GiB 每月 0.020 美元（2026 年 12 月查 Cloud Billing Catalog API，<a href="https://cloud.google.com/storage/pricing">定價頁</a>）。算一次：放 10 GiB 的檔案，10 × 0.020 = 每月 0.2 美元；放 1 TiB（1,024 GiB）就是每月約 20.5 美元。檔案越放越多，帳單就跟著長</li>

<li><strong>服務帳戶</strong>：不收費，但留著就是一個沒人管的身分，該刪</li>
</ul>



<h3 class="wp-block-heading">步驟 16：terraform destroy，第一次失敗</h3>



<p class="wp-block-paragraph"><strong><code>terraform destroy</code> 會把 state 裡記的資源全部刪掉，一樣要打 <code>yes</code>。</strong>它只刪 state 裡記的這 3 個，專案裡其他不是這份設定建的東西不會動。</p>



<pre class="wp-block-code"><code>terraform destroy</code></pre>



<pre class="wp-block-code"><code>（每個資源要刪掉的屬性都列出來，省略）
Plan: 0 to add, 0 to change, 3 to destroy.

Changes to Outputs:
  - bucket_name           = "do-10-dong-dong-gcp-3-files" -&gt; null
  - service_account_email = "do-10-run@dong-dong-gcp-3.iam.gserviceaccount.com" -&gt; null
  - service_url           = "https://do-10-hello-b5j2wtbgca-de.a.run.app" -&gt; null

Do you really want to destroy all resources?
  Terraform will destroy all your managed infrastructure, as shown above.
  There is no undo. Only 'yes' will be accepted to confirm.

  Enter a value: yes

google_storage_bucket.files: Destroying... [id=do-10-dong-dong-gcp-3-files]
google_cloud_run_v2_service.hello: Destroying... [id=projects/dong-dong-gcp-3/locations/asia-east1/services/do-10-hello]
google_storage_bucket.files: Destruction complete after 1s
╷
│ Error: cannot destroy service without setting deletion_protection=false and running `terraform apply`
│
│
╵</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="983" src="https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-19-destroy-error.png" alt="terraform destroy 輸入 yes 後，bucket 1 秒刪掉，但 Cloud Run 出現紅字 Error: cannot destroy service without setting deletion_protection=false and running terraform apply" class="wp-image-14195" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-19-destroy-error.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-19-destroy-error-300x184.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-19-destroy-error-1024x629.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-19-destroy-error-768x472.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-19-destroy-error-1536x944.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph">bucket 刪掉了，Cloud Run 刪不掉。原因就是步驟 7 看到的 <code>deletion_protection = true</code>：google provider 從 <a href="https://registry.terraform.io/providers/hashicorp/google/latest/docs/guides/version_6_upgrade">6.0 版</a>起，Cloud Run 服務預設開啟「刪除保護」，防止有人一個 destroy 就把正式服務刪掉。服務帳戶因為 Cloud Run 還在用（相依），也沒輪到刪。</p>



<p class="wp-block-paragraph">兩個重點：</p>


<ul class="wp-block-list">
<li>這個保護<strong>只擋 Terraform</strong>。官方升級指南寫明它不會擋 Terraform 以外的刪除，在 Console 或用 gcloud 照樣刪得掉</li>

<li>錯誤訊息說得很清楚：要先把 <code>deletion_protection</code> 改成 <code>false</code>，<strong>而且要 apply 一次</strong>讓 state 記住，再 destroy</li>
</ul>



<h3 class="wp-block-heading">步驟 17：關掉刪除保護，apply 一次</h3>



<p class="wp-block-paragraph">這一步要在 <code>main.tf</code> 的 Cloud Run 那段加一行 <code>deletion_protection = false</code>，改完長這樣，新加的那行在 <code>resource "google_cloud_run_v2_service" "hello" {</code> 的大括號裡面：</p>



<pre class="wp-block-code"><code>resource "google_cloud_run_v2_service" "hello" {
  name                 = "do-10-hello"
  location             = var.region
  invoker_iam_disabled = true
  deletion_protection  = false

  labels = {</code></pre>



<p class="wp-block-paragraph">看不懂下面的 <code>sed</code> 沒關係，用編輯器打開 <code>main.tf</code>，在 <code>invoker_iam_disabled = true</code> 下面手動多打這一行，結果一樣。我實測是用指令做的：<code>sed</code>（用指令改文字檔的工具）插入那一行，<code>grep</code>（找文字的工具）印出那兩行確認位置，最後 apply：</p>



<pre class="wp-block-code"><code>terraform state list; sed -i '/invoker_iam_disabled = true/a\  deletion_protection  = false' main.tf; grep -n -A1 invoker_iam_disabled main.tf; terraform apply -auto-approve</code></pre>



<pre class="wp-block-code"><code>google_cloud_run_v2_service.hello
google_service_account.run
38:  invoker_iam_disabled = true
39-  deletion_protection  = false
（Refreshing state 省略）
Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
  + create
  ~ update in-place

Terraform will perform the following actions:

  # google_cloud_run_v2_service.hello will be updated in-place
  ~ resource "google_cloud_run_v2_service" "hello" {
      ~ deletion_protection     = true -&gt; false
        id                      = "projects/dong-dong-gcp-3/locations/asia-east1/services/do-10-hello"
        name                    = "do-10-hello"
        # (36 unchanged attributes hidden)

        # (3 unchanged blocks hidden)
    }

  # google_storage_bucket.files will be created
（中間省略）
Plan: 1 to add, 1 to change, 0 to destroy.
（中間省略）
google_storage_bucket.files: Creating...
google_cloud_run_v2_service.hello: Modifying... [id=projects/dong-dong-gcp-3/locations/asia-east1/services/do-10-hello]
google_cloud_run_v2_service.hello: Modifications complete after 1s [id=projects/dong-dong-gcp-3/locations/asia-east1/services/do-10-hello]
google_storage_bucket.files: Creation complete after 2s [id=do-10-dong-dong-gcp-3-files]

Apply complete! Resources: 1 added, 1 changed, 0 destroyed.</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="983" src="https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-20-deletion-protection-false.png" alt="加上 deletion_protection = false 後 terraform apply -auto-approve：Cloud Run 的 deletion_protection 從 true 改成 false，同時 bucket 被重新建立，Apply complete! Resources: 1 added, 1 changed" class="wp-image-14196" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-20-deletion-protection-false.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-20-deletion-protection-false-300x184.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-20-deletion-protection-false-1024x629.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-20-deletion-protection-false-768x472.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-20-deletion-protection-false-1536x944.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph"><strong>這裡出了一個意外</strong>：<code>terraform state list</code> 只剩 2 個資源（bucket 在步驟 16 刪掉了），但 <code>main.tf</code> 裡 bucket 還寫著。apply 的工作是「讓雲端跟設定檔一樣」，所以它<strong>把剛刪掉的 bucket 又建了回來</strong>（<code>1 to add</code>）。我原本只想改刪除保護，因為用了 <code>-auto-approve</code> 沒看計畫就套用了。這正是步驟 14 說「手動操作不建議用 <code>-auto-approve</code>」的原因。你照做時，建議把最後的 <code>terraform apply -auto-approve</code> 換成 <code>terraform apply</code>，看到計畫裡的 <code>1 to add</code>，就知道 bucket 會被建回來，心裡有數再打 <code>yes</code>（步驟 18 的 destroy 會把它一起刪掉）。</p>



<h3 class="wp-block-heading">步驟 18：再 destroy 一次，全部刪乾淨</h3>



<pre class="wp-block-code"><code>terraform destroy -auto-approve</code></pre>



<pre class="wp-block-code"><code>（省略）
Plan: 0 to add, 0 to change, 3 to destroy.
（中間省略）
google_storage_bucket.files: Destroying... [id=do-10-dong-dong-gcp-3-files]
google_cloud_run_v2_service.hello: Destroying... [id=projects/dong-dong-gcp-3/locations/asia-east1/services/do-10-hello]
google_storage_bucket.files: Destruction complete after 1s
google_cloud_run_v2_service.hello: Still destroying... [id=projects/dong-dong-gcp-3/locations/asia-east1/services/do-10-hello, 00m10s elapsed]
google_cloud_run_v2_service.hello: Destruction complete after 10s
google_service_account.run: Destroying... [id=projects/dong-dong-gcp-3/serviceAccounts/do-10-run@dong-dong-gcp-3.iam.gserviceaccount.com]
google_service_account.run: Destruction complete after 1s

Destroy complete! Resources: 3 destroyed.</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1600" height="983" src="https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-21-destroy-complete.png" alt="terraform destroy -auto-approve：bucket 1 秒、Cloud Run 10 秒刪完，最後才刪服務帳戶，Destroy complete! Resources: 3 destroyed" class="wp-image-14197" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-21-destroy-complete.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-21-destroy-complete-300x184.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-21-destroy-complete-1024x629.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-21-destroy-complete-768x472.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-21-destroy-complete-1536x944.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<p class="wp-block-paragraph">刪的順序跟建的時候相反：Cloud Run 刪完，才輪到它用的服務帳戶。</p>



<p class="wp-block-paragraph">確認 state 是空的、GCP 上也找不到 <code>do-10-</code> 開頭的資源：</p>



<pre class="wp-block-code"><code>terraform state list | wc -l; gcloud run services list --region=asia-east1 --filter='metadata.name~^do-10-' --format='value(metadata.name)'; gcloud iam service-accounts list --filter='email~^do-10-' --format='value(email)'; gcloud storage buckets list --filter='name~^do-10-' --format='value(name)'</code></pre>



<pre class="wp-block-code"><code>0</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/do10-shots-22-verify-clean.png" alt="terraform state list 數量是 0，gcloud 查 Cloud Run 服務、服務帳戶、bucket 都沒有 do-10- 開頭的結果" class="wp-image-14198" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-22-verify-clean.png 1600w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-22-verify-clean-300x21.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-22-verify-clean-1024x73.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-22-verify-clean-768x55.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-22-verify-clean-1536x109.png 1536w" sizes="(max-width: 1600px) 100vw, 1600px" /></figure>



<h3 class="wp-block-heading">步驟 19：刪掉練習資料夾</h3>



<pre class="wp-block-code"><code>cd ~ &amp;&amp; rm -rf ~/do-10 &amp;&amp; ls -d ~/do-10 2&gt;&amp;1 | sed "s#$HOME#~#"</code></pre>



<pre class="wp-block-code"><code>ls: cannot access '~/do-10': No such file or directory</code></pre>



<figure class="wp-block-image aligncenter size-full"><img loading="lazy" decoding="async" width="1596" height="177" src="https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-23-cleanup.png" alt="回到家目錄刪掉 ~/do-10，ls 確認資料夾已經不存在" class="wp-image-14199" srcset="https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-23-cleanup.png 1596w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-23-cleanup-300x33.png 300w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-23-cleanup-1024x114.png 1024w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-23-cleanup-768x85.png 768w, https://dongdonggcp.com/wp-content/uploads/2026/12/do10-shots-23-cleanup-1536x170.png 1536w" sizes="(max-width: 1596px) 100vw, 1596px" /></figure>



<p class="wp-block-paragraph"><code>.terraform</code> 的 135 MB 也一起刪了。用 apt 裝的 Terraform 不用特別移除：它裝在家目錄以外，Cloud Shell 下次重開就不見了。我另外用 Cloud Shell 跑了系列的清理檢查腳本，專案裡沒有任何 <code>do-10-</code> 開頭的資源。</p>



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



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



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph"><strong>1. Cloud Shell 不內建 Terraform 了</strong>：打 <code>terraform version</code> 只印出安裝說明。<a href="https://docs.cloud.google.com/shell/docs/release-notes">Cloud Shell 版本資訊</a>寫明 2026 年 6 月 20 日起移除。Google 官方繁中的 Terraform 快速入門，事前準備已經改成「請照 HashiCorp 的說明安裝」，但頁面裡的範例輸出還是 provider <code>v5.35.0</code>，跟這次裝到的 <code>v8.12.0</code> 差了 3 個大版本（步驟 1、5）。</p>



<p class="wp-block-paragraph"><strong>2. 用 apt 裝的重開就不見</strong>：只有家目錄會保存。要長期用，寫進 <code>~/.customize_environment</code> 或把執行檔放家目錄（步驟 2）。</p>



<p class="wp-block-paragraph"><strong>3. provider 自己加了一個標籤</strong>：我只寫了 <code>env</code>、<code>managed-by</code>，資源上多了 <code>goog-terraform-provisioned=true</code>，6.0 版起的預設行為（步驟 7、10）。</p>



<p class="wp-block-paragraph"><strong>4. Cloud Run 預設有刪除保護</strong>：plan 裡就有 <code>deletion_protection = true</code>，第一次 destroy 刪掉 bucket 後卡在 Cloud Run（步驟 16）。</p>



<p class="wp-block-paragraph"><strong>5. 關保護的那次 apply，把刪掉的 bucket 又建回來</strong>：設定檔還寫著 bucket，apply 就照設定檔補回去；加了 <code>-auto-approve</code> 沒看到計畫（步驟 17）。</p>



<p class="wp-block-paragraph"><strong>6. state 裡有我的 email</strong>：Cloud Run 的 <code>creator</code> 欄位明文存著建立者帳號（步驟 11）。</p>



<p class="wp-block-paragraph"><strong>7. 服務帳戶建了 23 秒</strong>：比 bucket（2 秒）、Cloud Run（11 秒）都久，Cloud Run 一直等它建好才開始（步驟 8）。</p>



<p class="wp-block-paragraph"><strong>8. plan 不會特別標「這是有人在外面改的」</strong>：手動改標籤後的 plan，長得跟步驟 13 改變數時一樣，都是 <code>~ update in-place</code>，差別只在箭頭左邊變成 <code>hotfix</code>。要認出漂移，得自己看箭頭左邊的值是不是你設定的（步驟 14）。</p>
</blockquote>



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



<h2 class="wp-block-heading">Terraform 和 OpenTofu、Infrastructure Manager、Config Connector 差在哪</h2>



<p class="wp-block-paragraph">新版考綱 1.2 一次列了好幾個 IaC 工具，先用一張表分清楚，細節在第 11 篇。</p>



<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>Terraform</td><td>這篇用的，最多人用的 IaC 工具</td><td>HashiCorp（2025 年起屬於 IBM），BSL 授權</td><td>HCL（<code>.tf</code>）</td></tr><tr><td>OpenTofu</td><td>2023 年授權改變後，社群分出來的開源版本</td><td>開源社群</td><td>跟 Terraform 幾乎一樣的 HCL</td></tr><tr><td>Infrastructure Manager</td><td>Google 代管的服務，幫你跑 Terraform、保管 state</td><td>Google Cloud</td><td>一樣寫 Terraform</td></tr><tr><td>Config Connector</td><td>用 Kubernetes 的 YAML 管 GCP 資源</td><td>Google Cloud</td><td>Kubernetes YAML</td></tr><tr><td>Helm</td><td>打包、安裝 Kubernetes 應用程式的工具</td><td>CNCF 社群</td><td>範本化的 YAML</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">OpenTofu 最新是 1.13.11（2026 年 11 月 30 日在 GitHub 發布，2026 年 12 月查），這篇沒有實測 OpenTofu。</p>



<p class="wp-block-paragraph">Infrastructure Manager 能用的 Terraform 版本有限：沒指定時預設用免費的 1.5.7，較新的 1.16.5 要另外收管理費，都不是這篇用的 1.17.3（2026 年 12 月查<a href="https://docs.cloud.google.com/infrastructure-manager/docs/terraform-version-deprecation">官方支援版本表</a>）。在 Cloud Shell 用新版語法寫的設定，搬過去前要先確認版本。</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>1.2 管理基礎架構</strong></td><td>IaC 工具與代管服務（Application Design Center、Infrastructure Manager、Config Connector、GitOps、Terraform、Helm）</td><td>整篇；工具比較表</td></tr><tr><td><strong>1.2</strong></td><td>用 Google 建議的做法和藍圖改基礎架構（<strong>Terraform modules and blueprints，新版點名</strong>）</td><td>這篇的 4 個檔案就是最小的「根模組」，modules 在第 11 篇</td></tr><tr><td><strong>2.1 建置管線</strong></td><td>應用程式<strong>和基礎架構</strong>的 CI/CD</td><td><code>plan -out</code> 存檔、審過再 apply 的做法</td></tr><tr><td><strong>1.4 管理多個執行環境</strong></td><td>管理短暫環境（ephemeral environments）</td><td>同一份設定換 <code>env</code> 變數；用完 <code>terraform destroy</code></td></tr><tr><td><strong>1.5 管理雲端開發環境</strong></td><td>幫環境裝好需要的工具（bootstrapping），例子點名 Cloud Shell</td><td>Cloud Shell 不內建 Terraform 了，用 <code>~/.customize_environment</code> 每次開機自動裝</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">跟舊版比：1.2 新增了 Application Design Center，拿掉了 Cloud Foundation Toolkit，「藍圖」那條多寫了 Terraform modules。</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>「環境要能重複建立」「避免手動設定」「設定要版本控制」</td><td>IaC，Terraform 設定檔放 Git</td></tr><tr><td>「套用前先確認會改什麼」「變更要審查」</td><td><code>terraform plan</code>（CI 裡 <code>plan -out</code> 給人審）</td></tr><tr><td>「有人在 Console 手動改了設定」「設定漂移」</td><td>跑 <code>terraform plan</code> 找差異，用 apply 改回設定檔的樣子（只限設定檔有寫的屬性；<code>lifecycle</code> 的 <code>ignore_changes</code> 列出的欄位不管）</td></tr><tr><td>「多人一起改」「state 檔衝突、遺失」</td><td>state 放遠端（Cloud Storage）並加鎖，第 11 篇</td></tr><tr><td>「state 裡有敏感資料」</td><td>state 不放 Git、限制存取權限、遠端加密</td></tr><tr><td>「不想自己架 Terraform 執行環境」「Google 代管」</td><td>Infrastructure Manager</td></tr><tr><td>「用 Kubernetes 的方式管 GCP 資源」</td><td>Config Connector</td></tr><tr><td>「防止 Terraform 誤刪正式服務」</td><td><code>deletion_protection</code>（只擋 Terraform）、搭配 IAM 權限控管</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>「Terraform 的 plan 和 apply 差在哪？」</strong>：plan 只比對、列出要做的事，不動手；apply 才真的呼叫 API。補一句「apply 前一定先看 plan 最後一行的數字，有 <code>-/+</code> 要特別確認資料會不會丟」</li>

<li><strong>「state 是什麼？為什麼不能放 Git？」</strong>：Terraform 記住它管哪些資源的檔案；裡面是明文，會有帳號、密碼這類敏感值。團隊要放遠端（例如 Cloud Storage）並開鎖定，避免兩個人同時 apply</li>

<li><strong>「有人在 Console 手動改了 Terraform 管的資源會怎樣？」</strong>：設定檔裡有寫的屬性，下次 plan 會出現差異（漂移），apply 會改回設定檔的樣子（這篇實測：手動把標籤改成 hotfix，plan 顯示 <code>1 to change</code>，apply 後回到 dev）。設定檔沒寫的欄位就抓不到，所以規定要改就改設定檔</li>

<li><strong>「什麼情況 Terraform 會把資源刪掉重建？」</strong>：改了不能原地修改的屬性，例如 bucket 的位置，plan 會標 <code>-/+</code> 和 <code># forces replacement</code></li>

<li><strong>「Terraform 跟 gcloud 腳本差在哪？」</strong>：gcloud 腳本寫步驟（命令式），重跑要自己處理「已經存在」；Terraform 寫最後狀態（宣告式），重跑沒差異就 <code>No changes</code></li>
</ul>



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



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



<h3 class="wp-block-heading">Cloud Shell 為什麼打 terraform 沒反應，只有安裝說明？</h3>



<p class="wp-block-paragraph">Google Cloud 的 Cloud Shell 版本資訊寫明，2026 年 6 月 20 日起 Cloud Shell 不再內建 Terraform CLI。現在打 <code>terraform</code> 只會印出安裝說明。照說明用 apt 安裝（這篇實測裝到 1.17.3）就能用，但 Cloud Shell 重開後會消失；要保留，就把安裝指令寫進 <code>~/.customize_environment</code>，或把執行檔放在家目錄。</p>



<h3 class="wp-block-heading">Terraform 要錢嗎？</h3>



<p class="wp-block-paragraph">Terraform CLI 可以免費下載使用。2023 年 8 月起新版本改用 BSL 1.1 授權，限制的是拿它做跟 HashiCorp 競爭的商業服務，一般個人和公司內部使用不受影響。要付錢的是你用 Terraform 建出來的雲端資源，例如這篇的 Cloud Storage 放了檔案才照容量收費、Cloud Run 有流量才收運算費。</p>



<h3 class="wp-block-heading">terraform.tfstate 可以放進 Git 嗎？</h3>



<p class="wp-block-paragraph">不建議。HashiCorp 官方文件寫明 state 是明文檔案，會存下設定裡的秘密值；這篇實測 Cloud Run 的 <code>creator</code> 欄位就存著建立者的 email。一個人練習放本機就好；團隊使用要放到有權限控管、能加鎖的遠端位置，例如 Cloud Storage。<code>.terraform.lock.hcl</code>（provider 版本鎖定檔）則建議放進 Git。</p>



<h3 class="wp-block-heading">為什麼 terraform destroy 刪不掉 Cloud Run？</h3>



<p class="wp-block-paragraph">google provider 從 6.0 版起，<code>google_cloud_run_v2_service</code> 的 <code>deletion_protection</code> 預設是 <code>true</code>。實測第一次 destroy 回 <code>cannot destroy service without setting deletion_protection=false and running terraform apply</code>。做法是在設定檔加上 <code>deletion_protection = false</code>，先 apply 一次讓 state 記住，再 destroy。這個保護只擋 Terraform，在 Console 或用 gcloud 照樣刪得掉。</p>



<h3 class="wp-block-heading">在 Console 手動改了 Terraform 建的資源會怎樣？</h3>



<p class="wp-block-paragraph">如果改的是設定檔裡有寫的屬性，下次 <code>terraform plan</code> 會列出差異，apply 會改回設定檔寫的樣子。實測用 gcloud 把 bucket 的 <code>env</code> 標籤改成 <code>hotfix</code>，plan 立刻列出 <code>"hotfix" -&gt; "dev"</code>、<code>1 to change</code>，apply 後標籤回到 <code>dev</code>。設定檔沒寫的欄位被手動改了，plan 通常看不出來，所以 Terraform 管的資源，要改就改設定檔，不要手動改。</p>



<h3 class="wp-block-heading">Terraform 和 OpenTofu 差在哪？</h3>



<p class="wp-block-paragraph">OpenTofu 是 2023 年 Terraform 改成 BSL 授權後，社群從最後一個開源版本分出來的工具，2024 年 1 月 10 日推出 1.6.0 正式版，寫法幾乎跟 Terraform 一樣。差別主要在授權和維護者：Terraform 屬於 HashiCorp（2025 年起是 IBM 的一部分），OpenTofu 是開源社群維護。這篇只實測 Terraform。</p>



<h3 class="wp-block-heading">plan 裡的 <code>+</code>、<code>~</code>、<code>-/+</code>、<code>-</code> 是什麼意思？</h3>



<p class="wp-block-paragraph"><code>+</code> 是新增、<code>~</code> 是原地修改、<code>-/+</code> 是先刪除再重建、<code>-</code> 是刪除。這篇各實測一次：第一次 plan 是 <code>3 to add</code>；把 <code>env</code> 變數改成 <code>test</code> 是 <code>2 to change</code>；把區域改成 <code>asia-northeast1</code> 是 <code>2 to add, 2 to destroy</code>；destroy 是 <code>3 to destroy</code>。看到 <code>-/+</code> 和 <code>-</code> 要特別確認資料會不會跟著被刪。</p>



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



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


<ul class="wp-block-list">
<li><strong>Terraform 教學的核心是 4 個指令</strong>：<code>init</code> 下載 provider（實測 google 8.12.0，135 MB）、<code>plan</code> 只預覽、<code>apply</code> 打 <code>yes</code> 才建、<code>destroy</code> 照 state 全部刪</li>

<li><strong>Cloud Shell 從 2026 年 6 月 20 日起不內建 Terraform</strong>：照它印的 apt 指令裝（實測 1.17.3），重開會消失，要保留就寫進 <code>~/.customize_environment</code> 或放家目錄（家目錄 120 天沒用會被刪）</li>

<li><strong>state 是 Terraform 的記帳本</strong>：3 個資源就有 337 行 JSON，還明文存著建立者 email，不能放 Git；團隊用的遠端 state 在第 11 篇</li>

<li><strong>plan 最後一行先看</strong>：<code>+</code> 新增、<code>~</code> 原地修改、<code>-/+</code> 砍掉重建（bucket 的檔案會一起不見）、<code>-</code> 刪除；有人手動改了設定檔裡有寫的屬性，plan 會抓出漂移</li>

<li><strong>刪除有兩個坑</strong>：Cloud Run 預設 <code>deletion_protection = true</code>，要改 <code>false</code> 並 apply 一次；那次 apply 也會把已刪掉、但設定檔還寫著的資源重建回來</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>第 9 篇：<a href="https://dongdonggcp.com/2026/11/28/platform-engineering-ops-glossary-devops-sre-finops/">Ops 名詞總表：DevOps、SRE、Platform Engineering、FinOps 差在哪</a></li>

<li>第 11 篇：<a href="https://dongdonggcp.com/2026/12/05/terraform-state-gcs-modules-infrastructure-manager/">Terraform 進階：state 放 Cloud Storage、modules、Infrastructure Manager</a></li>

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



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


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

<li><a href="https://dongdonggcp.com/2026/11/21/cloud-run-pricing-cold-start-min-instances/">Cloud Run 收費怎麼算？Cloud Run pricing、冷啟動、最小執行個體一次看懂</a></li>

<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>
</ul>



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


<ul class="wp-block-list">
<li><a href="https://dongdonggcp.com/2024/12/02/what-is-gitops-methodolity-what-is-gitops-process/">GitOps 方法論是什麼東東？GitOps 的工作流程是什麼？</a></li>

<li><a href="https://dongdonggcp.com/2026/05/19/gcp-bill-explosion-prevention-guide/">GCP 帳單爆炸防護指南：5 個步驟讓你不再睡醒崩潰</a></li>
</ul>



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



<p class="wp-block-paragraph">一個人用 Terraform 建好環境之後，下一步是讓團隊一起用：state 放到 Cloud Storage、把重複的設定包成模組，第 11 篇接著做。可以看看<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": "Cloud Shell 為什麼打 terraform 沒反應，只有安裝說明？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "Google Cloud 的 Cloud Shell 版本資訊寫明，2026 年 6 月 20 日起 Cloud Shell 不再內建 Terraform CLI。現在打 `terraform` 只會印出安裝說明。照說明用 apt 安裝（這篇實測裝到 1.17.3）就能用，但 Cloud Shell 重開後會消失；要保留，就把安裝指令寫進 `~/.customize_environment`，或把執行檔放在家目錄。"
      }
    },
    {
      "@type": "Question",
      "name": "Terraform 要錢嗎？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "Terraform CLI 可以免費下載使用。2023 年 8 月起新版本改用 BSL 1.1 授權，限制的是拿它做跟 HashiCorp 競爭的商業服務，一般個人和公司內部使用不受影響。要付錢的是你用 Terraform 建出來的雲端資源，例如這篇的 Cloud Storage 放了檔案才照容量收費、Cloud Run 有流量才收運算費。"
      }
    },
    {
      "@type": "Question",
      "name": "terraform.tfstate 可以放進 Git 嗎？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "不建議。HashiCorp 官方文件寫明 state 是明文檔案，會存下設定裡的秘密值；這篇實測 Cloud Run 的 `creator` 欄位就存著建立者的 email。一個人練習放本機就好；團隊使用要放到有權限控管、能加鎖的遠端位置，例如 Cloud Storage。`.terraform.lock.hcl`（provider 版本鎖定檔）則建議放進 Git。"
      }
    },
    {
      "@type": "Question",
      "name": "為什麼 terraform destroy 刪不掉 Cloud Run？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "google provider 從 6.0 版起，`google_cloud_run_v2_service` 的 `deletion_protection` 預設是 `true`。實測第一次 destroy 回 `cannot destroy service without setting deletion_protection=false and running terraform apply`。做法是在設定檔加上 `deletion_protection = false`，先 apply 一次讓 state 記住，再 destroy。這個保護只擋 Terraform，在 Console 或用 gcloud 照樣刪得掉。"
      }
    },
    {
      "@type": "Question",
      "name": "在 Console 手動改了 Terraform 建的資源會怎樣？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "如果改的是設定檔裡有寫的屬性，下次 `terraform plan` 會列出差異，apply 會改回設定檔寫的樣子。實測用 gcloud 把 bucket 的 `env` 標籤改成 `hotfix`，plan 立刻列出 `\"hotfix\" -> \"dev\"`、`1 to change`，apply 後標籤回到 `dev`。設定檔沒寫的欄位被手動改了，plan 通常看不出來，所以 Terraform 管的資源，要改就改設定檔，不要手動改。"
      }
    },
    {
      "@type": "Question",
      "name": "Terraform 和 OpenTofu 差在哪？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "OpenTofu 是 2023 年 Terraform 改成 BSL 授權後，社群從最後一個開源版本分出來的工具，2024 年 1 月 10 日推出 1.6.0 正式版，寫法幾乎跟 Terraform 一樣。差別主要在授權和維護者：Terraform 屬於 HashiCorp（2025 年起是 IBM 的一部分），OpenTofu 是開源社群維護。這篇只實測 Terraform。"
      }
    },
    {
      "@type": "Question",
      "name": "plan 裡的 `+`、`~`、`-/+`、`-` 是什麼意思？",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "`+` 是新增、`~` 是原地修改、`-/+` 是先刪除再重建、`-` 是刪除。這篇各實測一次：第一次 plan 是 `3 to add`；把 `env` 變數改成 `test` 是 `2 to change`；把區域改成 `asia-northeast1` 是 `2 to add, 2 to destroy`；destroy 是 `3 to destroy`。看到 `-/+` 和 `-` 要特別確認資料會不會跟著被刪。"
      }
    }
  ]
}
</script><p>The post <a href="https://dongdonggcp.com/2026/12/05/terraform-tutorial-gcp-init-plan-apply-state/">Terraform 教學：用程式碼建 GCP 資源（init、plan、apply、state）</a> first appeared on <a href="https://dongdonggcp.com">東東 GCP 教學 - GCP 實戰講師</a>.</p>]]></content:encoded>
					
					<wfw:commentRss>https://dongdonggcp.com/2026/12/05/terraform-tutorial-gcp-init-plan-apply-state/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
