昨天我們聊到 Provisioners 和 External Data Source,學會了怎麼讓 Terraform 跟外部世界互動,補足 Provider 沒有的功能。
但隨著基礎架構越來越複雜,另一個問題也會浮現:團隊如何確保每個人寫的 Terraform 都符合公司規範?
這就是今天要介紹的主題 —— Policy as Code(政策即程式碼)。
在大型團隊或企業環境中,光是能建立資源還不夠,還要有規範:
傳統的做法是 人工 Code Review,但難免會漏掉細節。
更好的方式是把規範寫成程式,讓 Terraform 在 plan
或 apply
前就自動檢查。
範例(禁止沒有標籤的資源):
import "tfplan/v2" as tfplan
main = rule {
all tfplan.resources as _, rs {
all rs.applied as r {
"tags" in r
}
}
}
.tf
或 .json
plan 檔做靜態檢查範例(禁止開放 0.0.0.0/0 的防火牆):
package main
deny[msg] {
input.resource.type == "google_compute_firewall"
rule := input.resource.values
rule.source_ranges[_] == "0.0.0.0/0"
msg = "防火牆規則不能對 0.0.0.0/0 全開"
}
執行方式:
terraform plan -out tfplan.binary
terraform show -json tfplan.binary > tfplan.json
conftest test tfplan.json
如果團隊規模較小,也可以在 GitHub Actions / GitLab CI 中加入簡單檢查:
grep
檢查程式碼裡是否有 0.0.0.0/0
tflint
)檢查不良習慣plan
階段就能攔截不合規的資源,避免進入 production。今天我們介紹了 Terraform Policy as Code 的概念,並看到三種實踐方式:
在團隊協作中,Policy as Code 就像是「守門員」,幫忙把不合規的基礎架構擋在門外。
這樣,Terraform 不只是一個自動化工具,更能成為「安全、合規」的基礎架構守護者。