Terraform Conditional Bucket Policy Creation

Viewed 29

I have some terrform code, that creates bucket policies across a range of buckets.

resource "aws_s3_bucket_policy" "foo-bucket-policy" {
  count  = length(var.foo_policies)
  bucket = element(values(var.foo_policies[count.index]), 0)
  policy = <<POLICY
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "HTTP",
      "Effect": "Deny",
      "Principal": "*",
      "Action": "*",
      "Resource": [
        "arn:aws:s3:::${element(values(var.foo_policies[count.index]), 0)}/*",
        "arn:aws:s3:::${element(values(var.foo_policies[count.index]), 0)}"
      ],
      "Condition": {
        "Bool": {
          "aws:SecureTransport": "false"
        }
      }
    },
    {
      "Sid": "IPAllow",
      "Effect": "Deny",
      "Principal": "*",
      "Action": "s3:*",
      "Resource": [
        "arn:aws:s3:::${element(values(var.foo_policies[count.index]), 0)}/*",
        "arn:aws:s3:::${element(values(var.foo_policies[count.index]), 0)}"
      ],
      "Condition": {
         "NotIpAddress": {
          "aws:SourceIp": [
            "${join("\", \"", concat(var.my_ips,
     var.BAR_IPS))}"
        ]
       },
      "Bool": {
      "aws:ViaAWSService": "true"
      }
     }
   }
 ]
}
POLICY
}

And this is what var.foo_policies looks like.

variable "foo_policies" {
  type        = list(any)
  default = [
    { bucket-1 = "foo-bucket-1" },
    { bucket-2 = "foo-bucket-2" },
    { bucket-3 = "foo-bucket-3" },
    { bucket-4 = "foo-bucket-4" },
    { bucket-5 = "foo-bucket-5" },
    { bucket-6 = "foo-bucket-6" },
    { bucket-7 = "foo-bucket-7" }
  ]
}

However, I would like to change the bucket policy on foo-bucket-4 alone without touching the policies on the other buckets.

Is there a way to add a condition in Terraform to say,

if bucket = element(var.foo_policies[3]), use this templatefile, otherwise use the default inline policy

0 Answers
Related