动态数据政策内容

Man*_*ich 0 terraform terraform-provider-aws terraform0.12+

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

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
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

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

问题说明:

问题是,如果我只想传递某个值,它将无法工作,因为它会形成一个空值

如果我只添加身份记录,这就是 terraform 在这种情况下应用的内容

  + 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"
        }
    )
Run Code Online (Sandbox Code Playgroud)

由此出现的问题是:

创建 IAM 角色名称-角色时出错:MalformedPolicyDocument:策略中的主体无效:com.amazon.balsa.error.InvalidPolicyException:传入的策略有一个没有主体的语句!

Nic*_*ick 5

这应该可以解决问题:

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
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

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