Terraform 1.7.4动态生成SSM Automation文档报错求助
问题分析与解决
核心问题
你的代码存在两个关键错误,直接导致了报错:
1. 重复的Map Key
var.arg_map中所有条目使用了相同的key "key",Terraform的Map类型要求key必须唯一,重复key会被依次覆盖,最终arg_map只会保留最后一个条目"key" = ["j", "k"],完全不符合你生成多个步骤的需求。
2. 模板语法错误
你使用了错误的Terraform templatefile循环语法,导致模板无法正确识别循环变量:
- 正确的HCL2模板控制结构(for/if)需要用
%{ ... }%包裹,而非% ...: - 错误的语法使得模板将
${key}当作顶层模板变量(而非循环变量),但传入的vars字典中只有account_number和arg_map,没有key这个键,因此触发报错。
修正后的代码
main.tf(修正arg_map)
provider "aws" { region = "us-east-1" } variable "account_number" { default = "123456789" } variable "arg_map" { type = map(list(string)) default = { "step1" = ["a", "b"] "step2" = ["d", "e"] "step3" = ["g", "h"] "step4" = ["j", "k"] } } resource "aws_ssm_document" "sync_epv2asm" { name = "sync_epv2asm" document_type = "Automation" content = templatefile("${path.module}/ssm_document_template.tftpl", { account_number = var.account_number arg_map = var.arg_map }) }
ssm_document_template.tftpl(修正模板语法)
{ "schemaVersion": "0.3", "description": "My description.", "mainSteps": [ %{ for key, values in arg_map ~} { "description": "Invoke Lambda Function ${key}", "name": "InvokeLambdaFunction${key}", "action": "aws:invokeLambdaFunction", "inputs": { "FunctionName": "arn:aws:lambda:us-east-1:${account_number}:function:hello", "InvocationType": "RequestResponse", "Payload": "{\"key1\": \"${account_number}\", \"key2\": \"${values[0]}\", \"key3\": \"${values[1]}\"}" } }%{ if not loop.last },%{ endif ~} %{ endfor ~} ] }
关键语法说明
%{ ... }%:包裹Terraform模板的控制逻辑(循环、条件),是templatefile要求的标准语法~:用于消除模板生成时的多余空白和换行,确保最终生成的JSON格式合法- 唯一的Map Key:每个步骤对应一个唯一key,保证循环能遍历所有预期条目
内容的提问来源于stack exchange,提问作者peter cooke
相关产品推荐
相关产品推荐

