MantyQuestions
MantyQuestions

Reputation: 379

Conditionally add to resource attribute via terraform

i am attempting to create a service fabric cluster via terraform, I wish to add either 1 or 2 node type parameters dynamically.

My cluster is defined as so:

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
  }
}

What I would like, is to deploy only the 'first' node_type when a variable is false, and deploy both 'first' and 'second' when a variable is true.

Usually, If i was deploying resources, I would use

  count                = var.node_type_count > 1 ? 1 : 0

However this cannot be done as the node types themselves are not resources, they are simply attributes. How can i conditionally add to this?

Upvotes: 3

Views: 381

Answers (1)

Marcin
Marcin

Reputation: 239000

You can use dynamic blocks. Basically, first is always created, while second is optional:

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    
    }
  }

}

Upvotes: 3

Related Questions