简体   繁体   English

创建内联策略以通过 terraform 附加 IAM 用户

[英]Create Inline policy to attach with IAM user via terraform

I am trying to create a single inline policy to attach with multiple IAM user in my terraform module.我正在尝试创建一个内联策略以附加到我的 terraform 模块中的多个 IAM 用户。

This is my main.tf这是我的 main.tf

locals {
  name_prefix = var.environment
}

resource "aws_iam_user" "npdata" {
  count = length(var.username)
  name = element(var.username,count.index )
  tags = merge({
    Name = element(var.username,count.index )
    },
    var.default_tags,
  )
}

resource "aws_iam_user_policy" "lb_ro" {
  name = "test"
  user = element(aws_iam_user.npdata.*.name,count.index)
  policy = jsonencode({
    Version = "2012-10-17"
    Statement = [
      {
        actions = [
         "s3:GetObject",
         "s3:ListBucket",
         "s3:PutObject",
         "s3:GetObjectVersion"
    ]
        Effect   = "Allow"
        resources = [
          var.dev_arn,
          var.prd_arn
    ]
      },
    ]
  })
}

but terraform plan is giving error但 terraform 计划出错

Error: Reference to "count" in non-counted context

  on modules/iam-user/main.tf line 18, in resource "aws_iam_user_policy" "lb_ro":
  18:   user = element(aws_iam_user.npdata.*.name,count.index)

The "count" object can only be used in "module", "resource", and "data"
blocks, and only when the "count" argument is set.

How can I use count to provide list of IAM users to resource aws_iam_user_policy我如何使用 count 为资源aws_iam_user_policy提供 IAM 用户列表

You're trying to use the count.index variable here:您正在尝试在此处使用count.index变量:

user = element(aws_iam_user.npdata.*.name,count.index)

But you haven't declared a count for the aws_iam_user_policy resource, so that variable doesn't exist.但是您还没有为aws_iam_user_policy资源声明count ,因此该变量不存在。

Additionally, you can't assign a single inline policy to multiple users, so you will have to create multiple inline policy resources.此外,您不能将单个内联策略分配给多个用户,因此您必须创建多个内联策略资源。 So you need to add count = length(var.username) to the aws_iam_user_policy resource.因此,您需要将count = length(var.username)添加到aws_iam_user_policy资源。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM