Terraform中通过for_each动态创建Confluent Schema的配置方案
动态生成Confluent Schema资源的Terraform配置修改方案
1. 定义变量(variables.tf)
在variables.tf中新增变量,用来接收包含主题名与Schema文件路径的对象列表:
variable "confluent_schemas" { type = list(object({ subject_name_avro = string schema_file_path = string })) description = "Confluent Schema配置列表,每个元素包含主题名和对应Avro Schema文件路径" default = [] }
2. 修改Confluent Schema资源配置(schema.tf)
替换原固定路径的资源代码,改用for_each迭代变量列表生成资源,以主题名作为唯一标识键:
resource "confluent_schema" "avro_schemas" { for_each = { for schema in var.confluent_schemas : schema.subject_name_avro => schema } subject_name = each.value.subject_name_avro format = "AVRO" schema = file(each.value.schema_file_path) # 保留原有必填配置(如环境ID、API凭据等,根据实际情况调整) environment { id = var.confluent_environment_id } credentials { key = var.confluent_api_key secret = var.confluent_api_secret } }
3. 在tfvars中传入配置示例(terraform.tfvars)
按照变量结构传入需要创建的Schema集合:
confluent_schemas = [ { subject_name_avro = "users.value" schema_file_path = "./schemas/user-value.avsc" }, { subject_name_avro = "orders.value" schema_file_path = "./schemas/order-value.avsc" } ]
注意事项
- 主题名必须唯一:
for_each要求键值唯一,重复的subject_name_avro会触发Terraform报错。 - 文件路径注意相对位置:
schema_file_path默认以执行terraform命令的工作目录为基准,也可直接使用绝对路径。 - 保留原有资源的必填参数:示例中的
environment和credentials块需根据你的Confluent环境配置调整。
内容的提问来源于stack exchange,提问作者sHaShAnk K
相关产品推荐
相关产品推荐

