I have an IAM terraform module that needs to take a list of ARNs as an input and use templatefile() to modify an IAM template. I’m getting an error because terraform lists add a trailing comma which IAM doesn’t like. Is this a limitation of the templatefile() function? If not, how can I use this function with an IAM template?
The error that I am getting is:
Error: "policy" contains an invalid JSON: invalid character ']' looking for beginning of value
on main.tf line 84, in resource "aws_iam_role_policy" "iam_dynamoDB_policy_rw_list":
84: resource "aws_iam_role_policy" "iam_dynamoDB_policy_rw_list" {
Here’s the user input:
arn_list = ["arn:aws:dynamodb:*:1234567890:table/taco","arn:aws:dynamodb:*:1234567890:table/taco1","arn:aws:dynamodb:*:1234567890:table/taco2"]
Here’s the relevant portion of the terraform script:
locals {
arn_fmt = formatlist("\"%s\",", var.arn_list)
arn_map = { arn_list = local.arn_fmt }
}
resource "aws_iam_role_policy" "iam_dynamoDB_policy_rw_list" {
count = var.accesstype == "rw_list" ? length(local.role_names) : 0
name = "${var.accesstype}-dynamo-${local.policy_name}-${var.aws_region}-${local.aws_account_id}"
policy = templatefile("${path.module}/files/iam_policy/taco.json.tpl", local.arn_map)
role = element(local.role_names, count.index)
}
Here’s the IAM template that I’m trying to modify:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "VisualEditor0",
"Effect": "Allow",
"Action": [
"dynamodb:BatchWriteItem",
"dynamodb:PutItem",
"dynamodb:DescribeTable",
"dynamodb:DeleteItem",
"dynamodb:UpdateItem"
],
"Resource": [
%{ for arn in arn_list ~}
${arn}
%{ endfor ~}
]
}
]
}