【问题标题】:How to prepare rendered JSON for aws-cli in Terraform?如何在 Terraform 中为 aws-cli 准备渲染的 JSON?
【发布时间】:2019-02-04 11:19:46
【问题描述】:

在另一个 thread I have asked 中,如何在 AWS 中保持 ECS task definitions 处于活动状态。因此,我计划像这样更新任务定义:

resource "null_resource" "update_task_definition" {
  triggers {
    keys = "${uuid()}"
  }

  # Workaround to prevent older task definitions being deactivated
  provisioner "local-exec" {
    command = <<EOF
aws ecs register-task-definition \
--family my-task-definition \
--container-definitions ${data.template_file.task_definition.rendered} \
--network-mode bridge \
EOF
  }
}

data.template_file.task_definition 是一个模板数据源,它从文件中提供模板化的 JSON。但是,这不起作用,因为 JSON 包含新行和空格。

我已经发现我可以使用 replace 插值函数来消除新行和空格,但是我仍然需要转义双引号,以便 AWS API 接受请求。

如何安全地准备由data.template_file.task_definition.rendered 生成的字符串?我正在寻找这样的东西:

原始字符串:

{
  "key": "value",
  "another_key": "another_value"
}

准备好的字符串:

{\"key\":\"value\",\"another_key\":\"another_value\"}

【问题讨论】:

    标签: amazon-web-services terraform aws-cli hcl


    【解决方案1】:

    您应该能够使用 jsonencode function 包装呈现的 JSON。

    使用以下 Terraform 代码:​​

    data "template_file" "example" {
      template = file("example.tpl")
    
      vars = {
        foo = "foo"
        bar = "bar"
      }
    }
    
    resource "null_resource" "update_task_definition" {
      triggers = {
        keys = uuid()
      }
    
      provisioner "local-exec" {
        command = <<EOF
    echo ${jsonencode(data.template_file.example.rendered)}
    EOF
      }
    }
    

    还有以下模板文件:

    {
      "key": "${foo}",
      "another_key": "${bar}"
    }
    

    运行 Terraform 应用会提供以下输出:

    null_resource.update_task_definition: Creating...
      triggers.%:    "" => "1"
      triggers.keys: "" => "18677676-4e59-8476-fdde-dc19cd7d2f34"
    null_resource.update_task_definition: Provisioning with 'local-exec'...
    null_resource.update_task_definition (local-exec): Executing: ["/bin/sh" "-c" "echo \"{\\n  \\\"key\\\": \\\"foo\\\",\\n  \\\"another_key\\\": \\\"bar\\\"\\n}\\n\"\n"]
    null_resource.update_task_definition (local-exec): {
    null_resource.update_task_definition (local-exec):   "key": "foo",
    null_resource.update_task_definition (local-exec):   "another_key": "bar"
    null_resource.update_task_definition (local-exec): }
    

    【讨论】:

    • 看起来vars { 应该是vars = {
    • @mathieux51 感谢您的指点。我已经从旧的 HCL1 语法更新为 HCL2 语法。一般来说,我不会回顾我的数百个 HCL1 答案并对其进行转换,但是如果有人建议对答案进行编辑或 cmets,我很乐意对其进行更新,尤其是迫在眉睫的 0.14 版本现在使 0.12 成为一个非常旧的版本。
    • 您好我有一个类似的问题:stackoverflow.com/questions/65938396/… 我正在尝试为日志记录 JSON 消息编码 json,只是想知道什么是 .tpl 文件,如何生成它?我应该把我的 json 消息放在那个文件里吗?
    猜你喜欢
    • 1970-01-01
    • 2019-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-06
    • 2020-03-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多