问题描述
我正在尝试使用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",{
"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.
解决方法
您需要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
}