Terraform 将 IP 范围添加到存储桶策略

Terraform Add IP Range to Bucket Policy

我正在使用 terraform 创建一个 s3 存储桶,需要向其添加一个存储桶策略,以将一组 IP 地址列入白名单。

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
}

我遇到的问题是,虽然 var.foo_ipvar.bar_ip 是单个 IP 地址,但 var.foobar_ip 是 IP 地址范围。 10.0.0.0 - 10.0.0.200

我不想把 IP 地址写 200 次,比如

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

All the way to 200

有没有办法传入这个 IP 范围,以便填充所需的范围?

您可以创建一个本地块。

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

然后你的保单就变成了

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