How to pass a list in template_file var section instead of string, in terraform

Viewed 2693

I have a situation where I have multiple SQS queues, and want to include those SQS queue arns in IAM policy resource section. Is there a decent way to do it? I tried to pass the sqs queue arn list to var section, though it looks like terraform expects a string in this section

resource "aws_sqs_queue" "sqs_queue" {
   count                      = length(var.sqs_queue)
   name                       = element(var.sqs_queue, count.index)
   delay_seconds              = 0
   max_message_size           = var.sqs_max_message_size
   message_retention_seconds  = var.sqs_message_retention_seconds
   receive_wait_time_seconds  = 0
}

data "template_file" "lambda_policy" {
   template = file(var.lambda_policy)

   vars = {
     sqs_queues = aws_sqs_queue.sqs_queue[0].arn # want to change this to list of arn's
   }
}

The idea is to pass the list of SQS arn via vars section, so that it will get replaced in lambda_policy file, in resource section

lambda_policy file =>

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "sqs:ReceiveMessage",
                "sqs:DeleteMessage"
            ],
            "Resource": "${sqs_queues}"
        }
    ]
}

Not sure if i'm doing in the wrong way, or is there a better way to do it. Idea is to stack all created sqs queue arns to pass to policy template file, so the policy can be compiled with those lists (in resource section); and that policy will be passed to lambda when creating.

1 Answers

Its better to use templatefile. So you could have:

locals {

  policy=templatefile(
               "${path.module}/lambda_policy.tmpl",
               {
                 sqs_queues = aws_sqs_queue.sqs_queue[*].arn
               }
              )

}

where lambda_policy.tmpl is:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "sqs:ReceiveMessage",
                "sqs:DeleteMessage"
            ],
            "Resource": ${jsonencode(sqs_queues)}
        }
    ]
}
Related