【问题标题】:Terraform - Ignore part of a variable's value if it equals a certain valueTerraform - 如果变量值等于某个值,则忽略它的一部分
【发布时间】:2021-08-09 17:29:47
【问题描述】:

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

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

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 模块 忽略 allow.value["port"] 当它等于 -1 时,或者我不需要在我的 .tfvars 文件中为 ICMP 定义端口,并告诉 AWS 在allow.value["protocol"] 等于icmp添加 -1 作为端口号。

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

【问题讨论】:

    标签: amazon-web-services google-cloud-platform dynamic conditional-statements terraform


    【解决方案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 的值。

    【讨论】:

    • 太完美了,谢谢@ydaetskcoR。我没有意识到您可以将条件用于这样的单个参数,我只看到它们用于资源的顶部来决定创建整个事物!
    猜你喜欢
    • 2021-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-08
    • 1970-01-01
    • 2013-01-24
    • 2022-07-04
    • 2012-05-25
    相关资源
    最近更新 更多