【问题标题】:Terraform - Automatically create SGs for CloudFront IPsTerraform - 为 CloudFront IP 自动创建 SG
【发布时间】:2021-12-02 12:24:42
【问题描述】:

我正在尝试为 CloudFront IP 自动创建 SG,以便将它们关联到我的 ALB。

This article 非常了解如何实现它,但不幸的是它不适用于我的环境。

这是代码:

data "aws_ip_ranges" "cloudfront" {
  regions = ["global"]
  services = ["cloudfront"]
}

locals {
  chunks_v4 = chunklist(data.aws_ip_ranges.cloudfront.cidr_blocks, 60)
}

resource "aws_security_group" "cloudfront" {
    count = length(local.chunks_v4)

    ingress {
        from_port = 443
        to_port   = 443
        protocol  = "tcp"
        cidr_blocks = [local.chunks_v4[count.index]]
    }

    egress {
        from_port = 0
        to_port   = 0
        protocol  = "-1"
        cidr_blocks = ["0.0.0.0/0"]
    }

    lifecycle {
        create_before_destroy = true
    }
}

这就是错误信息:

╷
│ Error: Incorrect attribute value type
│ 
│   on main.tf line 34, in resource "aws_security_group" "cloudfront":
│   34:         cidr_blocks = [local.chunks_v4[count.index]]
│     ├────────────────
│     │ count.index is a number, known only after apply
│     │ local.chunks_v4 is a list of list of dynamic, known only after apply
│ 
│ Inappropriate value for attribute "cidr_blocks": element 0: string required.
╵

不应该是这样的:

local.chunks_v4[count.index][0 to 59???]

如何使用 Terraform 实现它?

【问题讨论】:

  • 好吧,我的错!我让 PyC​​harm 转换了旧语法,并在此处保留了括号: ["${local.chunks_v4[count.index]}"]

标签: terraform terraform-provider-aws aws-security-group


【解决方案1】:

编辑:由于有 60 个 CIDR 块的硬性限制,我们需要将其分成块,感谢@Marcin 的提醒!

locals {
  chunks_v4 = chunklist(data.aws_ip_ranges.cloudfront.cidr_blocks, 60)
}

data "aws_ip_ranges" "cloudfront" {
  regions  = ["global"]
  services = ["cloudfront"]
}

resource "aws_security_group" "cloudfront" {
  count = length(local.chunks_v4)

  ingress {
    from_port   = 443
    to_port     = 443
    protocol    = "tcp"
    cidr_blocks = local.chunks_v4[count.index]
  }

  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }

  lifecycle {
    create_before_destroy = true
  }
}

【讨论】:

  • 您确信这会奏效吗?我认为你可能会达到 SG 限制,因为我预计 Cloudfront 有很多 IP 范围。因此,OP 试图通过将data.aws_ip_ranges.cloudfront.cidr_blocks 拆分为小块来克服限制。
  • 我只是运行它来仔细检查。我得到“规则:RulesPerSecurityGroupLimitExceeded:已达到每个安全组的最大规则数”,data.aws_ip_ranges.cloudfront.cidr_blocks 中有多少元素?
  • 没有理由删除。我认为它的好答案。也许只是关于限制的一个小注释会很有用。
  • 我得到了同样的结果,但没有错误,terraform 运行良好。 Inbound rules (76) 我会记下这个限制。感谢@Marcin 的帮助!
  • @没问题。看起来不错。
猜你喜欢
  • 2021-11-03
  • 2018-01-27
  • 2020-08-08
  • 1970-01-01
  • 2017-10-22
  • 1970-01-01
  • 2021-10-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多