【问题标题】:Terraform 12 block variableTerraform 12 块变量
【发布时间】:2020-12-24 12:07:34
【问题描述】:

现在我正在迁移到 Terraform 12。这里的主要功能之一是更严格的 HCL2,我喜欢它。

例如,如果我有地图列表:

  elb_listeners = [
     {
       instance_port     = 80
       instance_protocol = "http"
       lb_port           = 80
       lb_protocol       = "http"
     },
     {
       instance_port      = 443
       instance_protocol  = "http"
       lb_port            = 443
       lb_protocol        = "https"
       ssl_certificate_id = ARN certificate
     }

我可以用动态块旋转它:

  dynamic "listener" {
    for_each = [for listener in var.elb_listeners : {
      instance_port     = listener.instance_port
      instance_protocol = listener.instance_protocol
      lb_port           = listener.lb_port
      lb_protocol       = listener.lb_protocol
    }]

    content {
      instance_port     = listener.value.instance_port
      instance_protocol = listener.value.instance_protocol
      lb_port           = listener.value.lb_port
      lb_protocol       = listener.value.lb_protocol
    }
  }

但是让我们假设我只有一个块并且只有一个块是可能的:

  health_check {
    healthy_threshold   = 2
    unhealthy_threshold = 2
    timeout             = 3
    target              = "HTTP:8000/"
    interval            = 30
  }

我不想声明所有这些变量,我也想在设置中将其描述为块一次。是的,在这里我也可以将dynamic_block 与一个元素一起使用,但在这里看起来有点过头了。有可能这样做吗?喜欢

  health_check {
    var.health_check
  }

什么的。

【问题讨论】:

    标签: terraform infrastructure-as-code


    【解决方案1】:

    我知道你要去哪里。但我认为目前不可能在资源中“扩展”地图。您可以使用默认值定义映射变量,尽管这需要更多代码行。

    variable health_check {
        type = "map"
        default = {
            healthy_threshold   = 2
            unhealthy_threshold = 2
            timeout             = 3
            target              = "HTTP:8000/"
            interval            = 30
        }
    }
    
    health_check {
        healthy_threshold   = var.health_check.healthy_threshold
        unhealthy_threshold = var.health_check.unhealthy_threshold
        timeout             = var.health_check.timeout
        target              = var.health_check.target
        interval            = var.health_check.interval
    }
    

    再想一想,我不明白你为什么需要它。它使您的代码结构的可读性和明确性降低。因此,选项是使用或不使用默认值显式定义它,或者当您有多个资源要从列表/地图创建时使用 for_each。

    【讨论】:

    • > 不要认为当前可以在资源内“扩展”地图 health_check 不能有更多资源,它只能有一个块。这就是为什么我不想使用for_each
    猜你喜欢
    • 2021-04-01
    • 2020-12-25
    • 2019-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-06
    • 2018-09-07
    相关资源
    最近更新 更多