2

我正在尝试使用 Terraform 部署 ECS 任务定义。这是我的 ECS 任务定义资源代码:

resource "aws_ecs_task_definition" "my_TD" {
  family                   = "my_container"
  container_definitions    = <<DEFINITION
    [{
      "name": "my_container",
      "image": "${format("%s:qa", var.my_ecr_arn)}",
      "portMappings": [
        {
          "containerPort": 80,
          "hostPort": 80
        }
      ],
      "memory": 300,
      "networkMode": "awsvpc",
      "environment": [
        {
          "name": "PORT",
          "value": "80"
        },
        {
          "name": "Token",
          "value": "xxxxxxxx"
        }
      ]
    }
  ]
  DEFINITION
  requires_compatibilities = ["EC2"]
  network_mode             = "awsvpc"
  cpu                      = "256"
  memory                   = "512"
  task_role_arn            = var.ecs_role
  execution_role_arn       = var.ecs_role
}

环境变量在这里是硬编码的。因此,我尝试从 terraform 输入中获取这些环境变量。所以,我修改了:

variable "my_env_variables"{
  default = [
        {
          "name": "PORT",
          "value": "80"
        },
        {
          "name": "token",
          "value": "xxxxx"
        }
      ]
}

...
...
"environment" : "${var.my_env_variables}"
...
...

它给了我这样的问题:

var.my_env_variables is tuple with 1 element

Cannot include the given value in a string template: string required.

我是 Terraform 的新手。我该如何解决这个问题?

4

1 回答 1

2

您需要 json 字符串,可以使用jsonencode获得。因此,您可以尝试以下方法:

resource "aws_ecs_task_definition" "my_TD" {
  family                   = "my_container"
  container_definitions    = <<DEFINITION
    [{
      "name": "my_container",
      "image": "${format("%s:qa", var.my_ecr_arn)}",
      "portMappings": [
        {
          "containerPort": 80,
          "hostPort": 80
        }
      ],
      "memory": 300,
      "networkMode": "awsvpc",
      "environment": ${jsonencode(var.my_env_variables)}
    }
  ]
  DEFINITION
  requires_compatibilities = ["EC2"]
  network_mode             = "awsvpc"
  cpu                      = "256"
  memory                   = "512"
  task_role_arn            = var.ecs_role
  execution_role_arn       = var.ecs_role
}
于 2020-09-29T05:08:14.213 回答