Terraform Aws S3 – 限制除特定用户外的所有用户

108次阅读
没有评论

问题描述

在使用Terraform创建AWS S3存储桶时,希望将其限制为仅允许特定用户访问。用户已经编写了以下脚本,但似乎仍然允许所有用户对存储桶进行操作。

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}/*",
    ]
  }
}

解决方案

请注意以下操作注意版本差异及修改前做好备份。
为了限制特定用户对存储桶的访问,我们需要创建一个具有显式拒绝权限的存储桶策略。在存储桶策略中,我们可以使用NotPrincipal来指定拒绝访问的用户。
以下是一个存储桶策略的示例:

{
    "Id": "bucketPolicy",
    "Statement": [
        {
            "Action": "s3:*",
            "Effect": "Deny",
            "NotPrincipal": {
                "AWS": [
                    "arn:aws:iam::1234567890:user/alloweduser"
                ]
            },
            "Resource": [
                "arn:aws:s3:::examplebucket",
                "arn:aws:s3:::examplebucket/*"
            ]
        }
    ],
    "Version": "2012-10-17"
}

在Terraform中,我们可以使用data块来定义这个策略:

data "aws_iam_policy_document" "vulnerability-scans" {
  statement {
    not_principals {
      type        = "AWS"
      identifiers = [
        aws_iam_user.circleci.arn
      ]
    }
    effect = "Deny"
    actions = [
      "s3:*"
    ]
    resources = [
      aws_s3_bucket.vulnerability-scans.arn,
      "${aws_s3_bucket.vulnerability-scans.arn}/*",
    ]
  }
}

请注意,这个策略将拒绝除了arn:aws:iam::1234567890:user/alloweduser之外的所有用户对存储桶的访问。

正文完