Terraform state 放 Cloud Storage 多人共用又加鎖,模組重用設定,Google 也能代跑。
Terraform 是把雲端資源寫成文字檔、交給它去建的工具;state(狀態檔)是 Terraform 記住「我建了哪些東西」的記帳本,預設是你下指令那個資料夾裡的 terraform.tfstate。第 10 篇:Terraform 教學:用程式碼建 GCP 資源(init、plan、apply、state)已經把基本功走過一次:provider、resource、變數、output,init、plan、apply、destroy 四個指令。不熟的話,先把 plan 當成「預覽會改什麼」、apply 當成「真的去改」就夠了。這篇接著處理一個人練完之後一定會遇到的三個問題:同事也要改同一套環境,記帳本放哪?同樣的設定一直複製貼上怎麼辦?能不能不要自己按 apply?
我在 2026 年 12 月 5 日凌晨,用 Cloud Shell 實際做了一次:
- 用 gcloud 建一個開了版本控管的 bucket,再用
terraform init -migrate-state把本機的 terraform state 搬上 Cloud Storage - 開兩個終端機模擬兩個人:A 的 apply 停在等 yes,B 一跑 plan 就被 state lock(狀態鎖)擋下,畫面是
Error 412,意思是「有人正在用,請等一下」 - 把 A 的程式強制砍掉,留下一把沒人拿著、也不會自己消失的鎖,再用
terraform force-unlock解開,發現要用錯誤訊息裡的數字 ID,鎖檔裡那串英數字 ID 會失敗 - 自己寫一個 bucket 模組叫兩次,再用 Google 維護的官方 Registry 模組建第三個
- 把一份設定交給 Infrastructure Manager(Google 代管的 Terraform 執行服務),從下指令到建好 3 分 46 秒,預設用的 Terraform 是 1.5.7
這篇寫給已經會 Terraform 基本指令、要開始跟同事一起用的人,也寫給準備 GCP DevOps 證照的人。指令都可以整段複製,最後全部刪乾淨。

為什麼你需要知道
- 記帳本只有一份,而且在你的資料夾裡:第 10 篇的
terraform.tfstate放在 Cloud Shell 的練習資料夾。同事在自己電腦跑同一份設定,Terraform 看不到你的記帳本,會當成什麼都還沒建,plan 出來全是+新增 - 兩個人同時改,會改到同一本帳:這篇實測 A 正在 apply 時,B 跑 plan 直接被擋下來。看懂這個錯誤訊息,才知道該等、還是該解鎖
- 鎖卡住時不會解,整個團隊都動不了:apply 跑到一半被中斷,鎖不會自己消失。這篇實測第一次用錯 ID 解鎖失敗,第二次才成功
- 同樣的設定複製貼上 10 次,規定一改就要改 10 個地方:模組(module)把「公司規定的 bucket 長什麼樣」寫一次,到處叫它
- 上班第一週就會碰到:公司的 Terraform 幾乎都是多人共用、state 放遠端,新人報到先拿到的就是 backend 設定和模組資料夾。面試也常問「state 放哪」「鎖卡住怎麼辦」,文末整理了題目
- 證照會考:Professional Cloud DevOps Engineer 2026 年 11 月 23 日起的新版考綱,1.2 點名 Infrastructure Manager,也新增了「Terraform modules and blueprints」
先懂 4 個名詞
backend 和遠端 state 是什麼
backend(後端)是 Terraform 存放 state 的地方。沒設定時用 local,state 是你資料夾裡的 terraform.tfstate;改成 gcs,state 就變成 Cloud Storage bucket 裡的一個檔案,大家讀寫同一份。放在遠端的 state 就叫遠端 state(remote state)。
- 白話:記帳本從你的抽屜,搬到辦公室有鎖的公用櫃子
- 生活比喻:第 10 篇把 state 比喻成工頭的進貨單。一個工地有三個工頭,進貨單如果各自放口袋,誰也不知道別人買過什麼;放在工地辦公室的櫃子,每個人進貨前先翻同一本
- 來龍去脈:團隊要共用 state,最直覺是放進 Git(版本控制工具),但 state 是明文,第 10 篇實測裡面就存著建立者的 email,而且兩個人各改一份會互相蓋掉。所以 Terraform 提供 backend 設定,把 state 存到有權限控管的地方,Cloud Storage 的
gcs、AWS 的 S3 都是其中一種 - 為什麼要學:團隊一起用 Terraform 的第一步就是設好 backend。證照題目看到「state 檔衝突、遺失、多人協作」,答案都從這裡開始
HashiCorp 的 gcs backend 說明寫了三個重點(2026 年 12 月查官方文件):bucket 要事先建好、這個 backend 支援鎖定、強烈建議 bucket 開版本控管,誤刪或寫壞時才救得回來。
state lock(狀態鎖)是什麼
state lock 是 Terraform 要動 state 之前,先在旁邊放一塊「使用中」的牌子;別人看到牌子就不能動,等你做完拿走牌子,才輪到下一個人。
- 白話:廁所門上的「使用中」
- 生活比喻:同一本帳簿,兩個會計同時寫,數字一定亂掉。規定只有拿到那支筆的人可以寫,寫完把筆放回去
- 來龍去脈:gcs backend 的做法是在 state 旁邊寫一個
default.tflock檔。這篇的錯誤訊息看得出來:Terraform 寫鎖檔時附了「這個檔案不存在才寫」的條件,鎖檔已經存在,條件不成立,Cloud Storage 就回412(HTTP 狀態碼,意思是「你給的前提條件不成立」) - 為什麼要學:apply、destroy 這類會寫 state 的指令都會先拿鎖,實測連 plan 也被擋。鎖被擋下來是保護你,不是壞掉;真正要處理的是「拿著鎖的人已經不在了」那一種
module(模組)是什麼
module(模組)是一包可以重複使用的 Terraform 設定:把幾個資源和公司的規定寫在一個資料夾,其他地方用 module 區塊叫它,只要傳幾個參數。
- 白話:公司的標準表單範本,大家照填,不用每次重畫表格
- 生活比喻:系統家具的標準櫃。尺寸、板材、防撞角都先定好,每個房間只要說「放 2 個、白色」。哪天規定改成全部加門擋,改型錄一次,之後訂的櫃子全都有
- 來龍去脈:其實第 10 篇寫的那個資料夾就已經是模組,叫根模組(root module,你下指令的那個資料夾);被它叫的叫子模組(child module)。子模組可以放在本機另一個資料夾,也可以從 Terraform Registry(provider 和模組的下載站)下載。Google 自己維護的模組放在 Registry 的
terraform-google-modules底下,官方叫它 Terraform blueprints and modules - 為什麼要學:bucket、網路、權限這些東西公司都有規定,寫成模組才能保證每個人建出來都一樣。新版考綱 1.2 把「Terraform modules and blueprints」寫進去了
Infrastructure Manager 是什麼
Infrastructure Manager(常簡稱 Infra Manager)是 Google Cloud 代管的 Terraform 執行服務:你把 Terraform 設定交給它,它在 Cloud Build 裡幫你跑 init、plan、apply,state 和每一次的執行紀錄都由它保管。
- 白話:不用自己按 apply,交給 Google 按,每次按完還留一份紀錄
- 生活比喻:自己記帳 vs 交給會計事務所。你把單據交出去,事務所照規矩入帳,每個月留一份底稿,帳本也是他們保管
- 來龍去脈:它的 API 叫
config.googleapis.com。每一套環境叫一個部署(deployment),每改一次多一個修訂版本(revision,實測叫r-0、r-1…)。底下真正執行 Terraform 的是 Cloud Build(Google 的建置服務,會開一台臨時機器照步驟跑指令,詳見容器系列的 Cloud Build 教學) - 為什麼要學:新版考綱 1.2 直接點名。不想自己顧 state bucket、執行環境和 Terraform 版本的團隊,會走這條路;但它能用的 Terraform 版本有限,這篇實測預設是 1.5.7
下面幾個名詞先看過去,動手做時會一個一個遇到:
| 名詞 | 白話 | 這篇的例子 |
|---|---|---|
| prefix | state 在 bucket 裡的資料夾名稱 | app,state 會是 app/default.tfstate |
default.tflock | 鎖檔,有人在改 state 時才存在 | 實測 A 等 yes 的時候一直在 |
| 版本控管(Object Versioning) | Cloud Storage 把被蓋掉、被刪掉的檔案留成舊版本 | state 留了 3 個版本 |
| generation | Cloud Storage 每個檔案版本的編號 | default.tfstate#1796406067242927 |
| serial | state 自己的流水號,每寫一次加 1 | 1、4、5 |
| 軟刪除(soft delete) | 刪掉的檔案先放回收區幾天,可以救回來 | 新 bucket 預設 7 天 |
| 服務帳戶(service account) | 給程式用的帳號,不是給人登入的 | do-11-im,給 Infra Manager 用 |
自己跑 Terraform、Infrastructure Manager、Config Connector 怎麼選
這三種都能「用程式碼管 GCP 資源」,差在誰來執行、state 放哪、要準備什麼環境。表格裡的 CI(持續整合,Continuous Integration)是程式一推上 Git 就自動跑檢查、部署的流程;Kubernetes 是管理大量容器的平台,GKE 是 Google 代管的 Kubernetes;YAML 是用縮排寫設定的文字格式。

| 自己跑 terraform | Infrastructure Manager | Config Connector | |
|---|---|---|---|
| 寫法 | Terraform(.tf) | Terraform(.tf) | Kubernetes 的 YAML |
| 誰執行 | 你的終端機或 CI,用你的帳號或 CI 的身分 | Cloud Build,用你指定的服務帳戶 | Kubernetes 叢集裡的控制器(一直在跑的小程式) |
| state | 自己設 backend,例如這篇的 gcs | Google 代管,設定裡不能寫 backend | 沒有 Terraform state,Kubernetes 裡的 YAML 就是「應該長怎樣」 |
| 版本 | 自己裝什麼就用什麼(實測 1.17.3) | 只能選它支援的(實測預設 1.5.7) | 跟著 Config Connector 版本 |
| 要先準備 | state bucket、執行環境 | 開 API、服務帳戶和權限 | 一個 Kubernetes 叢集(例如 GKE) |
| 適合 | 已經有 CI/CD、要用最新版 Terraform | 不想自己顧執行環境,要每次執行都有紀錄 | 團隊已經用 Kubernetes、想用同一套方式管雲端資源 |
Config Connector 是 Google 官方說的「Kubernetes 外掛(add-on)」,用 Kubernetes 的方式管 GCP 資源,這篇沒有實測,觀念可以看站上的〈Config Connector 是什麼東東?如何使用?〉。
動手做:state 搬上 Cloud Storage、兩個人搶鎖、模組、Infra Manager
做完之後,你的專案裡會有:一個放 state 的 bucket、三個用模組建的 bucket、一個由 Infrastructure Manager 建的 Artifact Registry 存放區(放容器映像檔的地方),最後全部刪掉。
- 在哪裡做:Cloud Shell(Google 提供、開瀏覽器就能打指令的 Linux 終端機),專案 dong-dong-gcp-3,區域
asia-east1(台灣彰化)。怎麼開 Cloud Shell 在第 1 篇 - 要先裝好 Terraform:Cloud Shell 從 2026 年 6 月 20 日起不內建 Terraform(Cloud Shell 版本資訊),你的 Cloud Shell 如果還沒裝過,照步驟 1 的三行指令裝。Cloud Shell 只保留家目錄(官方說明),用 apt 裝的 Terraform 在機器被回收、重新開一台之後就不在了,看到安裝說明就重裝一次。我的機器上第 10 篇裝的 1.17.3 剛好還在,這次直接用
- 花多久:我實測從建 bucket 到刪乾淨約 23 分鐘,其中 Infrastructure Manager 建立 3 分 46 秒、刪除 41 秒;第一次邊讀邊做,預留 1 小時
- 權限:最簡單是專案擁有者(Owner),自己建的練習專案,建立者預設就是 Owner;不確定的話,到 Console 的「IAM 與管理」頁面找自己的帳號看角色。不是 Owner 的話,要能建 bucket(
roles/storage.admin)、建服務帳戶並給它權限(roles/iam.serviceAccountAdmin、roles/resourcemanager.projectIamAdmin)、用 Infrastructure Manager(roles/config.admin),而且要能「以那個服務帳戶的身分執行」(roles/iam.serviceAccountUser)(2026 年 12 月查官方文件) - API:Infrastructure Manager 要開
config.googleapis.com,底下會用到 Cloud Build。我的專案之前已經開好,這次沒有重跑;你的專案沒開的話,官方的指令是gcloud services enable config.googleapis.com,開法跟第 10 篇步驟 3 一樣。開 API 本身也要權限(例如roles/serviceusage.serviceUsageAdmin),不是 Owner 的話請管理員先幫忙開 - 會不會花錢:幾乎不會。空的 bucket 不收儲存費,state 檔只有幾 KB;Infrastructure Manager 用 1.5.7 不收管理費,只照 Cloud Build 執行時間和 Cloud Storage 用量收(實測 Cloud Build 跑 35 秒);Artifact Registry 存放區是空的。另外 Infrastructure Manager 部署時會自動多出兩個 bucket,刪部署不會跟著刪,處理方式在「用完記得刪」最後一節
- 中途斷線:重新連上後先
cd ~/do-11,再重跑步驟 1 的export那一行
下面每段指令都是整段複製、貼進 Cloud Shell、按 Enter,等結尾是 $ 的提示字元再出現就是跑完了。截圖裡的提示字元有縮短,你的畫面會是「你的帳號@cloudshell:~/do-11 (專案ID)$」。這篇建的東西一律 do-11- 開頭,下面指令裡的 dong-dong-gcp-3 都要換成你的專案 ID。
步驟 1:建練習資料夾、確認 Terraform 版本
先建資料夾。第二行的 TF_PLUGIN_CACHE_DIR 是讓 Terraform 把下載的 provider(Terraform 跟 GCP 溝通的外掛)放在一個共用位置:第 10 篇實測 google provider 一個就 135 MB,這篇會有兩個資料夾各自 init,共用之後只下載一次。Cloud Shell 的家目錄只有 5 GB,省一點比較安全。$HOME 是你的家目錄。這行設定關掉 Cloud Shell 就會消失,沒重跑也不會壞,只是會多下載一次 provider:
mkdir -p ~/do-11/.plugin-cache && cd ~/do-11
export TF_PLUGIN_CACHE_DIR=$HOME/do-11/.plugin-cache
terraform version
Terraform v1.17.3
on linux_amd64

如果看到的是一段安裝說明,代表這台 Cloud Shell 還沒裝 Terraform。照 Cloud Shell 印出來的說明,跑下面三行(第 10 篇步驟 2 實測過,第 1 行下載 HashiCorp 的簽章金鑰、第 2 行加入它的軟體來源、第 3 行安裝,sudo 是用管理員權限執行,Cloud Shell 不用輸入密碼),最後出現 Setting up terraform 就裝好了,再跑一次 terraform version:
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 '(?<=UBUNTU_CODENAME=).*' /etc/os-release || lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/hashicorp.list
sudo apt update && sudo apt install -y terraform
步驟 2:先用 gcloud 建放 state 的 bucket,開版本控管
state bucket 要在 Terraform 之外先建好,理由有兩個:HashiCorp 文件寫明 backend 用的 bucket 必須事先存在;而且這個 bucket 如果由同一份 Terraform 管,哪天有人跑 terraform destroy,記帳本會跟著被刪。有些網路教學用 Terraform 建 state bucket 還加上 force_destroy = true(destroy 時連裡面的檔案一起刪),Google 官方範例則是設 false,這篇乾脆用 gcloud 建。
bucket 名稱全世界不能重複,所以把專案 ID 放進去:
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)'
--uniform-bucket-level-access:權限統一用 IAM(GCP 的權限系統)在 bucket 層級管,不能對單一檔案另外開權限--public-access-prevention:禁止把這個 bucket 公開到網路上。state 是明文,絕對不能公開--versioning:開版本控管,state 被蓋掉時舊的那份會留下來
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

我沒設軟刪除,輸出卻多了一段 soft_delete_policy:這是 Cloud Storage 新 bucket 的預設行為,刪掉的檔案會先留一段時間。算一次:604800 秒 ÷ 86,400 秒(一天)= 7 天。這 7 天內被刪的檔案還救得回來,但也照儲存量收費。
步驟 3:寫一個 bucket 模組,再寫要用它的根模組
這篇的資料夾長這樣:modules/bucket/ 是子模組,寫「公司規定的 bucket 長什麼樣」;app/ 是根模組,負責叫它。
先寫子模組的 3 個檔。main.tf 把規定寫死:統一權限、禁止公開、一定要貼 env 和 managed-by 標籤。注意它只宣告需要 google provider,沒有寫 provider 區塊,provider 由叫它的根模組決定,HashiCorp 也是這樣建議的:
cd ~/do-11
mkdir -p modules/bucket app
cat > modules/bucket/main.tf <<'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
variables.tf 是模組開放給外面填的欄位。有 default 的可以不填,project_id 和 name 沒有預設值,叫它的人一定要給:
cat > modules/bucket/variables.tf <<'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
outputs.tf 是模組建好之後要交回去的值,根模組用 module.名稱.輸出名稱 拿:
cat > modules/bucket/outputs.tf <<'EOF'
output "name" {
value = google_storage_bucket.this.name
}
output "url" {
value = google_storage_bucket.this.url
}
EOF
再寫根模組。module "logs" 和 module "assets" 叫的是同一個子模組(source = "../modules/bucket",意思是「上一層的 modules/bucket 資料夾」),只差在名稱和要不要開版本控管:
cd ~/do-11/app
cat > main.tf <<'EOF'
terraform {
required_providers {
google = {
source = "hashicorp/google"
version = "~> 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 > terraform.tfvars <<'EOF'
project_id = "dong-dong-gcp-3"
EOF
cd ~/do-11; find . -name '*.tf*' -not -path '*/.*' | sort; cd app
./app/main.tf
./app/terraform.tfvars
./modules/bucket/main.tf
./modules/bucket/outputs.tf
./modules/bucket/variables.tf

步驟 4:terraform init,多了一段 Initializing modules
terraform init
Initializing the backend...
Initializing modules...
- logs in ../modules/bucket
- assets in ../modules/bucket
Initializing provider plugins...
- Finding hashicorp/google versions matching "~> 8.0"...
- Installing hashicorp/google v8.12.0...
- Installed hashicorp/google v8.12.0 (signed by HashiCorp)
(中間省略)
Terraform has been successfully initialized!

跟第 10 篇比,多了 Initializing modules:Terraform 先找到 logs、assets 兩個模組的位置。以後加了新模組、或改了 source,都要重跑一次 terraform init,輸出最後一段也這樣提醒。
步驟 5:plan,看資源的新名字
grep 是只挑出含特定文字的行,這裡只看每個資源的標題和最後一行:
terraform plan | grep -E '# |Plan:'
# 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.

資源的名字變成 module.logs.google_storage_bucket.this:前面多了「從哪個模組來的」。模組裡只寫了一個 this,叫兩次就是兩個資源,各自有自己的地址。
步驟 6:apply,state 還在本機
-auto-approve 是不問 yes 直接做,步驟 5 已經看過 plan 才這樣用;tail -12 只看最後 12 行:
terraform apply -auto-approve | tail -12; ls; terraform state list
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

兩個 bucket 2~3 秒建好。注意 ls 那一行:terraform.tfstate 還在本機資料夾,這就是下一步要搬走的記帳本。
步驟 7:加上 backend,把 state 搬上 Cloud Storage
新增一個 backend.tf,寫上 bucket 和 prefix。backend 區塊不能用變數,HashiCorp 文件寫明它不能引用 variable、local 這類值,所以 bucket 名稱要直接寫死。
cat > backend.tf <<'EOF'
terraform {
backend "gcs" {
bucket = "do-11-dong-dong-gcp-3-tfstate"
prefix = "app"
}
}
EOF
terraform init -migrate-state
-migrate-state 是「換 backend 時,把舊的 state 搬過去」。Terraform 會停下來問你:
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:
意思是:本機有一份 state,新的 gcs 那邊還沒有,要不要複製過去?打 no 會從空的記帳本開始,Terraform 就忘了那兩個 bucket。這裡打 yes:
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!

步驟 8:本機剩什麼?雲端多了什麼?
wc -c 是算檔案有幾個位元組(bytes):
ls; wc -c terraform.tfstate*; gcloud storage ls gs://do-11-dong-dong-gcp-3-tfstate/app/; terraform state list
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

三件事:
- state 搬上去了:bucket 裡多了
app/default.tfstate。app是 prefix,default是預設的工作區(workspace,同一份設定可以有多本 state,這篇不用) - 本機的
terraform.tfstate變成 0 bytes,Terraform 現在去 Cloud Storage 讀寫 - 本機還留著 5,935 bytes 的
terraform.tfstate.backup,裡面是搬家前的完整 state。第 10 篇實測 state 會明文存敏感資料,所以這個備份檔不要放進 Git,確認搬好之後自己刪掉
權限也要跟著想:從現在開始,能讀這個 bucket 的人就能讀到 state 全文。HashiCorp 文件寫的是,存取 state 的身分要有 bucket 的 Storage 物件管理員(roles/storage.objectAdmin),只給需要跑 Terraform 的人。
步驟 9:模擬同事 B,開另一個資料夾接同一份 state
真實情況裡 B 在自己的電腦,從 Git 拉下同一份設定。這裡用同一台 Cloud Shell 的另一個資料夾 app-b 模擬。步驟 9 到 15 會有兩個人,先記住誰在哪:
| 角色 | 在哪個分頁打指令 | 資料夾 |
|---|---|---|
| A(你) | 分頁 1,就是你現在用的這個 | ~/do-11/app |
| B(同事) | 分頁 2,步驟 11 才開 | ~/do-11/app-b |
在 A 的分頁,複製設定檔到 app-b(不複製 state),在那裡 init,再回到 app:
mkdir -p ../app-b && cp main.tf backend.tf terraform.tfvars ../app-b/ && cd ../app-b && terraform init | grep -E 'backend|initialized' ; cd ../app
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,

B 沒有 state 檔,但接上了同一個 bucket,看到的是同一本記帳本。這裡沒有複製 modules 資料夾也能 init,是因為 app-b 和 app 在同一層,../modules/bucket 剛好指到同一個地方。
步驟 10:A 開始 apply,停在等 yes
在 A 的分頁,把環境標籤從 dev 改成 test,跑到它問 yes 時先不要回答:
terraform apply -var=env=test
# 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:

重點:從這一刻起,A 就拿著鎖了。 等 yes 的這段時間,鎖一直在。所以 apply 不要開著去吃飯,同事會整個卡住。
步驟 11:B 同時跑 plan,被鎖擋下
A 的分頁保持不動,按 Cloud Shell 終端機上方分頁列的「+」,開出分頁 2 當 B。兩個分頁連的是同一台 Cloud Shell 機器、同一個家目錄。(截圖裡我是用 tmux 把畫面切成上下兩格拍的,上面是 A、下面是 B,效果一樣。tmux 是在一個終端機裡切出多個視窗的工具。)
在 B 的分頁:
cd ~/do-11/app-b
terraform plan
(前面幾行捲出畫面了,完整的開頭在步驟 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.

這段錯誤一行一行看:
Error 412 ... conditionNotMet:B 想寫鎖檔,但鎖檔已經存在,Cloud Storage 拒絕。完整訊息的第一行是Error acquiring the state lock(拿不到鎖),B 什麼都沒改,plan 直接停- Lock Info:誰拿著鎖。
Operation是 apply、Version是 1.17.3、Created是拿鎖的時間(+0000 UTC是世界標準時間,台灣要加 8 小時,也就是凌晨 1:42)。Who是 Cloud Shell 的使用者名稱加機器名稱,截圖裡我換成「你的帳號@cloudshell」 - 最後一段:說你可以用
-lock=false關掉鎖,但「不建議」。關掉鎖就等於拿掉「使用中」的牌子,兩個人真的會同時改
這時候 B 該做的是等 A 做完,或去問 A 在幹嘛。官方文件另外有 -lock-timeout 參數,可以讓 B 等一段時間再放棄(plan 指令說明),這篇沒有實測。
步驟 12:看看鎖檔長什麼樣子
還是在 B 的分頁,列出 bucket 裡的檔案,再印出鎖檔內容:
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
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"}

鎖檔是一小段 JSON(用大括號和「名稱: 值」記資料的文字格式),跟錯誤訊息的 Lock Info 幾乎一樣。但仔細看 ID:鎖檔裡是 aa682a93-... 這種英數字,錯誤訊息裡是 1796406128790709 這種純數字,兩個不一樣。步驟 15 會遇到這個差別。
步驟 13:A 打 no,鎖就消失
回到 A 的分頁,打 no 取消:
Enter a value: no
Apply cancelled.
再到 B 的分頁看一次:
gcloud storage ls gs://do-11-dong-dong-gcp-3-tfstate/app/; terraform plan | tail -3
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.

鎖檔不見了,B 的 plan 也跑得動了。正常結束(做完、取消)時,Terraform 會自己把鎖拿走。
步驟 14:A 的程式被砍掉,鎖留下來
麻煩的是不正常結束:真實情況是網路斷線、電腦當機、CI 工作被取消,程式來不及把鎖拿走。這一步是故意製造這種意外,平常不會這樣做。
在 A 的分頁再跑一次,一樣停在等 yes,不要回答:
terraform apply -var=env=test
到 B 的分頁貼下面這行,把 A 的 terraform 強制結束。這行只在這個練習用,不要拿去公司的機器貼(截圖時我是從另一個連線到同一台 Cloud Shell 的終端機跑的,在 B 的分頁貼效果一樣):
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
這行在做的事:找出「在 ~/do-11/app 資料夾裡跑的 terraform」,只砍它,不會動到 B 自己或其他程式。kill -9 是 Linux 強制結束程式的指令:平常按 Ctrl+C 是請程式自己結束,程式有機會收拾;kill -9 不給它收拾的機會,才做得出「鎖留下來」的情況。輸出是 killed 33319,33319 是那個程式的編號。A 的分頁變成:
Enter a value: Killed
在 B 的分頁再跑一次 plan:
terraform plan
╷
│ 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

A 已經不在了,鎖還在。這把鎖不會自己消失,沒人處理,整個團隊都不能 apply。
步驟 15:用 force-unlock 解鎖,第一次就用錯 ID
terraform force-unlock 是手動把鎖拿掉,-force 是不再問一次確認。以下都在 B 的分頁做。
先照直覺,再看一次鎖檔裡的 ID:
gcloud storage cat gs://do-11-dong-dong-gcp-3-tfstate/app/default.tflock; echo
這是步驟 14 新留下的那把鎖,所以 ID 跟步驟 12 不一樣,這次是 665f17a4-d69a-e4a9-7653-5ab5b3411de9(其他欄位的格式跟步驟 12 一樣)。拿它來解鎖:
terraform force-unlock -force 665f17a4-d69a-e4a9-7653-5ab5b3411de9
Failed to unlock state: Lock ID should be numerical value, got '665f17a4-d69a-e4a9-7653-5ab5b3411de9'
失敗了:gcs backend 要的是數字。改用錯誤訊息 Lock Info 裡的 ID,這串數字要換成你自己步驟 14 錯誤訊息裡的那個:
terraform force-unlock -force 1796406284140647
gcloud storage ls gs://do-11-dong-dong-gcp-3-tfstate/app/
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

這個數字是什麼?到步驟 28 刪 bucket 時列出所有版本,會看到 default.tflock#1796406284140647:它就是那個鎖檔在 Cloud Storage 的 generation(版本編號)。所以記住:gcs backend 解鎖,用錯誤訊息裡的數字,不要去翻鎖檔。
force-unlock 的官方說明也提醒:只有確定拿鎖的人已經不在了才能用。A 如果其實還在跑,你把鎖拿掉,兩個人就會同時改 state。實務上先在群組問一聲「誰在 apply?」再解鎖。
步驟 16:換用官方 Registry 模組
自己寫的模組適合放公司規定;常見的東西也可以直接用 Google 維護的。這裡用 Registry 上的 terraform-google-modules/cloud-storage/google 多建一個 bucket。新增 registry.tf:
cd ~/do-11/app
cat > registry.tf <<'EOF'
# 官方 Registry 上 Google 維護的 Cloud Storage 模組
module "shared" {
source = "terraform-google-modules/cloud-storage/google"
version = "~> 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
source不是資料夾路徑,而是 Registry 上的名字(組織/模組名/provider)version = "~> 12.4":用 12.4 以上、13.0 以下的版本。Registry 模組一定要寫 version,不然作者改了大版本,你下次 init 就默默換掉(HashiCorp 建議)public_access_prevention = "enforced":這行是我特別加的,原因寫在這一步的最後
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 ">= 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

兩個重點:
- 抓到 12.4.1,下載到
.terraform/modules/shared,是一整包有文件、範例的專案 - 多裝了一個
hashicorp/randomprovider:這個模組會用亂數幫 bucket 名稱加尾巴(預設randomize_suffix = false,沒開),但它宣告需要 random,所以 init 就會裝
我看了模組的原始碼:public_access_prevention 預設是 inherited(照組織的規定走,組織沒規定就允許公開),跟我自己模組寫死的 enforced 不一樣。用別人的模組前,先看預設值合不合你的規定,這就是我多加那一行的原因。

步驟 17:plan,看 Registry 模組的資源名稱
terraform plan | grep -E '# |Plan:'
# module.shared.google_storage_bucket.buckets["shared"] will be created
Plan: 1 to add, 0 to change, 0 to destroy.
![terraform plan 顯示 module.shared.google_storage_bucket.buckets["shared"] will be created,Plan: 1 to add](https://dongdonggcp.com/wp-content/uploads/2026/12/do11-shots-18-registry-plan.png)
資源叫 buckets["shared"]:這個模組用一份設定建很多個 bucket,names 裡有幾個名字就建幾個,用名字當索引。bucket 名稱是模組用 - 把 prefix 和 names 接起來,結果是 do-11-dong-dong-gcp-3-shared。
步驟 18:apply,三個資源都在同一本帳
terraform apply -auto-approve | grep -E 'Creat|Apply'; terraform state list
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"]

自己寫的模組和 Registry 模組建的資源,記在同一本 state 裡。這次 apply 有寫 state,也有拿鎖、放鎖,過程很快所以看不到。
步驟 19:看 state 留了幾個版本
步驟 2 開了版本控管,每次 state 被蓋掉,舊的都會留下。gcloud storage ls -a 會列出所有版本(# 後面就是 generation),再從每個版本裡挑出 serial(state 的流水號):
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
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

三個版本,各代表一次寫入:
- serial 1:步驟 7 的 init 一接上 gcs,就先寫了一份空的 state(我另外查了大小,只有 181 bytes、0 個資源),這時我還沒打 yes
- serial 4:打 yes 之後,從本機搬上來的那份(本機是 3,搬上來加 1)。generation 的數字看起來是寫入時間(微秒),這兩個相差約 11.6 秒,正好是我讀提示、打 yes 的時間
- serial 5:步驟 18 加了
sharedbucket 之後
步驟 10 和 14 的 apply 都沒有真的做(取消、被砍),所以沒有留下版本。哪天 state 被寫壞,就是從這些舊版本救回來。
步驟 20:換 Infrastructure Manager,先看它支援哪些 Terraform 版本
接下來改用 Infrastructure Manager。先看它在台灣區域支援哪些 Terraform 版本:
gcloud infra-manager terraform-versions list --location=asia-east1
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

能用的只有 4 個版本,最新是 1.16.5,沒有我在 Cloud Shell 用的 1.17.3。這跟授權有關:Terraform 1.5.7 以前是開源授權(MPL 2.0),之後改成 BSL(Business Source License,一般使用免費,但限制拿來做跟 HashiCorp 競爭的商業服務)。對你來說重點只有一個:用 1.5.7 以前的版本不收管理費,新版要收;計費頁寫明 1.5.7 以前不收管理費,1.16.5 以後要照管理的資源數收費(2026 年 12 月查官方文件)。沒指定版本時,預設用免費的 1.5.7。
步驟 21:建一個服務帳戶給 Infrastructure Manager 用
服務帳戶(service account)是給程式用的帳號,不是給人登入的;IAM 角色(role)是「這個帳號能做哪些事」的權限清單。Infrastructure Manager 不用你的帳號跑 Terraform,而是用你指定的服務帳戶,所以要先建一個,再給它兩種角色:
roles/config.agent:讓 Infrastructure Manager 能用它的身分執行(官方規定一定要有)- 設定裡要建的資源的權限:這篇要建 Artifact Registry 存放區,所以給
roles/artifactregistry.admin。正式環境要照實際要建的東西給最小權限
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
--condition=None:這個權限不加條件。專案裡已經有「有條件的權限」時,不寫這個 gcloud 會停下來問你--format=none:不印出整份專案權限清單,那份清單裡會有其他人的 email
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].

步驟 22:寫設定、交給 Infrastructure Manager 部署
開一個新資料夾放要交出去的設定。跟步驟 3、7 的設定最大的差別:這份設定裡沒有 backend 區塊。官方文件寫明 state 由 Infrastructure Manager 管,設定裡不要寫 backend。最後的部署指令會跑 3~4 分鐘,畫面一直印點點點是正常的,不要按 Ctrl+C 中斷。
mkdir -p ~/do-11/im && cd ~/do-11/im
cat > main.tf <<'EOF'
terraform {
required_providers {
google = {
source = "hashicorp/google"
version = "~> 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
部署指令有點長,拆開看:
deployments apply projects/.../locations/asia-east1/deployments/do-11-im:建立(或更新)一個叫do-11-im的部署,放在台灣區域--service-account=:用步驟 21 的服務帳戶,要寫完整的projects/專案/serviceAccounts/email格式--local-source=.:把目前資料夾(.)的設定上傳上去。也可以改用 Git repo 或 Cloud Storage 當來源--input-values=project_id=...:幫project_id這個變數填值,等於自己跑時的terraform.tfvars- 前後的
date +%T是印出當下時間,算花了多久
01:48:41
Uploading 1 file(s) totalling 592 bytes.
Creating the deployment...
(中間是一長串點點點,省略)
.......done.
01:52:27

從 01:48:41 到 01:52:27,花了 3 分 46 秒。 自己跑 apply 建一個 bucket 只要 2 秒,這裡建一個空的存放區卻要將近 4 分鐘,原因在步驟 24。
步驟 23:看部署的結果
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)'
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

tfVersion: 1.5.7:沒指定版本,用的就是預設的免費版r-0 APPLIED:第一個修訂版本,套用成功。之後每改一次設定再 apply,會多一個r-1、r-2artifactsGcsBucket:Infrastructure Manager 自動建的 bucket,名稱是「專案編號-區域-blueprint-config」,放每次執行的紀錄和設定- 存放區的標籤多了
goog-ccm=true:我只寫了managed-by。goog-terraform-provisioned是 google provider 自己加的(第 10 篇遇過),goog-ccm是第 10 篇自己跑 apply 時沒出現過的,透過 Infrastructure Manager 建才多了它
在 Console 也看得到。上方搜尋列打「Infrastructure Manager」進去,部署清單裡有 do-11-im,狀態「已建立」:

點進去是部署的詳細資料:State 顯示「有效」(就是 gcloud 看到的 ACTIVE),Terraform Version 是 1.5.7,下面有「總覽、資源、修訂版本、預覽、輸入內容、輸出內容」幾個分頁,右上角可以直接看 Cloud Build 記錄:

步驟 24:看 Cloud Build 裡到底跑了什麼
每次執行的紀錄都放在 artifactsGcsBucket 裡,路徑是「部署名稱/修訂版本/logs」。下面的 600195576280 是我的專案編號(不是專案 ID),換成你步驟 23 輸出裡的那個:
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/
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

這份紀錄回答了三個問題:
- 它做的事跟你自己做的一樣:
init→validate(檢查語法)→plan存成檔案 →apply那個計畫檔。先存計畫再套用,確保套用的就是剛剛算出來的那份 - state 去哪了:
Successfully configured the backend "http"。Infrastructure Manager 自己幫你接了一個 http backend,所以你的設定不能再寫 backend - 為什麼要等 3 分 46 秒:Terraform 從 17:51:39 跑到 17:51:58,真正建存放區只花 10 秒。我用
gcloud builds list查,這次 Cloud Build 從開始到結束 35 秒,其他時間是部署建立後、建置開始前的等待
apply_results/content/ 裡有 .terraform.lock.hcl:我設定寫 ~> 8.0,它在 Terraform 1.5.7 底下裝的也是 google provider 8.12.0,舊版 Terraform 照樣能用新版 provider。
用完記得刪
這篇建了四類東西:Infrastructure Manager 部署(含存放區)、服務帳戶和它的權限、三個模組建的 bucket、放 state 的 bucket。刪的順序要倒過來:state bucket 一定最後刪,不然 Terraform 就找不到記帳本,沒辦法用 destroy 刪那三個 bucket。
不刪的話會怎麼收費:
- bucket:空的不收錢。放了檔案,台灣
asia-east1的 Standard 儲存是每 GiB 每月 0.020 美元(第 10 篇查的 Cloud Storage 定價)。算一次:state 只有幾 KB;假設一個大專案的 state 長到 1 MiB、留了 100 個舊版本,總共 100 MiB 約 0.1 GiB,0.1 × 0.020 = 每月約 0.002 美元。花不了幾個錢,比較要在意的是舊版本裡也有明文的敏感資料,所以正式環境建議設生命週期規則,用daysSinceNoncurrentTime(變成舊版本幾天後)或numNewerVersions(後面已經有幾個新版本)自動清掉太舊的版本 - Infrastructure Manager:用 1.5.7 不收管理費。只照 Cloud Build 執行時間收,每個帳單帳戶每月有 2,500 分鐘免費建置時間(限預設集區的 e2-standard-2 機型),排隊的時間不算(Cloud Build 定價,2026 年 12 月查)
- 如果用付費的 1.16.5:每個帳單帳戶每月 500 個資源免費,超過的每個資源一年 1 美元,按秒計(計費頁)。算一次:假設公司用 1.16.5 管 800 個資源一整個月,超過的是 800 − 500 = 300 個;300 × 1 美元 ÷ 12 個月 ≈ 每月 25 美元。預覽(preview)不收管理費,只有真正 apply 的資源才算
- Artifact Registry 存放區:空的不收儲存費,推了映像檔才照容量收
- 服務帳戶:免費,但留著一個有
artifactregistry.admin權限的帳號沒人管,是資安風險
步驟 25:刪掉 Infrastructure Manager 部署
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'
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.

刪部署花了 41 秒,它建的存放區也一起刪掉了(Listed 0 items)。這是預設行為;gcloud infra-manager deployments delete 另外有 --delete-policy 參數,可以選 abandon(只刪部署紀錄、資源留著),這篇沒有用。
步驟 26:拿掉權限、刪服務帳戶
先拿掉權限再刪帳號,不然專案的權限清單裡會留下「已刪除的帳號」:
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
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]

步驟 27:terraform destroy,刪掉三個模組建的 bucket
cd ~/do-11/app && terraform destroy -auto-approve | grep -E 'Destr|Plan'
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.

三個 bucket 都是空的,各 1 秒刪完。bucket 裡有檔案的話,Terraform 預設會刪不掉,這是保護,不要為了好刪就加 force_destroy = true。
步驟 28:刪掉 state bucket,連舊版本一起刪
開了版本控管的 bucket,要加 --all-versions 才會連舊版本一起刪。先列一次所有版本,再刪:
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)'
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/...

12 個版本,其中 8 個是鎖檔。 每次拿鎖會寫一個鎖檔、放鎖會刪掉它,開了版本控管,被刪的鎖檔也留成舊版本。第三行的 1796406128790709 就是步驟 11 錯誤訊息裡的鎖 ID,第五行的 1796406284140647 是步驟 15 解掉的那把。最後一行 buckets list 沒有印出任何東西,代表 do-11- 開頭的 bucket 都刪光了。
被刪的檔案會照步驟 2 的軟刪除設定再留 7 天,這段期間照儲存量計費,這裡只有幾 KB,可以忽略。
步驟 29:刪掉練習資料夾
本機的 terraform.tfstate.backup(步驟 8 那份 state 全文)也在裡面,一起刪:
cd ~ && rm -rf ~/do-11 && ls -d ~/do-11
ls: cannot access '~/do-11': No such file or directory

Infrastructure Manager 自動建的兩個 bucket
部署時 Infrastructure Manager 和 gcloud 自動建了兩個 bucket,刪部署時不會跟著刪,名字也不是 do-11- 開頭:
專案編號-asia-east1-blueprint-config:放執行紀錄。刪完部署還留著archived-deployments/do-11-im_.../一包刪除時的紀錄專案ID_infra_manager_staging:--local-source上傳設定用的暫存區
我用 gcloud storage du -s 看了大小:
27416 gs://600195576280-asia-east1-blueprint-config
0 gs://dong-dong-gcp-3_infra_manager_staging
一個 27 KB、一個是空的,儲存費可以忽略。這個專案以後還會用 Infrastructure Manager 的話,留著就好;確定不用了,可以用步驟 28 同樣的 gcloud storage rm --recursive 刪掉。專案裡有其他 Infrastructure Manager 部署時不要刪,那是大家共用的紀錄。
實測時的意外
1. 搬完 state,本機還留一份全文:
-migrate-state之後terraform.tfstate變 0 bytes,但多了 5,935 bytes 的terraform.tfstate.backup,就是搬家前的完整 state,要自己刪(步驟 8)。2. force-unlock 要用數字 ID,不是鎖檔裡的 ID:鎖檔 JSON 裡的
ID是665f17a4-...這種英數字,拿去 force-unlock 會回Lock ID should be numerical value;要用錯誤訊息 Lock Info 的數字,它其實是鎖檔在 Cloud Storage 的 generation(步驟 15、28)。3. 等 yes 的時候就拿著鎖:apply 停在
Enter a value的時候,鎖已經在了,同事連 plan 都跑不了(步驟 10、11)。4. 版本控管也把鎖檔留下來了:刪 bucket 前列出 12 個版本,8 個是鎖檔、4 個是 state(步驟 28)。
5. 第一個 state 版本是空的:init 一接上 gcs 就先寫了一份 181 bytes 的空 state(serial 1),打 yes 之後才寫入搬上來的那份(serial 4)(步驟 19)。
6. 官方 Registry 模組的預設不一定是你要的:
public_access_prevention預設inherited,不是enforced;而且就算沒開隨機尾巴,init 也會多裝一個 random provider(步驟 16)。7. Infrastructure Manager 建一個空存放區要 3 分 46 秒:Terraform 本身只跑了約 20 秒、建資源 10 秒,大部分時間在等建置開始(步驟 22、24)。
8. 不能用最新版 Terraform:支援清單最新是 1.16.5(要付費),預設 1.5.7;Cloud Shell 自己裝的 1.17.3 不在清單上(步驟 20)。
9. 刪部署會連資源一起刪,但留下兩個 bucket:存放區跟著刪了,
blueprint-config和infra_manager_staging兩個 bucket 還在(步驟 25 之後)。10. 文件有的參數,gcloud 還沒有:Infrastructure Manager 官方文件提到
--provider-source,但 Cloud Shell 的 gcloud 594.0.1 跑gcloud infra-manager deployments apply --help找不到這個參數(2026 年 12 月 5 日實測)。
證照會怎麼考
Professional Cloud DevOps Engineer 考試 2 小時、50~60 題選擇題、報名費 200 美元,考試語言英文和日文(2026 年 11 月查官方考試頁)。2026 年 11 月 23 日起適用新版考綱。
| 考綱小節(新版) | 原文重點 | 這篇對應的地方 |
|---|---|---|
| 1.2 管理基礎架構 | IaC 工具與代管服務(Application Design Center、Infrastructure Manager、Config Connector、GitOps、Terraform、Helm) | 步驟 20~25;三種工具怎麼選 |
| 1.2 | 用 Google 建議的做法和藍圖改基礎架構(Terraform modules and blueprints) | 步驟 3~6 自己寫模組;步驟 16~18 用 Google 維護的模組 |
| 1.4 管理多個執行環境 | 短暫環境(ephemeral environments)、設定與政策(configuration and policy) | 同一個模組換 env;backend 用不同 prefix 分開各環境的 state |
| 2.1 建置管線 | 應用程式和基礎架構的 CI/CD | Infrastructure Manager 用服務帳戶在 Cloud Build 跑、每次留修訂版本;CI 裡跑 Terraform 一定要遠端 state 加鎖 |
看到這些字,就想到這個(情境題的判斷關鍵字):
| 題目關鍵字 | 想到 |
|---|---|
| 「團隊多人一起改」「state 檔衝突、遺失」 | 遠端 state:backend "gcs",bucket 開版本控管 |
| 「兩個人同時 apply」「避免同時修改」 | state lock(gcs backend 內建) |
| 「apply 中斷後一直顯示 state 被鎖住」 | 先確認沒人在跑,再 terraform force-unlock |
| 「state 被誤刪、寫壞要還原」 | Cloud Storage 版本控管的舊版本 |
| 「state 有敏感資料」 | bucket 禁止公開、只給需要的人權限,不放 Git |
| 「同樣的資源設定在很多專案重複」「統一公司規範」 | Terraform modules |
| 「用 Google 建議的做法」「藍圖」 | Google 維護的 Terraform blueprints and modules(terraform-google-modules) |
| 「Google 代管」「不想自己架 Terraform 執行環境」「保留每次部署紀錄」 | Infrastructure Manager |
| 「用 Kubernetes 的方式管 GCP 資源」 | Config Connector |
| 「dev、staging、prod 各自的 state」 | 不同的 prefix(或不同的 bucket),同一份模組 |
考試範圍完整的準備地圖在第 1 篇:GCP DevOps 證照怎麼考?2026 新版考綱、比重與準備地圖。
面試會怎麼問
- 「Terraform state 你們放哪?為什麼?」:放 Cloud Storage(
backend "gcs"),因為要多人共用、要加鎖、要能還原。bucket 用 gcloud 事先建好、開版本控管、禁止公開、只給跑 Terraform 的身分權限 - 「遇過 state lock 卡住嗎?怎麼處理?」:先看錯誤訊息的 Lock Info 是誰、什麼時候拿的,去問本人或看 CI 工作是不是還在跑;確定沒人在用,才用
terraform force-unlock加錯誤訊息裡的 ID 解鎖。gcs backend 的 ID 是數字 - 「本機的 state 怎麼搬到遠端?」:加 backend 區塊,跑
terraform init -migrate-state,回答 yes;搬完確認state list一樣、把本機留下的.backup刪掉 - 「什麼時候該寫模組?」:同一種資源在很多地方用、而且有公司規定要統一的時候。用別人的模組要鎖版本、先看預設值
- 「Infrastructure Manager 跟自己在 CI 跑 Terraform 差在哪?」:Infrastructure Manager 幫你管執行環境和 state、每次留修訂版本,但能用的 Terraform 版本有限(預設 1.5.7)、每次執行要等幾分鐘;自己跑彈性大,但 state bucket、權限、執行環境都要自己顧
常見問答
terraform state 要放在哪裡比較好?
一個人練習放本機就好;團隊一起用,要放在大家都拿得到、有權限控管、能加鎖的地方。在 GCP 上最常見的是 Cloud Storage,用 backend "gcs" 設定。bucket 要事先建好、開版本控管、禁止公開。不建議放 Git,因為 state 是明文,而且 Git 沒有鎖定機制。
兩個人同時 terraform apply 會怎樣?
用支援鎖定的 backend(例如 gcs)時,後到的人會被擋下來。實測 A 的 apply 停在等 yes 的時候,B 跑 plan 就出現 Error acquiring the state lock 和 Error 412 ... conditionNotMet,什麼都沒改。A 做完或取消後,鎖檔消失,B 就能繼續。如果 state 放在各自的本機,兩個人看到的記帳本不一樣,各改各的,雲端上的資源跟兩本帳都對不起來。
出現 Error acquiring the state lock 怎麼辦?
先看錯誤訊息裡的 Lock Info:誰(Who)、什麼操作(Operation)、什麼時候(Created)。對方還在跑就等他做完。確定對方的程式已經中斷(例如被強制結束、CI 工作被取消),再用 terraform force-unlock 加 Lock Info 裡的 ID 解鎖。gcs backend 的 ID 是一串數字,用鎖檔 JSON 裡的英數字 ID 會失敗。
backend 區塊可以用變數嗎?
不行。HashiCorp 官方文件寫明 backend 區塊不能引用變數、local 這類值,所以 bucket 名稱要直接寫死在設定檔。要讓不同環境用不同的 bucket,可以在 terraform init 時用 -backend-config 從外面帶,但不要把金鑰之類的憑證這樣傳,官方提醒它會被寫進 .terraform 資料夾和計畫檔。
Terraform module 和官方 Registry 模組差在哪?
模組就是一包可以重複叫的 Terraform 設定。自己寫的模組放在本機資料夾,用 source = "../modules/bucket" 叫,適合寫公司自己的規定;Registry 模組從網路下載,例如 Google 維護的 terraform-google-modules/cloud-storage/google,一定要寫 version 鎖版本。實測這個模組的 public_access_prevention 預設是 inherited,不是禁止公開,用之前要先看預設值。
Infrastructure Manager 要錢嗎?
看 Terraform 版本。用 1.5.7 以前的版本不收管理費(預設就是 1.5.7),只收底下 Cloud Build 的執行時間和 Cloud Storage 的儲存量。用 1.16.5 以後的付費版本,每個帳單帳戶每月前 500 個資源免費,超過的每個資源一年 1 美元,按秒計算;預覽不收(2026 年 12 月查官方計費頁)。
Infrastructure Manager 可以用最新版 Terraform 嗎?
不行,只能用它支援的版本。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 能不能跑。
重點整理
- terraform state 團隊用要放遠端:
backend "gcs"指到一個事先用 gcloud 建好、開版本控管、禁止公開的 bucket,用terraform init -migrate-state搬上去,搬完記得刪本機的.backup - state lock 是保護:有人在 apply(包含停在等 yes),其他人連 plan 都會被
Error 412擋下。程式被中斷留下的鎖,確認沒人在跑才force-unlock,gcs 要用錯誤訊息裡的數字 ID - 版本控管救得回 state,也會留下敏感資料:實測 12 個舊版本(8 個鎖檔、4 個 state);正式環境用生命週期規則清掉太舊的版本,刪 bucket 要加
--all-versions - 模組讓規定只寫一次:自己寫的放公司規定、叫幾次建幾個;Registry 模組要鎖
version,實測 Google 的 Cloud Storage 模組預設inherited,要自己改enforced - Infrastructure Manager 是代管的 Terraform:用服務帳戶在 Cloud Build 跑、state 和每次紀錄它保管、設定不能寫 backend;預設 Terraform 1.5.7 免費,實測建一個資源 3 分 46 秒
延伸閱讀
本系列
- 第 1 篇:GCP DevOps 證照怎麼考?2026 新版考綱、比重與準備地圖
- 第 3 篇:CI/CD 是什麼?持續整合、持續交付、持續部署差在哪
- 第 7 篇:DevSecOps 是什麼?跟 SecOps、Google SecOps 差在哪
- 第 9 篇:Ops 名詞總表:DevOps、SRE、Platform Engineering、FinOps 差在哪
- 第 10 篇:Terraform 教學:用程式碼建 GCP 資源(init、plan、apply、state)
- 第 13 篇:Cloud Build 串 GitHub/GitLab:push 就自動建置部署
- 第 17 篇:Secret Manager 教學:密碼和設定怎麼管?Parameter Manager、Cloud KMS 實測
這篇用到的服務
- Cloud Build 是什麼?用 cloudbuild.yaml 自動建映像檔、部署到 Cloud Run
- Artifact Registry 是什麼?把 Docker 映像檔推上 GCP 教學
- GCP 的 Cloud IAM:角色與權限控管介紹
- 使用 GCP Service Account 開發程式的小技巧和注意事項
站上相關文章
- [[GKE 教學] Config Connector 是什麼東東?如何使用?](https://dongdonggcp.com/2024/12/02/gke-what-is-config-connector-and-how-to-use/)
- GitOps 方法論是什麼東東?GitOps 的工作流程是什麼?
- GCP 帳單爆炸防護指南:5 個步驟讓你不再睡醒崩潰
state 共用、模組重用之後,下一步是讓部署跟著 Git push 自動跑,第 13 篇:Cloud Build 串 GitHub/GitLab:push 就自動建置部署會用到同一個 Cloud Build。可以看看東東的 GCP 課程,或加 LINE 聊聊你現在的狀況,一起找出最適合你的學習順序。


