【问题标题】:Conditionally add to resource attribute via terraform通过 terraform 有条件地添加到资源属性
【发布时间】:2021-04-30 14:55:55
【问题描述】:

我正在尝试通过 terraform 创建一个服务结构集群,我希望动态添加 1 或 2 个节点类型参数。

我的集群是这样定义的:

resource "azurerm_service_fabric_cluster" "example" {
  name                 = "example-servicefabric"
  resource_group_name  = "${var.cluster_name}-group"
  location             = var.location
  reliability_level    = "Bronze"
  upgrade_mode         = "Manual"
  cluster_code_version = "7.1.456.959"
  vm_image             = "Windows"
  management_endpoint  = "https://example:80"

  node_type{
        name                 = "first"
        instance_count       = 3
        is_primary           = true
        client_endpoint_port = 2020
        http_endpoint_port   = 80
  }

    node_type{
        name                 = "second"
        instance_count       = 3
        is_primary           = true
        client_endpoint_port = 2020
        http_endpoint_port   = 80
  }
}

我想要的是,当变量为假时仅部署“第一”节点类型,当变量为真时部署“第一”和“第二”。

通常,如果我正在部署资源,我会使用

  count                = var.node_type_count > 1 ? 1 : 0

但是这无法做到,因为节点类型本身不是资源,它们只是属性。我怎样才能有条件地添加到这个?

【问题讨论】:

    标签: azure terraform


    【解决方案1】:

    您可以使用dynamic blocks。基本上,first 总是被创建,而second 是可选的:

    resource "azurerm_service_fabric_cluster" "example" {
      name                 = "example-servicefabric"
      resource_group_name  = "${var.cluster_name}-group"
      location             = var.location
      reliability_level    = "Bronze"
      upgrade_mode         = "Manual"
      cluster_code_version = "7.1.456.959"
      vm_image             = "Windows"
      management_endpoint  = "https://example:80"
    
    
      node_type {
            name                 = "first"
            instance_count       = 3
            is_primary           = true
            client_endpoint_port = 2020
            http_endpoint_port   = 80    
      }
    
      dynamic "node_type" {
    
        for_each = var.second_node == true ? [1] : []
    
        content {
            name                 = "second"
            instance_count       = 3
            is_primary           = true
            client_endpoint_port = 2020
            http_endpoint_port   = 80    
        }
      }
    
    }
    

    【讨论】:

    • 这行得通 - 您能否具体说明 [1] 的用途是什么?当我们试图访问第一个值时,这不应该是 [0] 吗?即我们只有 1 个动态节点类型
    • @MantyQuestions 它可以是任何值,因为您没有使用它。这只是对for_each 进行一次迭代。
    猜你喜欢
    • 2021-05-01
    • 2021-07-03
    • 1970-01-01
    • 2018-01-21
    • 2019-05-07
    • 2018-06-26
    • 2019-11-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多