简体   繁体   中英

Take ECS Task Definition environment variables from Terraform input variables

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM