Home > Software design >  terraform variable using block with no argument
terraform variable using block with no argument

Time:11-07

I have a sample code below from terraform but I'm having some issues trying to declare a variable that the argument is a block

basic {}

and moving to production will be something like

 dedicated {
    cku = 2
  }

DEV

resource "confluent_kafka_cluster" "basic" {
  display_name = "basic_kafka_cluster"
  availability = "SINGLE_ZONE"
  cloud        = "GCP"
  region       = "us-central1"
  basic {}                         <<<< # I want this block to be declared as variable
  
  # Calling the variable
  local.cluster_type["dev"]        <<<< # this approach is not supported. how can I call the variable directly if there is no argument?
}

PROD

resource "confluent_kafka_cluster" "dedicated" {
  display_name = "dedicated_kafka_cluster"
  availability = "MULTI_ZONE"
  cloud        = "GCP"
  region       = "us-central1"
  
  # For Production it is using a different block
  dedicated {
    cku = 2
  }

  # Calling the variable
  local.cluster_type["prod"]         <<<<< # this approach is not supported. how can I call the variable directly if there is no argument?
}

Local variables

locals {
  cluster_type = {
    prod = "dedicated {
              cku = 2
            }"
    dev = "basic {}"
  }
}

CodePudding user response:

You have some issues with your script:

  1. confluent_kafka_cluster is deprecated, it should be replaced by confluentcloud_kafka_cluster

  2. To use the environment, you can create confluentcloud_environment:

      resource "confluentcloud_environment" "env" {
         display_name = var.environment
      }
    
  3. To solve the issue of the block, you can use dynamic with conditions, like this:

    dynamic "basic" {
      for_each = var.environment == "dev" ? [1] : []
      content {}
    }
    
    dynamic "dedicated" {
      for_each = var.environment == "prod" ? [1] : []
      content {
        cku = 2
      }
    }
    

Your code can be like this:

resource "confluentcloud_environment" "env" {
  display_name = var.environment
}

resource "confluentcloud_kafka_cluster" "basic" {
  display_name = "basic_kafka_cluster"
  availability = "SINGLE_ZONE"
  cloud        = "GCP"
  region       = "us-central1"

  dynamic "basic" {
    for_each = var.environment == "dev" ? [1] : []
    content {}
  }

  dynamic "dedicated" {
    for_each = var.environment == "prod" ? [1] : []
    content {
      cku = 2
    }
  }

  environment {
    id = confluentcloud_environment.env.id
  }
}

variable "environment" {
  default = "dev"
}
  • Related