【问题标题】:How to add a condition in terraform iam policy? based on some value如何在 terraform iam 策略中添加条件?基于一些价值
【发布时间】:2021-11-19 12:32:22
【问题描述】:

您好,我已将我的局部变量声明如下,

locals {
  incoming_messages_queue = local.production == 1 ? 
["${aws_sqs_queue.my_queue1.arn}",
  "$"{aws_sqs_queue.my_queue2.arn}] : 
["${aws_sqs_queue.my_queue1.arn}]
}

现在基于环境,即只有在生产时,我想创建一个允许两个队列的策略,或者在策略中只允许一个队列,如下所示,

resource "aws_iam_role_policy" "myservice_service_messaging" {
  role = aws_iam_role.myservice_service.name

  policy = <<POLICY
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
              "sns:CreateTopic",
               "sns:Publish"
             ],
    },
    {
       "Effect": "Allow",
       "Action": [
               "sqs:GetQueueUrl",
               "sqs:ReceiveMessage",
               "sqs:DeleteMessage",
               "sqs:ChangeMessageVisibility"
       ],
       "Resource": "${local.incoming_messages_queue}"  #==> How to handle here based on condition
    },
    .................
    POLICY

}

基本上,如果条件为真,我想在策略中添加多个资源,如果条件为假,我只想在策略中添加一个资源。我也尝试了 for 循环,它在政策下不起作用。有人可以解释一下我该如何解决这个问题吗?

【问题讨论】:

  • 您是在问如何将 HCL2 列表转换为 JSON 字符串列表?您只需使用 jsonencode 函数。
  • 我没有使用 jsonencode ,因为当我尝试它时,我收到以下错误“重复资源“aws_iam_role_policy”配置”。当我使用 policy =
  • 将 HCL2 转换为 JSON 不会导致重复声明错误。

标签: amazon-web-services terraform amazon-iam


【解决方案1】:

通过字符串连接生成 JSON(字符串模板就是这样做的)在获取正确语法方面充满挑战,因为 JSON 对标点符号的使用非常敏感。

因此,我(和 the Terraform docs)建议始终使用 the jsonencode function 生成 JSON,以便您可以专注于生成适当的数据结构,并让 Terraform 成为担心使用正确 JSON 表示该值的人语法。

当您使用jsonencode 时,您可以在其参数中编写普通的 Terraform 表达式,因此您可以直接内联使用条件表达式:

resource "aws_iam_role_policy" "myservice_service_messaging" {
  role = aws_iam_role.myservice_service.name

  policy = jsonencode({
    Version = "2012-10-17"
    Statement = [
      {
        Effect = "Allow"
        Action = [
          "sns:CreateTopic",
          "sns:Publish",
        ]
      },
      {
        Effect = "Allow"
        Action = [
          "sqs:GetQueueUrl",
          "sqs:ReceiveMessage",
          "sqs:DeleteMessage",
          "sqs:ChangeMessageVisibility",
        ]
        Resource = (
          local.production == 1 ? 
          [aws_sqs_queue.my_queue1.arn, aws_sqs_queue.my_queue2.arn] :
          [aws_sqs_queue.my_queue1.arn]
        )
      },
    ]
  })
}

如果您在模块的其他地方需要 Resource ARN 列表,那么您仍然可以根据需要将其分解为本地值。在这种情况下,你会写:

        Resource = local.incoming_messages_queue

(不过,因为它是一个列表,所以给它一个复数名称会更惯用,比如local.incoming_message_queues。)

【讨论】:

    猜你喜欢
    • 2021-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-19
    • 2021-08-28
    • 2018-01-11
    • 2017-08-17
    • 1970-01-01
    相关资源
    最近更新 更多