如何通过Terraform函数为AWS DMS配置正确转义的JSON参数
问题原因
你当前的配置出现报错是因为对JSON内容做了二次编码:file("${path.module}/test.json") 读取本地文件后返回的已经是字符串格式的合法JSON内容,外层再嵌套jsonencode()会对JSON字符串的引号等特殊字符做二次转义,最终输出的内容不符合AWS DMS的表映射参数格式要求。
解决方案
你可以从以下两种方案中选一种使用,都不需要手动写转义JSON:
方案1:直接读取本地JSON文件
去掉多余的jsonencode()嵌套,直接读取文件内容即可:
resource "aws_dms_replication_task" "test" { migration_type = "full-load" replication_instance_arn = aws_dms_replication_instance.test-dms-replication-instance-tf.replication_instance_arn replication_task_id = "test-dms-replication-task-tf" source_endpoint_arn = aws_dms_endpoint.test-dms-source-endpoint-tf.endpoint_arn # 这里直接用file读取,不需要jsonencode table_mappings = file("${path.module}/test.json") tags = { Name = "test" } target_endpoint_arn = aws_dms_endpoint.test-dms-target-endpoint-tf.endpoint_arn }
该方案适合需要单独维护表映射规则、规则内容比较复杂的场景。
方案2:直接在Terraform中定义映射结构再编码
如果不想单独维护JSON文件,可以把映射规则直接写为Terraform对象,再用jsonencode()转成JSON字符串:
resource "aws_dms_replication_task" "test" { migration_type = "full-load" replication_instance_arn = aws_dms_replication_instance.test-dms-replication-instance-tf.replication_instance_arn replication_task_id = "test-dms-replication-task-tf" source_endpoint_arn = aws_dms_endpoint.test-dms-source-endpoint-tf.endpoint_arn table_mappings = jsonencode({ rules = [ { "rule-type": "transformation", "rule-id": "1", "rule-name": "Rule name 1", "rule-action": "rename", "rule-target": "schema", "object-locator": { "schema-name": "SCHEMA_1", "table-name": "TABLE_1" }, "value": "main" } ] }) tags = { Name = "test" } target_endpoint_arn = aws_dms_endpoint.test-dms-target-endpoint-tf.endpoint_arn }
该方案适合规则比较简单、需要结合Terraform变量/插值动态生成映射规则的场景。
验证方法
修改配置后可以先执行terraform plan,查看输出的table_mappings参数值是否和你之前可用的硬编码转义JSON格式一致,确认无误后再执行terraform apply即可。
内容的提问来源于stack exchange,提问作者Miantian
相关产品推荐
相关产品推荐

