Terraform : "Error decoding JSON: json: cannot unmarshal string into Go struct field ContainerDefinition" aws_ecs_task_definition resource

Advertisements

I copied this resource block from terraform docs and update the values. But when I trigger the pipeline I’m getting below error and couldn’t solve it.

My version:
source = "hashicorp/aws"
version = "~> 3.0"

My resouce:

resource "aws_ecs_task_definition" "aws-ecs-task" {
  family                   = "${var.app_name}-task"
  network_mode             = "awsvpc"
  requires_compatibilities = ["FARGATE"]
  cpu                      = 256
  memory                   = 512
  execution_role_arn       = aws_iam_role.ecsTaskExecutionRole.arn
  task_role_arn            = aws_iam_role.ecsTaskExecutionRole.arn
  container_definitions = jsonencode([
    {
      name        = "${var.app_name}-${var.app_environment}-container"
      image       = "${var.repository_url}:latest"
      essential   = true
      environment = "${var.app_environment}"
      essential = true
      portMappings = [
        {
          containerPort = 8080
          hostPort      = 8080
        }
      ]
    }
  ])
  tags = {
    Name        = "${var.app_name}-ecs-td"
    Environment = var.app_environment
  }
}

My error output:

Error: ECS Task Definition container_definitions is invalid: Error decoding JSON: json: cannot unmarshal string into Go struct field ContainerDefinition.Environment of type []*ecs.KeyValuePair
  on application/cluster/cluster.tf line 84, in resource "aws_ecs_task_definition" "aws-ecs-task":
  84:   container_definitions = jsonencode([
  85:     {
  86:       name        = "${var.app_name}-${var.app_environment}-container"
  87:       image       = "${var.repository_url}:latest"
  88:       essential   = true
  89:       environment = "${var.app_environment}"
  90:       essential = true
  91:       portMappings = [
  92:         {
  93:           containerPort = 8080
  94:           hostPort      = 8080
  95:         }
  96:       ]
  97:     }
  98:   ])

>Solution :

According to https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/ecs_task_definition the environment needs to be of the form:

[
  {"name": "VARNAME", "value": "VARVAL"}
]

In your case that would translate to something like

environment = [{"name": "environment", "value": "${var.app_environment}"}]

Leave a ReplyCancel reply