running Terraform 1.7.4
for each row in arg map my SSM automation needs
{
"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\": \"<first value from arg_map>\", \"key3\": \"<second value from arg_map>\"}"
}
}
main.tf
provider "aws" {
region = "us-east-1" # Set your desired region here
}
variable "account_number" {
default = "123456789"
}
variable "arg_map" {
type = map(list(string))
default = {
"key" = ["a", "b"]
"key" = ["d", "e"]
"key" = ["g", "h"]
"key" = ["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
]
}
running terraform apply
│ Error: Invalid function argument │ │ on main.tf line 23, in resource "aws_ssm_document" "sync_epv2asm": │ 23: content = templatefile("${path.module}/ssm_document_template.tftpl", { │ 24: account_number = var.account_number │ 25: arg_map = var.arg_map │ 26: }) │ ├──────────────── │ │ while calling templatefile(path, vars) │ │ var.arg_map is a map of list of string │ │ Invalid value for "vars" parameter: vars map does not contain key "key", referenced at ./ssm_document_template.tftpl:7,44-47.
googling around is not finding anything. I even tried some of the AI to see if they and identify my problem.
some of the things on the internet were showing "{}" the template around the "%". that did not change my error.
any thoughts on why I cannot get the template to work?
Since you are trying to create a JSON document,
templatefileis almost never enough by itself to achieve that. Based on the documentation fortemplatefile, you can also use the built-injsonencodefunction with the template. It should look something like the following:The plan output shows the result like this:
I've trimmed the example to use only two keys, but this should work for any number of keys.
NOTE: You also have to append the Lambda version to the Lambda ARN, either using
$LATESTor a version number, otherwise, the SSM document will throw an error:Apply output: