terraform 中 aws_iam_policy 资源中条件的语法

Sab*_*Boz 7 amazon-iam terraform

我目前正在尝试在 terraform 中实现 aws_iam_policy ,如下所示:

resource "aws_iam_policy" "policyName" {
  name        = "policyName"
  path        = "/"
 
  policy = jsonencode({
    Version = "2012-10-17"
    Statement = [
      {
        Effect = "Allow"
        NotAction = [
          "iam:*"
        ]
        Resource = "*"
 
        Condition = {
          test = "StringEquals"
          variable = "s3:prefix"
          values = [
            "home/"
          ]
        }
      }
    ]
  })
}
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试在团队中使用的环境中部署它时,我收到一条错误,指出此内容存在语法错误(日志仅指出起始行,而没有指出其他地方)。当我取出条件块时,错误消失了,所以我知道这与条件有关。我已经检查了 terraform 文档,它们没有=后条件,但是当我删除后,=我收到一条错误消息,指出这=是预期的。有人知道正确的语法/查找相关文档的正确位置吗(如前所述,https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/iam_policy_document上的文档不不适合我)?

小智 9

作为 Joel Van Hollebeke 答案的替代方案,对原始文档中的条件块进行简单更改也可以。

代替 :

    Condition = {
      test = "StringEquals"
      variable = "s3:prefix"
      values = [
        "home/"
      ]
    }
Run Code Online (Sandbox Code Playgroud)

用这个:

   Condition = {
      "StringEquals" = {
        "s3:prefix" = "home/"
      }
    }
Run Code Online (Sandbox Code Playgroud)

话虽如此,“aws_iam_policy_document”仍然是在 terraform 中执行此操作最推荐的方法。


Joe*_*eke 7

我会尝试一个aws_iam_policy_document数据块,如下例所示:

data "aws_iam_policy_document" "example" {

  statement {

    not_actions = [
      "iam:*",
    ]

    effect = "Allow"

    resources = [
      "*",
    ]

    condition {
      test     = "StringEquals"
      variable = "s3:prefix"
      values = [
        "home/"
      ]
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

然后添加aws_iam_policy引用此数据源的资源:

resource "aws_iam_policy" "policyName" {
  name   = "policyName"
  path   = "/"
  policy = data.aws_iam_policy_document.example.json
}
Run Code Online (Sandbox Code Playgroud)

根据我的经验,这种模式在配置 IAM 策略时产生了最佳验证。