apache-kafkaterraformconfluent-cloud

Terraform enable or disable a resource conditionally


My requirement is to create or delete a resource by specifying enable flag true or false (In case of false the resource should get deleted, in case of true the resource should get created)

Kindly refer below code - here I am creating "confluent topic" resource and calling it dynamically using for_each condition.

Confluent Topic creation

topic.tf file:

resource "confluent_kafka_topic" "topic" {
  kafka_cluster {
    id = confluent_kafka_cluster.dedicated.id
  }
  for_each         = { for t in var.topic_name : t.topic_name => t }
  topic_name       = each.value["topic_name"]
  partitions_count = each.value["partitions_count"]
  rest_endpoint    = confluent_kafka_cluster.dedicated.rest_endpoint
  credentials {
    key    = confluent_api_key.app-manager-kafka-api-key.id
    secret = confluent_api_key.app-manager-kafka-api-key.secret
  }
}

Variable declared as:

variable "topic_name" {
  type = list(map(string))
  default = [{
    "topic_name" = "default_topic"
  }]
}

And finally executing it through DEV.tfvars file:

topic_name = [
    {
        topic_name  = "avro-topic-1"
        partitions_count = "6"
    },  
    {
        topic_name  = "json-topic-1"
        partitions_count = "8"
    },            
]

The above code execution works fine and I am able to create and delete multiple resources. I want to modify it further and add a flag/toggle to create or delete a resource.

Example as shown below:

topic_name = [
    {
        topic_name  = "avro-topic-1"
        partitions_count = "6"
        **enable = true #this flag will create the resource**
    },  
    {
        topic_name  = "json-topic-1"
        partitions_count = "8"
        **enable = false #this flag will delete the resource**
    },            
]

Kindly help suggest how it can be achieved and if there is any different approach to follow.


Solution

  • As mentioned in my comment, I think this can be achieved with the following change:

    resource "confluent_kafka_topic" "topic" {
      for_each         = { for t in var.topic_name : t.topic_name => t if t.enable }
      kafka_cluster {
        id = confluent_kafka_cluster.dedicated.id
      }
      topic_name       = each.value["topic_name"]
      partitions_count = each.value["partitions_count"]
      rest_endpoint    = confluent_kafka_cluster.dedicated.rest_endpoint
      credentials {
        key    = confluent_api_key.app-manager-kafka-api-key.id
        secret = confluent_api_key.app-manager-kafka-api-key.secret
      }
    }
    

    Additionally, for_each should probably be at the top of the resource block to make sure it is visible immediately to the reader. The if t.enable part will make sure that for_each will create a resource only when the variable key has the enabled = true.