【问题标题】:How to pass a list in template_file var section instead of string, in terraform如何在 terraform 中传递 template_file var 部分中的列表而不是字符串
【发布时间】:2021-06-10 00:32:05
【问题描述】:

我有多个 SQS 队列,并希望在 IAM 策略资源部分中包含这些 SQS 队列 arn。有没有一个体面的方法来做到这一点?我试图将 sqs 队列 arn 列表传递给 var 部分,但看起来 terraform 需要此部分中的字符串

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
   }
}

这个想法是通过 vars 部分传递 SQS arn 列表,以便在 lambda_policy 文件中的资源部分中替换它

lambda_policy 文件 =>

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

不确定我做错了,还是有更好的方法。想法是堆叠所有创建的 sqs 队列 arns 以传递给策略模板文件,因此可以使用这些列表(在资源部分中)编译策略;并且该策略将在创建时传递给 lambda。

【问题讨论】:

    标签: amazon-web-services terraform terraform-provider-aws


    【解决方案1】:

    最好使用templatefile。所以你可以:

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

    lambda_policy.tmpl 在哪里:

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

    【讨论】:

    • 谢谢。会试试这个,并会在这里更新这是怎么回事。
    • 另请注意,这是在文档部分Generating JSON or YAML from a template 中讨论的情况,它推荐了一种不同的方法来确保有效的 JSON 语法。
    • @MartinAtkins 谢谢你提醒我。下次我会尽量记住这一点。
    猜你喜欢
    • 2019-12-04
    • 2022-08-18
    • 2021-04-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-22
    • 2011-04-18
    • 2021-06-06
    • 2021-09-30
    相关资源
    最近更新 更多