Terraform Add IP Range to Bucket Policy

Viewed 408

I'm creating an s3 bucket using terraform and need to add a bucket policy to it, to whitelist a bunch of IP addresses.

resource "aws_s3_bucket" "foo-bucket" {
  bucket = "foobar-bucket"

}
resource "aws_s3_bucket_policy" "foo-policy" {
  bucket = "foobar-bucket"
  policy = <<POLICY
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "HTTP",
      "Effect": "Deny",
      "Principal": "*",
      "Action": "*",
      "Resource": [
        "arn:aws:s3:::foobar-bucket/*",
        "arn:aws:s3:::foobar-bucket"
      ],
      "Condition": {
        "Bool": {
          "aws:SecureTransport": "false"
        }
      }
    },
    {
      "Sid": "IPAllow",
      "Effect": "Deny",
      "Principal": "*",
      "Action": "s3:*",
      "Resource": [
        "arn:aws:s3:::foobar-bucket/*",
        "arn:aws:s3:::foobar-bucket"
      ],
      "Condition": {
         "NotIpAddress": {
          "aws:SourceIp": [
            "${join("\", \"", concat(var.foo_ip,
  var.bar_ip,
var.foobar_ip))}"
        ]
      },
      "Bool": {
      "aws:ViaAWSService": "true"
      }
      }
    }
  ]
}
POLICY
}

The issue I have here is that while var.foo_ip and var.bar_ip are a single IP address, var.foobar_ip is an IP address range. 10.0.0.0 - 10.0.0.200

I don't want to have to write the IP address out 200 times, like

variable "foobar_ip" {
  type = list(string)
  default = [
    "10.0.0.0",
    "10.0.0.1",
    "10.0.0.2"
  ]
}

All the way to 200

Is there a way to pass in this IP range so that the required range is populated?.

1 Answers

You can create a locals block.

locals {
  cidr = "10.0.0.0/24"
  ip_addresses = [ for host_number in range(0, 201) : cidrhost(local.cidr, host_number) ]
}

And then your policy becomes

      "Sid": "IPAllow",
      "Effect": "Deny",
      "Principal": "*",
      "Action": "s3:*",
      "Resource": [
        "arn:aws:s3:::foobar-bucket/*",
        "arn:aws:s3:::foobar-bucket"
      ],
      "Condition": {
         "NotIpAddress": {
          "aws:SourceIp": [
            "${join("\", \"", concat(var.foo_ip,
  var.bar_ip,
local.ip_addresses))}"
Related