Terraform如何从local值生成对应的tfvars文件?
问题描述
我有如下的locals数据结构:
locals { replication_tasks = { track_to_s3_live = { replication_task_id = "track-to-s3" migration_type = "full-load-and-cdc" replication_task_settings = file("files/s3_tracking_cdc_settings.json") table_mappings = file("files/s3_tracking_table_mappings.json") source_endpoint_key = "source" target_endpoint_key = "s3_tracking" } } }
尝试用以下代码生成可用于其他模块的等效.tfvars文件时:
resource "local_file" "file" { content = <<EOF replication_tasks = "${local.replication_tasks}" EOF filename = "${path.module}/tasks.auto.tfvars" }
遇到错误:
Cannot include the given value in a string template: string required.
请问该如何实现需求?
解决方案
错误原因是直接将嵌套Map这类非字符串类型的变量插入到字符串模板中,Terraform无法自动完成类型转换。要生成合法的HCL格式.tfvars文件,需使用Terraform内置的hclencode函数——它能将任意Terraform数据结构转换为符合HCL语法的字符串。
修改后的代码如下:
resource "local_file" "file" { content = "replication_tasks = ${hclencode(local.replication_tasks)}" filename = "${path.module}/tasks.auto.tfvars" }
补充说明
hclencode会自动处理嵌套结构、字符串转义等细节,生成的内容可直接作为tfvars文件使用。- 对于
replication_task_settings和table_mappings这类JSON格式的字符串,hclencode会自动将其转义为合法的HCL字符串值,无需额外处理。
内容的提问来源于stack exchange,提问作者Marco Caberletti
相关产品推荐
相关产品推荐

