Terraform - 如果变量值等于某个值,则忽略该变量值的一部分

Terraform - Ignore part of a variable's value if it equals a certain value

我正在尝试创建一个多云解决方案来为 EC2/GCE 实例构建安全规则。我的想法是我只想使用适用于两个平台的 单个 .tfvars 文件。

但是一切正常,因为 AWS 和 GCP 之间存在差异(AWS 要求您提供 -1 的端口值,而 GCP 要求您不要 在定义 ICMP 规则时提供一个端口),我的解决方案并不完全有效。这是我的 .tfvars:

的片段
rules = [
 {
    protocol = "tcp"
    port = 22
    cidrs = ["10.0.0.0/8"]
  },
  {
    protocol = "icmp"
    port = -1
    cidrs = ["10.0.0.0/8"]
  }
]

这些被传递到 variables.tf:

variable "rules" {
  type = list(object({
    protocol = string
    port = number
    cidrs = list(string)
  }))
}

然后使用动态块访问。以下是 GCP 的示例:

resource "google_compute_firewall" "this" {
  name        = "rule"
  network     = "network"
  project     = "project"
  target_tags = "targets"

  dynamic "allow" {
    for_each = var.rules

    content{
      protocol = allow.value["protocol"]
      ports    = [allow.value["port"]]
    }
  }
}

所以本质上,我要么需要告诉 GCP 模块 ignore allow.value["port"] 当它等于 -1 时,要么我不需要定义端口对于我的 .tfvars 文件中的 ICMP,当 allow.value["protocol"] 等于 icmp 时,告诉 AWS 添加 -1 作为端口号。

任何关于如何实现其中任何一个的建议都将不胜感激!

Terraform 0.12,以及引入 dynamic 块,introduced null 将省略向提供者发送属性。

当你有一些东西 conditional 并且提供者不满意说一个空字符串意味着它被省略时,这很有效(0.12 之前的常见技巧)。

所以你可以这样做:

resource "google_compute_firewall" "this" {
  name        = "rule"
  network     = "network"
  project     = "project"
  target_tags = "targets"

  dynamic "allow" {
    for_each = var.rules

    content{
      protocol = allow.value["protocol"]
      ports    = allow.value["port"] == -1 ? null : [allow.value["port"]]
    }
  }
}

现在,如果您将 port 设置为 -1,那么它将忽略 allow 块中的 ports 属性,否则会将其设置为 rules.port.