首页 > 解决方案 > 如何将两个模板文件连接成一个文件并传递到 terraform 中的 ECS 容器任务定义

问题描述

我有两个模板文件。我想将这些模板文件合并为一个,并将它们传递到aws_ecs_task_definition资源中的 ECS 属性container_definitions 。

Terraform 版本 => v0.14.9

nginx.tpl.json:

 [
    {
        "name": "nginx",
        "image": "public.ecr.aws/nginx/nginx:latest",
        "portMappings": [
            {
                "containerPort": 80,
                "hostPort": 80,
                "protocol": "tcp"
            }
        ]
    }
 ]

redis.json.tpl:

 [
    {
        "name": "redis",
        "image": "public.ecr.aws/peakon/redis:6.0.5",
        "portMappings": [
            {
                "containerPort": 6379,
                "hostPort": 6379,
                "protocol": "tcp"
            }
        ]
    }
 ]

当像下面这样手动组合两个模板文件时,它正在工作。但是随着 Terraform concatformat出现错误。

 [
    {
        "name": "nginx",
        "image": "public.ecr.aws/nginx/nginx:latest",
        "portMappings": [
            {
                "containerPort": 80,
                "hostPort": 80,
                "protocol": "tcp"
            }
        ]
    },
    {
        "name": "redis",
        "image": "public.ecr.aws/peakon/redis:6.0.5",
        "portMappings": [
            {
                "containerPort": 6379,
                "hostPort": 6379,
                "protocol": "tcp"
            }
        ]
    }
 ]

data "template_file" "ecs_task" {
  template = format("%s%s",file("./ecs/templates/nginx.json.tpl"),
                            file("./ecs/templates/redis.json. tpl")
              )
} => Here I need to combine the two template files and then pass them onto the container_definitions to the below resource.
resource "aws_ecs_task_definition" "testapp" {
  family                = "testapp"
  network_mode          = "awsvpc"
  cpu                   = 256
  memory                = 512
  container_definitions = data.template_file.ecs_task.rendered # I'm getting the following error.
}

错误:invalid character '}' looking for the beginning of object key string

有人可以帮我解决这个问题吗?

标签: terraform

解决方案


更新

从文件中删除括号

    {
        "name": "nginx",
        "image": "public.ecr.aws/nginx/nginx:latest",
        "portMappings": [
            {
                "containerPort": 80,
                "hostPort": 80,
                "protocol": "tcp"
            }
        ]
    }


    {
        "name": "redis",
        "image": "public.ecr.aws/peakon/redis:6.0.5",
        "portMappings": [
            {
                "containerPort": 6379,
                "hostPort": 6379,
                "protocol": "tcp"
            }
        ]
    }

然后代替 "%s%s". 似乎您缺少逗号: "[%s,%s]"


推荐阅读