confluentinc / terraform-provider-confluent

Terraform Provider for Confluent
Apache License 2.0
118 stars 61 forks source link

Data Source Topic return error when not found. But expected return null to allow use try #396

Open tonnytg opened 1 week ago

tonnytg commented 1 week ago

What happens:

I build a Module to Create or Edit Topics. I use Data Source Topic to get Topic; if it does not exist, run to create. If it exists, merge config from the data source with some new field of topic.config. But Data Source, when not found, Topic returns an error 404 not found, breaking all struct. We usually use a built-in function to solve this try(data.confluent_kafka_topic.main, {}) but try cannot process this kind of return of Error.

data "confluent_kafka_topic" "orders" {
  kafka_cluster {
    id = data.confluent_kafka_cluster.main.id
  }

  topic_name    = "topic_1"
  rest_endpoint = data.confluent_kafka_cluster.main.rest_endpoint

  credentials {
    key    = "xxxx"
    secret = "yyyy"
  }
}

output "config" {
  value = try(data.confluent_kafka_topic.orders.config, {})
}

Output:

  │ Error: error reading Kafka Topic "topic_1": 404 Not Found: This server does not host this topic-partition.
  │ 
  │   with data.confluent_kafka_topic.orders,
  │   on main.tf line 49, in data "confluent_kafka_topic" "orders":
  │   49: data "confluent_kafka_topic" "orders" {
  │ 

What expected:

It is expected try can change the value of Data Source to {}

Temporarily Solution:

I create a variable called isCreate and set true of false to active creation in this module or edit.

variable "isCreate" {
    type = bool
}

data "confluent_kafka_topic" "orders" {
  count = var.isCreate ? 1 : 0

  kafka_cluster {
    id = data.confluent_kafka_cluster.main.id
  }

  topic_name    = "topic_1"
  rest_endpoint = data.confluent_kafka_cluster.main.rest_endpoint

  credentials {
    key    = "xxxx"
    secret = "yyyy"
  }
}

locals {
  topicDataSource = var.isCreate ? data.confluent_kafka_topic.orders : []
}

output "config" {
  value = local.topicDataSource
}