如何使用 Terraform 为 AWS DMS 设置转义 json?

How to set an escaped json for AWS DMS with Terraform?

Terraform 的示例是 Resource: aws_dms_replication_task 我创建了一个测试资源

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(file("${path.module}/test.json"))

  tags = {
    Name = "test"
  }

  target_endpoint_arn = aws_dms_endpoint.test-dms-target-endpoint-tf.endpoint_arn
}

test.json 文件是

{
  "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"
    }
  ]
}

当运行 terraform 应用时,得到这个错误

Error: InvalidParameterValueException: Invalid Table Mappings document. Invalid json Invalid json object

如果使用格式作为示例可能没问题

table_mappings            = "{\"rules\":[{\"rule-type\":\"selection\",\"rule-id\":\"1\",\"rule-name\":\"1\",\"object-locator\":{\"schema-name\":\"%\",\"table-name\":\"%\"},\"rule-action\":\"include\"}]}"

如果使用Terraform的功能如何实现相同的结果?

要获得转义的 json 字符串,您可以这样做:

table_mappings = jsonencode(jsondecode(file("${path.module}/test.json")))

这有效地从您的 test.json 中删除 \n 并生成单行 json 转义字符串。

示例:

"{\"rules\":[{\"object-locator\":{\"schema-name\":\"SCHEMA_1\",\"table-name\":\"TABLE_1\"},\"rule-action\":\"rename\",\"rule-id\":\"1\",\"rule-name\":\"Rule name 1\",\"rule-target\":\"schema\",\"rule-type\":\"transformation\",\"value\":\"main\"}]}"