Terraform对S3存储桶使用现有策略

时间:2019-05-28 08:01:21

标签: amazon-web-services amazon-s3 terraform

在我的Terraform配置中,我有一个policy附加到某个roles上。
创建s3存储桶时如何重用此策略?


resource "aws_iam_policy" "s3-read-access" {
  name   = "my-warehouse-read-access"
  version = "2019-05-28"
  policy = "${data.aws_iam_policy_document.s3-read-access.json}"
}

resource "aws_s3_bucket" "my-warehouse" {
  bucket = "my-bucket"
  acl    = "private"
  policy = "${aws_iam_policy.s3-read-access.arn}"
}

不幸的是,我收到一个错误:Error putting S3 policy: MalformedPolicy: Policies must be valid JSON and the first byte must be '{'

似乎policy需要使用heredoc表示法的json配置,但是我必须重用现有策略。
如何在s3-bucket创建中引用该策略?

1 个答案:

答案 0 :(得分:1)

您可以通过多种方式实现这一目标。您可以拥有一个策略JSON并在每个存储桶中对其进行引用:

resource "aws_s3_bucket" "b" {
  bucket = "s3-website-test.hashicorp.com"
  acl    = "public-read"
  policy = "${file("policy.json")}"
}

或者您可以创建一个数据块:

data "aws_iam_policy_document" "your_super_amazing_policy" {
 count  = "${length(keys(var.statement))}"

  statement {
    sid       = "CloudfrontBucketActions"
    actions   = ["s3:GetObject"]
    resources = ["*"]
  }

还有你那桶子里的

resource "aws_s3_bucket" "private_bucket" {
  bucket = "acme-private-bucket"
  acl = "private"
  policy = "${data.aws_iam_policy_document.your_super_amazing_policy.json}"

  tags {
    Name = "private-bucket"
    terraform = "true"
  }
}