I am trying to deploy ECS task definition with Terraform. Here is my ECS task definition resource code:
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
}
The environment variables are hardcoded here. So, I tried to take those environment variables from terraform input. So, I modified with:
variable "my_env_variables"{
  default = [
        {
          "name": "PORT",
          "value": "80"
        },
        {
          "name": "token",
          "value": "xxxxx"
        }
      ]
}
...
...
"environment" : "${var.my_env_variables}"
...
...
It's giving me an issue like this:
var.my_env_variables is tuple with 1 element
Cannot include the given value in a string template: string required.
I am new to Terraform. How can I solve this issue?
You need json string, which you can get using jsonencode. So you could try the following:
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With