Terraform ECS 任务定义 jsonencode 问题

Terraform ECS Task Definition jsonencode issue

我在应用 Terraform 时遇到此错误。我的 env_Vars 显然有问题。我试过用引号或不用引号引起来的名字和价值。

Error: ECS Task Definition container_definitions is invalid: Error decoding JSON: json: cannot unmarshal number into Go struct field KeyValuePair.Environment.Value of type string

本地人:

locals {
  task_name = "${var.project_name}-${var.environment}-pgadmin"
  env_vars = [
    {
      name  = "ENV",
      value = var.environment
    },
    {
      name  = "POSTGRES_HOST",
      value = module.rds.db_address
    },
    {
      name  = "POSTGRES_USER",
      value = module.rds.db_username
    },
    {
      name  = "POSTGRES_PORT",
      value = module.rdsdb_port
    }
  ]
}

任务定义模板:

data "template_file" "task-definition" {

template = file("${path.module}/container_definition_template.json.tpl")

  vars = {
    container_name        = local.task_name
    container_image       = "dpage/pgadmin4"
    container_port        = 3001
    env_variables         = jsonencode(local.env_vars)
    secrets               = jsonencode(local.secrets)
  }
}

任务定义:

resource "aws_ecs_task_definition" "pgadmin_task_definition" {
  family                = local.task_name
  container_definitions = data.template_file.task-definition.rendered
  task_role_arn         = aws_iam_role.ecsTaskRole.arn

  network_mode             = "awsvpc"
  cpu                      = 1024
  memory                   = 2048
  requires_compatibilities = ["FARGATE"]
  execution_role_arn       = aws_iam_role.ecsTaskExecutionRole.arn
}

实际 json 模板是:

 [
  {
    "name": "${container_name}",
    "image": "${container_image}",
    "startTimeout": 120,
    "logConfiguration": {
      "logDriver": "awslogs",
      "options": {
        "awslogs-group": "${aws_logs_group}",
        "awslogs-region": "${aws_region}",
        "awslogs-stream-prefix": "${aws_log_stream_prefix}"
      }
    },
    "environment": ${env_variables},
    "secrets": ${secrets},
    "portMappings": [
      {
        "containerPort": ${container_port},
        "hostPort": ${container_port}
      }
    ]
  }
]

我认为发生这种情况是因为 module.rdsdb_portlocal.env_vars 中的数字,而不是字符串。你可以试试:

      value = tostring(module.rdsdb_port)