动态数据策略内容

Dynamic data policy content

请帮忙理解如何创建这样的东西?

data "aws_iam_policy_document" "assume_role_policy" {
  statement {
    actions = ["sts:AssumeRole"]
    principals {
      type        = "Service"
      identifiers = ["ec2.amazonaws.com"]
    }
  }

  dynamic "statement" {
    for_each     = var.assume_role_identities != [] ? [true] : []
    content {
      actions = ["sts:AssumeRole"]
      principals {
        type        = "AWS"
        identifiers = var.assume_role_identities
      }
    }
  }

  dynamic "statement" {
    for_each     = var.assume_role_services != [] ? [true] : []
    content {
      actions = ["sts:AssumeRole"]
      principals {
        type        = "Service"
        identifiers = var.assume_role_services
      }
    }
  }
}

此代码的问题在于,如果我不指定任何应该具有访问权限的角色或服务,则会退出并出现错误,即没有主体。 是否可以在动态块上设置一些计数条件?或者如何解决?

问题说明:

如果我只想传递一个值,它不会工作,因为它形成一个空值的问题

如果我只添加身份记录,这就是 terraform 应用于此 casem 的内容

  + assume_role_policy    = jsonencode(
        {
          + Statement = [
              + {
                  + Action    = "sts:AssumeRole"
                  + Effect    = "Allow"
                  + Principal = {
                      + Service = "ec2.amazonaws.com"
                    }
                  + Sid       = ""
                },
              + {
                  + Action    = "sts:AssumeRole"
                  + Effect    = "Allow"
                  + Principal = {
                      + AWS = "arn:aws:iam::account_id:user/some_user"
                    }
                  + Sid       = ""
                },
              + {
                  + Action    = "sts:AssumeRole"
                  + Effect    = "Allow"
                  + Principal = {
                      + Service = []
                    }
                  + Sid       = ""
                },
            ]
          + Version   = "2012-10-17"
        }
    )

由此出现的问题:

Error creating IAM Role name-role: MalformedPolicyDocument: Invalid principal in policy: com.amazon.balsa.error.InvalidPolicyException: The passed in policy has a statement with no principals!

这应该可以解决问题:

data "aws_iam_policy_document" "assume_role_policy" {
  statement {
    actions = ["sts:AssumeRole"]
    principals {
      type        = "Service"
      identifiers = ["ec2.amazonaws.com"]
    }
  }

  dynamic "statement" {
    for_each     = length(var.assume_role_identities) > 0 ? [var.assume_role_identities] : []
    content {
      actions = ["sts:AssumeRole"]
      principals {
        type        = "AWS"
        identifiers = var.assume_role_identities
      }
    }
  }

  dynamic "statement" {
    for_each     = length(var.assume_role_services) > 0 ? [var.assume_role_services] : []
    content {
      actions = ["sts:AssumeRole"]
      principals {
        type        = "Service"
        identifiers = var.assume_role_services
      }
    }
  }
}

您甚至不需要第一个语句,您可以将其作为参数传递给 var.assume_role_services