Terraform 作業的最佳做法
本文件提供 Terraform 作業的規範和建議。
本指南並非 Terraform 的介紹。如要瞭解如何搭配使用 Terraform 和 Trusted Cloud by S3NS,請參閱「開始使用 Terraform」。
一律先規劃
請務必先為 Terraform 執行作業產生計畫。將企劃書儲存至輸出檔案。基礎架構擁有者核准後,請執行這項計畫。即使開發人員在本機中製作變更原型,也應在套用計畫前產生計畫,並查看要新增、修改和刪除的資源。
實作自動化管道
為確保執行作業一致,請透過自動化工具執行 Terraform。如果您已使用並廣泛採用某個建構系統 (例如 Jenkins),請使用該系統自動執行 terraform plan
和 terraform apply
指令。如果沒有現有系統可用,請採用 Cloud Build 或 Terraform Cloud。
使用服務帳戶憑證進行持續整合
當 Terraform 從 CI/CD 管道中的機器執行時,應從執行管道的服務繼承服務帳戶憑證。盡可能在 Trusted Cloud 上執行持續整合管道,因為 Cloud Build、Google Kubernetes Engine 或 Compute Engine 會在未下載服務帳戶金鑰的情況下,插入憑證。
如果管道是在 Trusted Cloud外執行,建議使用工作負載身分聯盟,這樣就不必下載服務帳戶金鑰即可取得憑證。
避免匯入現有資源
盡可能避免匯入現有資源 (使用 terraform import
),因為這樣做可能會讓您難以完全瞭解手動建立資源的來源和設定。請改為透過 Terraform 建立新資源,然後刪除舊資源。
如果刪除舊資源會造成大量工作,請使用 terraform import
指令並取得明確核准。將資源匯入 Terraform 後,請專門使用 Terraform 管理該資源。
請勿手動修改 Terraform 狀態
Terraform 狀態檔案對於維護 Terraform 設定和 Trusted Cloud 資源之間的對應關係至關重要。資料毀損可能會導致重大基礎架構問題。如需修改 Terraform 狀態,請使用 terraform state
指令。
定期查看版本固定點
固定版本可確保穩定性,但會防止錯誤修正和其他改善項目納入設定。因此,請定期檢查 Terraform、Terraform 供應器和模組的版本固定值。
如要自動執行這項程序,請使用 Dependabot 等工具。
在本機執行時使用應用程式預設憑證
當開發人員在本機重複執行 Terraform 設定時,應透過執行 gcloud auth application-default login
產生應用程式預設憑證。請勿下載服務帳戶金鑰,因為下載的金鑰較難管理及保護。
將別名設為 Terraform
如要簡化本機開發作業,您可以為指令列 Shell 設定檔新增別名:
alias tf="terraform"
alias terrafrom="terraform"
後續步驟
除非另有註明,否則本頁面中的內容是採用創用 CC 姓名標示 4.0 授權,程式碼範例則為阿帕契 2.0 授權。詳情請參閱《Google Developers 網站政策》。Java 是 Oracle 和/或其關聯企業的註冊商標。
上次更新時間:2025-08-08 (世界標準時間)。
[[["容易理解","easyToUnderstand","thumb-up"],["確實解決了我的問題","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["缺少我需要的資訊","missingTheInformationINeed","thumb-down"],["過於複雜/步驟過多","tooComplicatedTooManySteps","thumb-down"],["過時","outOfDate","thumb-down"],["翻譯問題","translationIssue","thumb-down"],["示例/程式碼問題","samplesCodeIssue","thumb-down"],["其他","otherDown","thumb-down"]],["上次更新時間:2025-08-08 (世界標準時間)。"],[[["Always generate and review a Terraform plan before applying it, even during local development, and automate the execution of plans through a CI/CD pipeline."],["Utilize service account credentials through workload identity federation for CI/CD pipelines running outside of Google Cloud, and avoid downloading service account keys."],["Avoid importing existing resources whenever possible; instead, create new resources through Terraform to maintain clear resource management, and use the `terraform import` command with explicit approval if deletion of resources is not feasible."],["Refrain from manually modifying the Terraform state file, instead using the `terraform state` command for any necessary state adjustments."],["Regularly review version pins for Terraform, its providers, and modules, and consider automating this with a tool such as Dependabot."]]],[]]