我只是想用Terraform弄湿我的脚,但是我没有找到阻止我重复自己的明显方法。
我想管理Cloudlfare中的许多区域。这些区域的设置都非常相似,我希望我的.tf
文件简短易读。
假设我有example1.com example2.com example3.com ...我将它们添加为以下代码:
resource "cloudflare_zone" "example1"{
zone = "example1.com"
}
resource "cloudflare_zone" "example2"{
zone = "example2.com"
}
resource "cloudflare_zone" "example3"{
zone = "example3.com"
}
到目前为止很好。
现在,我想使用cloudflare_zone_settings_override
提供程序将相同的设置应用于所有区域。
查看文档,这对于一个区域来说很简单。但我宁愿不必对每个区域都这样做:
resource "cloudflare_zone_settings_override" "example1" {
name = "$example1.com"
settings {
brotli = "on"
security_level = "high"
opportunistic_encryption = "on"
automatic_https_rewrites = "on"
mirage = "on"
waf = "on"
minify {
css = "on"
js = "off"
html = "off"
}
}
}
将这些应用于Cloudflare的所有(或某些)区域的最佳方法是什么?
谢谢
答案 0 :(得分:0)
为了避免重复使用Terraform代码,您可以:
第二个解决方案的示例:
local {
domain_names = [
example1.com,
example2.com,
example3.com
]
}
resource "cloudflare_zone" "these_zones" {
count = "${length(local.domain_names)}"
zone = "${element(local.domain_names, count.index)}"
}
resource "cloudflare_zone_settings_override" "these_zones_settings" {
count = "${length(local.domain_names)}"
name = "${element(local.domain_names, count.index)}"
settings {
brotli = "on"
security_level = "high"
opportunistic_encryption = "on"
automatic_https_rewrites = "on"
mirage = "on"
waf = "on"
minify {
css = "on"
js = "off"
html = "off"
}
}
}
PS:此代码是为terraform <0.12
编写的答案 1 :(得分:0)
Terraform有两种方法可以最大程度地减少重复自己。
您可以使用count
meta-parameter根据需要创建资源来遍历列表:
variable "zones" {
type = "list"
}
resource "cloudflare_zone" "zones" {
count = "${length(var.zones)}"
zone = "${var.zones[count.index]}"
}
resource "cloudflare_zone_settings_override" "settings" {
count = "${length(var.zones)}"
name = "${cloudflare_zone.zones.*.zone[count.index]}"
settings {
brotli = "on"
security_level = "high"
opportunistic_encryption = "on"
automatic_https_rewrites = "on"
mirage = "on"
waf = "on"
minify {
css = "on"
js = "off"
html = "off"
}
}
}
请注意在区域设置中使用"${cloudflare_zone.zones.*.zone[count.index]}"
作为区域名称。这将确保Terraform在创建区域设置覆盖之前知道需要创建Cloudflare区域,而不是看不到两者之间的依赖关系并尝试同时创建它们,这可能会因为区域尚未建立而失败在Terraform尝试创建区域设置覆盖时创建。
或者您可以将区域配置移至module,从而使您可以抽象一些内容,从而为模块调用者提供了对资源的更多限制:
variable "zone" {}
variable "waf" {
default = "on"
}
resource "cloudflare_zone" "zone" {
zone = "${var.zone}"
}
resource "cloudflare_zone_settings_override" "settings" {
name = "${cloudflare_zone.zone.zone}"
settings {
brotli = "on"
security_level = "high"
opportunistic_encryption = "on"
automatic_https_rewrites = "on"
mirage = "on"
waf = "${var.waf}"
minify {
css = "on"
js = "off"
html = "off"
}
}
}
然后,此模块具有必需变量zone
和可选的默认变量waf
,该变量控制是否为区域启用WAF。为调用者设置了所有其他选项,因此可以像这样简单地多次调用该模块:
module "cloudflare_zone_example1" {
source = "path/to/module"
zone = "example1.com"
}
module "cloudflare_zone_example2" {
source = "path/to/module"
zone = "example2.com"
waf = "off"
}