策略中的 S3 存储桶名称,terraform

S3 bucketname in policy, terraform

我正在创建一个存储桶来存储 lb 日志。我不想对名称进行硬编码,因为由于 s3 的唯一名称要求,这会导致我的代码中断。我正在使用 terraform 提供的 bucket_prefix。

在bucket policy中我需要s3 bucket的名字,我的代码如下:

resource "aws_s3_bucket" "aws-s3-lb-logs" {
  acl = "private"
  force_destroy = true
  bucket_prefix = "some-prefix"


  policy = <<POLICY
{
  "Id": "Policy",
  "Statement": [
    {
      "Action": [
        "s3:PutObject"
      ],
      "Effect": "Allow",
      "Resource": "arn:aws:s3:::${aws_s3_bucket.aws-s3-lb-logs.bucket}/AWSLogs/*",
      "Principal": {
        "AWS": [
          "${data.aws_elb_service_account.main.arn}"
        ]
      }
    }
  ]
}
POLICY
}

当我尝试在策略中调用 ${aws_s3_bucket.aws-s3-lb-logs.bucket} 时,出现错误:

Error: Self-referential block

  on main.tf line 350, in resource "aws_s3_bucket" "aws-s3-lb-logs":
 350:       "Resource": "arn:aws:s3:::${aws_s3_bucket.aws-s3-lb-logs.bucket}/AWSLogs/*",

Configuration for aws_s3_bucket.aws-s3-lb-logs may not refer to itself.

我知道我不能调用同一个资源块,但在这种情况下,我如何获取 s3 存储桶的名称以放入策略块?

解决方案是使用单独的资源 (aws_s3_bucket_policy) 来设置存储桶策略。

resource "aws_s3_bucket" "aws-s3-lb-logs" {
  acl = "private"
  force_destroy = true
  bucket_prefix = "some-prefix"
}

resource "aws_s3_bucket_policy" "aws-s3-lb-logs" {
  bucket = aws_s3_bucket.aws-s3-lb-logs.id

  policy = <<POLICY
{
  "Id": "Policy",
  "Statement": [
    {
      "Action": [
        "s3:PutObject"
      ],
      "Effect": "Allow",
      "Resource": "arn:aws:s3:::${aws_s3_bucket.aws-s3-lb-logs.bucket}/AWSLogs/*",
      "Principal": {
        "AWS": [
          "${data.aws_elb_service_account.main.arn}"
        ]
      }
    }
  ]
}
POLICY
}