简体   繁体   中英

Terraform use existing policy for s3 bucket

In my terraform config I have a policy attached to some roles .
How can I reuse this policy when creating an s3 bucket?


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}"
}

Unfortunately, I get an error: Error putting S3 policy: MalformedPolicy: Policies must be valid JSON and the first byte must be '{' .

Seems that policy needs a json config in heredoc -notation, but I have to re-use the existing policy.
How can I reference that policy in s3-bucket creation?

You have multiple ways to achieve that. You can have a policy JSON and reference it in every bucket:

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

Or you can create a data block:

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

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

And you that on buckets:

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"
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM