使用Terraform创建AWS Batch作业定义时template_file报错求助
解决Terraform创建AWS Batch作业定义的JSON解析错误
问题场景
尝试通过Terraform的template_file数据源生成AWS Batch作业定义的容器属性,直接使用file函数加载JSON文件赋值给container_properties时可正常运行,但使用模板渲染后触发以下错误:
AWS Batch Job container_properties is invalid: Error decoding JSON: json: cannot unmarshal array into Go value of type batch.ContainerProperties
错误原因
模板中的JSON最外层被包裹在数组[]中,但AWS Batch的container_properties参数要求传入单个JSON对象,而非数组。直接用file加载时,原始JSON文件应为无外层数组的单个对象,因此能正常解析;模板渲染后输出数组格式,导致AWS无法反序列化。
此外,docker_command变量当前以带方括号的字符串形式传入,不符合AWS Batch对command字段(字符串数组)的格式要求。
解决方案
- 移除模板JSON的外层数组包裹,仅保留单个容器属性对象
- 使用
jsonencode函数处理命令参数,生成合法的JSON数组字符串 - 确保资源规格参数(memory、vcpu)以字符串类型传入(符合AWS字段要求)
修正后的代码示例
1. 模板文件(job_definition.json)
{ "command": ${docker_command}, "image": "${docker_image}", "resourceRequirements": [ { "type": "MEMORY", "value": "${memory}" }, { "type": "VCPU", "value": "${vcpu}" } ], "jobRoleArn": "${job_role_arn}", "volumes": [ { "host": { "sourcePath": "/mnt/efs" }, "name": "efs" } ], "mountPoints": [ { "sourceVolume": "efs", "containerPath": "/mnt/efs", "readOnly": false } ] }
2. Terraform代码(使用template_file数据源)
data "template_file" "dev_jd_template" { template = file("./data/job_definition.json") vars = { docker_command = jsonencode(["python", "/app/data_migrator.py"]) docker_image = "python:3.9.9-slim-bullseye" memory = "1024" vcpu = "1" job_role_arn = "arn:aws:iam::xxxxxxxx:role/AWSBatchJobRole" } } resource "aws_batch_job_definition" "job_definition" { name = "dev-jd-3" type = "container" platform_capabilities = ["EC2"] container_properties = data.template_file.dev_jd_template.rendered }
3. 更简洁的写法(使用templatefile函数,Terraform 0.12+推荐)
resource "aws_batch_job_definition" "job_definition" { name = "dev-jd-3" type = "container" platform_capabilities = ["EC2"] container_properties = templatefile("./data/job_definition.json", { docker_command = jsonencode(["python", "/app/data_migrator.py"]) docker_image = "python:3.9.9-slim-bullseye" memory = "1024" vcpu = "1" job_role_arn = "arn:aws:iam::xxxxxxxx:role/AWSBatchJobRole" }) }
内容的提问来源于stack exchange,提问作者vin'm
相关产品推荐
相关产品推荐

