0

我正在使用 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

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

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 范围以便填充所需的范围?

4

1 回答 1

1

您可以创建一个本地块。

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))}"
于 2022-03-01T14:11:09.153 回答