iT邦幫忙

2025 iThome 鐵人賽

DAY 24
0
DevOps

30 天 Terraform 學習筆記:從零開始的 IaC 實戰系列 第 24

Day 24 - Terraform Policy as Code

  • 分享至 

  • xImage
  •  

昨天我們聊到 ProvisionersExternal Data Source,學會了怎麼讓 Terraform 跟外部世界互動,補足 Provider 沒有的功能。

但隨著基礎架構越來越複雜,另一個問題也會浮現:團隊如何確保每個人寫的 Terraform 都符合公司規範?

這就是今天要介紹的主題 —— Policy as Code(政策即程式碼)

為什麼需要 Policy as Code?

在大型團隊或企業環境中,光是能建立資源還不夠,還要有規範:

  • 安全性:不能隨便建立一個「對全世界開放」的防火牆規則。
  • 一致性:所有 VM 都要加上標籤,方便計費與管理。
  • 合規性:資源建立必須符合 ISO / SOC2 / GDPR 等要求。

傳統的做法是 人工 Code Review,但難免會漏掉細節。

更好的方式是把規範寫成程式,讓 Terraform 在 planapply 前就自動檢查。

Terraform Policy as Code 的工具

1. Sentinel(HashiCorp 官方)

  • 與 Terraform Cloud / Enterprise 整合
  • 使用 Policy 語言(類似 HCL)
  • 可以在 plan 前自動驗證,例如:
    • 禁止沒有標籤的資源
    • 強制使用特定 VM 類型
    • 限制只能在特定 region 建立資源

範例(禁止沒有標籤的資源):

import "tfplan/v2" as tfplan

main = rule {
  all tfplan.resources as _, rs {
    all rs.applied as r {
      "tags" in r
    }
  }
}

2. OPA / Conftest(開源社群常用)

  • OPA = Open Policy Agent
  • Conftest 是 OPA 的 CLI 工具
  • 使用 Rego 語言 撰寫規則
  • 可以對 .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

3. 自製檢查(Pre-commit Hook / CI/CD)

如果團隊規模較小,也可以在 GitHub Actions / GitLab CI 中加入簡單檢查:

  • grep 檢查程式碼裡是否有 0.0.0.0/0
  • 用 lint 工具(如 tflint)檢查不良習慣
  • 在 PR 時自動跑測試,避免不合規程式碼進入主幹

Policy as Code 的好處

  • 自動化:不用靠人工 Review 記得檢查細節。
  • 可版本控制:規則寫在程式碼裡,跟 Terraform 配置一起管理。
  • 一致性:所有人都遵守相同規則。
  • 即時阻擋:在 plan 階段就能攔截不合規的資源,避免進入 production。

總結一下

今天我們介紹了 Terraform Policy as Code 的概念,並看到三種實踐方式:

  1. Sentinel(官方,深度整合 Terraform Cloud/Enterprise)
  2. OPA / Conftest(開源工具,靈活度高)
  3. 自製簡單檢查(pre-commit / CI/CD pipeline)

在團隊協作中,Policy as Code 就像是「守門員」,幫忙把不合規的基礎架構擋在門外。
這樣,Terraform 不只是一個自動化工具,更能成為「安全、合規」的基礎架構守護者。


上一篇
Day 23 - Provisioners 與 External Data:Terraform 與外部世界的橋樑
系列文
30 天 Terraform 學習筆記:從零開始的 IaC 實戰24
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言