从 Terraform 输入变量中获取 ECS 任务定义环境变量

Take ECS Task Definition environment variables from Terraform input variables

我正在尝试使用 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 的新手。我该如何解决这个问题?

您需要 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
}