简体   繁体   English

如何在 Terraform 中为 aws-cli 准备呈现的 JSON?

[英]How to prepare rendered JSON for aws-cli in Terraform?

In another thread I have asked how to keep ECS task definitions active in AWS.在另一个线程中,我询问了如何在 AWS 中保持ECS 任务定义处于活动状态。 As a result I am planning to update a task definition like this:因此,我计划更新这样的任务定义:

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 is a template data source which provides templated JSON from a file. data.template_file.task_definition是一个模板数据源,它从文件中提供模板化的 JSON。 However, this does not work, since the JSON contains new lines and whitespaces.但是,这不起作用,因为 JSON 包含新行和空格。

I figured out already that I can use the replace interpolation function to get rid of new lines and whitespaces, however I still require to escape double quotes so that the AWS API accepts the request.我已经发现我可以使用replace插值函数来删除新行和空格,但是我仍然需要转义双引号,以便 AWS API 接受请求。

How can I safely prepare the string resulting from data.template_file.task_definition.rendered ?如何安全地准备由data.template_file.task_definition.rendered产生的字符串? I am looking for something like this:我正在寻找这样的东西:

Raw string:原始字符串:

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

Prepared string:准备好的字符串:

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

You should be able to wrap the rendered JSON with the jsonencode function .您应该能够使用jsonencode函数包装呈现的 JSON。

With the following Terraform code:使用以下 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
  }
}

And the following template file:以及以下模板文件:

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

Running a Terraform apply gives the following output:运行 Terraform apply 会产生以下输出:

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): }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM