昨天我們聊到 Data Sources,可以從既有的資源中擷取資訊。今天來看另一個常用工具 Outputs —— 它能把 Terraform 建立好的資訊「輸出」出來,提供給自己、其他模組,甚至整個團隊使用。
Terraform 幫我們建好 VM 或 API Gateway,但我們最常需要的往往是 IP 或 Endpoint。這時就可以在 outputs.tf
定義:
output "vm_ip" {
description = "Public IP of the VM"
value = google_compute_instance.vm.network_interface[0].access_config[0].nat_ip
}
這樣一來,terraform apply
後就能直接看到結果,不用再去 Console 翻找:
vm_ip = "34.80.123.45
假設我們把專案拆成多個模組:
network
負責 VPCcompute
負責 VM那麼 network
模組可以輸出 VPC 名稱:
# modules/network/outputs.tf
output "vpc_name" {
value = google_compute_network.main.name
}
然後 compute
模組就能接收:
module "compute" {
source = "./modules/compute"
vpc_name = module.network.vpc_name
}
這樣不用硬編碼,模組就能互相串接,配置更彈性。
在自動化部署中,常常需要 Terraform 的結果交給下一步流程。
例如:
API_URL=$(terraform output -raw api_gateway_url)
curl "$API_URL/health"
這樣就能無縫串接。
Outputs 也很適合提供給團隊中其他成員。
例如:
只要跑 terraform output
,大家就能快速取得正確資訊。
有時候我們想輸出一整組 JSON,例如多台 VM 的 IP:
output "vm_ips" {
value = jsonencode(google_compute_instance.vm[*].network_interface[0].access_config[0].nat_ip)
}
這樣可以直接拿去當 API 測試或其他工具的輸入。
像是密碼、Token,則可以加上 sensitive = true
,Terraform 就會幫你把它遮住,不會在終端機上顯示出來。
output "db_password" {
value = random_password.db.result
sensitive = true
}
這邊的概念跟第10天我們在變數(variable)提到的遮住敏感資訊是一樣的。
小差別在於:
⚠️ 不過要再次注意:這樣只是遮起來,不是加密!
敏感值依然會存在 state 檔案 裡,因此真正的安全還是要依靠 外部 Secret Manager 來存放。
Outputs 的價值就在於 資訊傳遞與串接,它能幫助我們:
搭配 Data Sources,就能形成一個完整的資訊流: Data Sources (輸入) ➜ Terraform 配置 ➜ Outputs (輸出) 讓基礎設施管理更自動化、更可重用!!