简体   繁体   中英

How do I specify unmarshall types with JSON encode in Terraform?

I am working on building a fargate cluster and am having difficulties following the documentation for the aws_ecs_task_definition section ( https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/ecs_task_definition )

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

The error is pointing to the value for CPU. This would normally be another variable but I'm just testing out inputs to try and get it to pass. Annoyingly enough, if I set the value to a number, I get a different error: cannot unmarshal number into Go struct field KeyValuePair.Environment.Value of type string .

Any ideas?

Your analysis of the first error is correct: it is due to cpu having to be an integer / number / int64. That means you need to specify it as "cpu": 256 .

The second error then tells you not to look at ContainerDefinition.Cpu but KeyValuePair.Environment.Value which is the "environment": [ ... ] section. The problem here is that keys and values have to be string s and even though you write "${var.app_env_runner_sleep_secs}" terraform still outputs a number despite the " surrounding it. To fix that you need to put a tostring around the argument: "value": "${tostring(var.app_env_runner_sleep_secs)}" .

Note that additionally depending on your terraform version it is a lot shorter and cleaner to write eg "awslogs-region": var.region by removing the "${...}" in all places.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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