cloudflare terraform provider firewall creation with loop



我正在尝试解决防火墙创建分为 2 个部分的约束,创建一个过滤器并基于过滤器创建规则。筛选器创建公开应在 fw 规则创建中使用的筛选器 ID。我无法理解如何正确遍历具有过滤器和规则值并包含新创建的过滤器的地图。如果我只使用带有名称和表达式的简单地图,事情会起作用,但是如果我添加规则优先级,事情就会中断 这是我的地图

variable "fw_allowfilters1" {
description = "list of expressions for firewall to be included in the allow rules"
type = map(object({
fvalue = string
priority = number
}))
default = {
"office_filter1" = [
{
fvalue = "ip.geoip.asnum eq 111111"
priority = 1
}
]
"office_filter2" = [
{
fvalue = "ip.src eq 8.8.8.8"
priority = 3
}
]
}
}

现在这是我的过滤器和固件的代码

resource "cloudflare_filter" "allow-filters1" {
for_each = var.fw_allowfilters1
zone_id = var.zoneid
expression = each.value.fvalue
description = each.key
//description = [for o in var.fw_allowfilters1: "Filter_${var.fw_allowfilters1.name}"]
//expression = [for o in var.fw_allowfilters1: var.fw_allowfilters1.value]
}
resource "cloudflare_firewall_rule" "whitelist-rule" {
for_each = cloudflare_filter.allow-filters1
action = "allow"
filter_id =  tostring(each.value.id)
zone_id = var.zoneid
description = [for p in var.fw_allowfilters1.name: p.name ]
priority = [for p in var.fw_allowfilters1.priority: p.priority  ]
}

现在,如果我不包括优先级,我可以在防火墙创建中对过滤器输出进行for_each,使用资源和密钥的 ID 输出进行描述(cf tf 提供程序使用描述作为名称(但是,如果我需要添加密钥,我需要使用值和过滤器创建输出的 ID 遍历映射,我不确定如何正确映射它。 代码目前不起作用。

所以我想通了,这并不容易:(使用当地人帮助我创建了适当的迭代器:

resource "cloudflare_filter" "filters1" {
for_each = var.fw_rules
zone_id = var.zoneid
description = "Filter_${tostring(each.key)}"
expression = tostring(each.value[0])
}
locals {
filterids = [for f in cloudflare_filter.filters1 : f.id] //putting filter 
IDs into a separate list for concat later
fwvalues = (values(var.fw_rules)) // putting values from the map of fwvalues into 
a separate list to use the index position of a particular value as an interator when 
creating commong object that has both filterid and fwvalues
fwkeys = (keys(var.fw_rules)) //putting keys into a separate list
//iterating over all elements in the allowfilters1, combining existing lists in the 
variable with the ID value and readding the key as an element in the list
withid3 = {for p in var.fw_rules : local.fwkeys[index(local.fwvalues, p.*)] => 
concat(p, list(local.filterids[index(local.fwvalues, 
p.*)]),list(local.fwkeys[index(local.fwvalues, p.*)]))} //working version
}
resource "cloudflare_firewall_rule" "fw-rules" {
for_each = local.withid3
action = each.value[2]
filter_id =  each.value[4]
paused = each.value[3]
zone_id = var.zoneid
description = "FW-${tostring(each.value[2])}-${tostring(each.key)}"
priority = each.value[1]
}

其中可变的是: 语法如下: 规则名称(尽量精确 = [ 表达式, 优先级,操作, 禁用 - 布尔值] - 所有值都应该是字符串,确保正确终止引号 操作的允许值为:阻止、质询、js_challenge、允许、记录、绕过 必须根据规则优先级维护列表

variable "fw_rules" {
description = "list of expressions for firewall to be included in therules"
type = map
default = {
office_allow = ["putexpressionhere","1","allow","false"],
office_allow1 = ["putexpressionhere1","2","deny","false"]
}

最新更新