使用 Terraform 创建 S3 策略

Creating S3 policy with terraform

我正在尝试创建 S3 存储桶并对其应用策略。存储桶创建步骤很好,当我尝试应用以下策略时,我无法在此 tf 文件中找到错误

terraform 版本是 - Terraform v0.12.23

{
        "Sid": "DenyUnEncryptedConnection",
        "Effect": "Deny",
        "Principal": "*",
        "Action": "*",
        "Resource": [
             "arn:aws:s3:::${var.s3_bucketName}",
             "arn:aws:s3:::${var.s3_bucketName}/*"
        ],
        "Condition": {
            "Bool": {
                "aws:SecureTransport": "false"
            }
        }
    }

在我的 main.tf 文件中,这是我传递给变量的内容

  module "s3-bucket-policy" {
  source                            = "../s3-policy/"
  s3_bucketName                     = "${aws_s3_bucket.s3_bucket.id}"
  bucket_arn                        = "${aws_s3_bucket.s3_bucket.arn}"
....

terraform plan 命令给我的策略如下。(运行 它是通过 Jenkins 作业从 Jenkins 日志中复制出来的)

    module.s3_bucket.module.s3-bucket-policy.aws_s3_bucket_policy.communication_policy[0][0m will be created[0m[0m
00:00:07.805 [0m  [32m+[0m[0m resource "aws_s3_bucket_policy" "communication_policy" {
00:00:07.805       [32m+[0m [0m[1m[0mbucket[0m[0m = (known after apply)
00:00:07.805       [32m+[0m [0m[1m[0mid[0m[0m     = (known after apply)
00:00:07.805       [32m+[0m [0m[1m[0mpolicy[0m[0m = (known after apply)
00:00:07.805     }

但是当我尝试应用相同的方法时出现以下错误,我不确定如何继续。

 [31m
00:01:13.117 [1m[31mError: [0m[0m[1mError putting S3 policy: MalformedPolicy: Action does not apply to any resource(s) in statement
00:01:13.117    status code: 400, [0m
00:01:13.117 

非常感谢任何对此的指点

您需要提供与您的存储桶兼容的适当 Action,将您的策略​​更改为以下内容,它应该会起作用:

resource "aws_s3_bucket" "my_bucket" {
  bucket = "my-bucket"

  acl    = "public-read"
  policy = <<EOF
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "DenyUnEncryptedConnection",
            "Effect": "Deny",
            "Principal": "*",
            "Action": "s3:*",
            "Resource": [
                "arn:aws:s3:::my-bucket",
                "arn:aws:s3:::my-bucket/*"
            ],
            "Condition": {
                "Bool": {
                    "aws:SecureTransport": "false"
                }
            }
        }
    ]
}
EOF
}

(我将资源更改为使用 bucket_arn,但它应该可以像您那样与 s3_bucketName 一起使用。)

注意 "Action": "s3:*",当请求满足条件 "aws:SecureTransport": "false"(即它不是 HTTPS 连接)时,此策略明确拒绝存储桶和对象上的所有 actions