如何在 Terraform 中使用 JSON 编码指定解组类型?

Rhi*_*rus 9 json unmarshalling amazon-web-services amazon-ecs terraform

我正在构建一个fargate集群,但在遵循aws_ecs_task_definition部分的文档时遇到困难(https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/ecs_task_definition

\n
\xe2\x94\x82 Error: ECS Task Definition container_definitions is invalid: Error decoding JSON: json: cannot unmarshal string into Go struct field ContainerDefinition.Cpu of type int64\n\xe2\x94\x82 \n\xe2\x94\x82   with aws_ecs_task_definition.app,\n\xe2\x94\x82   on ecs.tf line 40, in resource "aws_ecs_task_definition" "app":\n\xe2\x94\x82   40:   container_definitions = jsonencode([\n\xe2\x94\x82   41:     {\n\xe2\x94\x82   42:       "name": "${var.prefix}",\n\xe2\x94\x82   43:       "image": "${var.app_image}",\n\xe2\x94\x82   44:       "cpu": "256",\n\xe2\x94\x82   45:       "memory": "${var.fargate_memory}",\n\xe2\x94\x82   46:       "networkMode": "awsvpc",\n\xe2\x94\x82   47:       "logConfiguration": {\n\xe2\x94\x82   48:           "logDriver": "awslogs",\n\xe2\x94\x82   49:           "options": {\n\xe2\x94\x82   50:             "awslogs-group": "${aws_cloudwatch_log_group.ecs.name}",\n\xe2\x94\x82   51:             "awslogs-region": "${var.region}",\n\xe2\x94\x82   52:             "awslogs-stream-prefix": "ecs"\n\xe2\x94\x82   53:           }\n\xe2\x94\x82   54:       },\n\xe2\x94\x82   55:       "environment": [\n\xe2\x94\x82   56:         {"name": "ENV_RUNNER_SLEEP_SECS", "value": "${var.app_env_runner_sleep_secs}"}\n\xe2\x94\x82   57:       ]\n\xe2\x94\x82   58:     }\n\xe2\x94\x82   59:   ])\n
Run Code Online (Sandbox Code Playgroud)\n

该错误指向 CPU 的值。这通常是另一个变量,但我只是测试输入以尝试让它通过。令人烦恼的是,如果我将值设置为数字,则会收到不同的错误:cannot unmarshal number into Go struct field KeyValuePair.Environment.Value of type string

\n

有任何想法吗?

\n

luk*_*302 23

您对第一个错误的分析是正确的:这是由于cpu必须是整数/数字/int64。这意味着您需要将其指定为"cpu": 256.

然后第二个错误告诉您不要查看该ContainerDefinition.Cpu部分。这里的问题是键和值必须是s,即使你编写terraform 仍然会输出一个数字,尽管它周围有数字。要解决这个问题,您需要在参数周围加上一个: 。KeyValuePair.Environment.Value"environment": [ ... ]string"${var.app_env_runner_sleep_secs}""tostring"value": "${tostring(var.app_env_runner_sleep_secs)}"

请注意,此外,根据您的 terraform 版本,编写起来会更短、更清晰,例如"awslogs-region": var.region通过删除"${...}"所有地方的 。