Terraform AWS S3 - 拒绝除特定用户之外的所有人

Xer*_*xes 3 amazon-s3 amazon-web-services terraform terraform-provider-aws

我有一个需要限制为特定用户的存储桶,我编写了以下脚本,但它似乎仍然允许所有用户对该存储桶进行操作。

resource "aws_s3_bucket" "vulnerability-scans" {
  bucket = "vulnerability-scans"
}

resource "aws_s3_bucket_policy" "vulnerability-scans" {
  bucket = aws_s3_bucket.vulnerability-scans.id
  policy = data.aws_iam_policy_document.vulnerability-scans.json
}

data "aws_iam_policy_document" "vulnerability-scans" {
  statement {
    principals {
      type = "AWS"
      identifiers = [
        aws_iam_user.circleci.arn,
      ]
    }

    actions = [
      "s3:PutObject",
      "s3:GetObject",
      "s3:ListBucket",
    ]

    resources = [
      aws_s3_bucket.vulnerability-scans.arn,
      "${aws_s3_bucket.vulnerability-scans.arn}/*",
    ]
  }
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*o E 7

我认为您必须考虑到其他用户的Allow策略中可能有这些内容,因此这里的方法应该是拒绝任何不是您希望的用户的用户的访问。AWS 文档 [1] 中有详细的解释,但为了简洁起见,我认为 terraform 代码应该如下所示:

data "aws_iam_policy_document" "vulnerability-scans" {
  statement {
    sid    = "AllExceptUser"
    effect = "Deny"
    principals {
      type = "AWS"
      identifiers = ["*"]
    }

    actions = [
      "s3:PutObject",
      "s3:GetObject",
      "s3:ListBucket",
    ]

    resources = [
      aws_s3_bucket.vulnerability-scans.arn,
      "${aws_s3_bucket.vulnerability-scans.arn}/*",
    ]

    condition {
      test     = "StringNotLike"
      variable = "aws:userId"
      values = [
        aws_iam_user.circleci.arn
      ]
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

尽管参考 URL 表示它适用于 IAM 角色,但这同样适用于用户。条件StringNotLike运算符在[2]中有更详细的解释。


[1] https://aws.amazon.com/blogs/security/how-to-restrict-amazon-s3-bucket-access-to-a-specific-iam-role/

[2] https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String