aws_iam_policy 和 aws_iam_role_policy 之间的区别

Difference between aws_iam_policy and aws_iam_role_policy

我有一个 aws_iam_role,我想向其添加政策。通常,我会使用 aws_iam_role 创建策略并将其附加到具有 aws_iam_role_policy_attachment 的角色。

但是,我看过一些使用 aws_iam_role_policy 的文档,在我看来,它们似乎在做同样的事情。

我是正确的还是有细微的差别我遗漏了?

区别是Managed policies and inline policies

当您创建 aws_iam_policy 时,这是一个托管策略,可以是 re-used。

当您创建 aws_iam_role_policy 内联策略时

For a given role, aws_iam_role_policy resource is incompatible with using the aws_iam_role resource inline_policy argument. When using that argument and this resource, both will attempt to manage the role's inline policies and Terraform will show a permanent difference.

重现上述状态的代码

resource "aws_iam_role_policy" "test_policy" {
  name = "test_policy"
  role = aws_iam_role.test_role.id

  # Terraform's "jsonencode" function converts a
  # Terraform expression result to valid JSON syntax.
  policy = jsonencode({
    Version = "2012-10-17"
    Statement = [
      {
        Action = [
          "ec2:Describe*",
        ]
        Effect   = "Allow"
        Resource = "*"
      },
    ]
  })
}

resource "aws_iam_role" "test_role" {
  name = "test_role"

  assume_role_policy = jsonencode({
    Version = "2012-10-17"
    Statement = [
      {
        Action = "sts:AssumeRole"
        Effect = "Allow"
        Sid    = ""
        Principal = {
          Service = "ec2.amazonaws.com"
        }
      },
    ]
  })
}
resource "aws_iam_role" "role" {
  name = "test-role1"

  assume_role_policy = <<EOF
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Action": "sts:AssumeRole",
      "Principal": {
        "Service": "ec2.amazonaws.com"
      },
      "Effect": "Allow",
      "Sid": ""
    }
  ]
}
EOF
}

resource "aws_iam_policy" "policy" {
  name        = "test-policy"
  description = "A test policy"

  policy = <<EOF
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Action": [
        "ec2:Describe*"
      ],
      "Effect": "Allow",
      "Resource": "*"
    }
  ]
}
EOF
}
resource "aws_iam_role_policy_attachment" "test-attach" {
  role       = aws_iam_role.role.name
  policy_arn = aws_iam_policy.policy.arn
}