Terraform - 如何在特定子网上循环

Terraform - How to loop on Specific subnets

我是创建 4 个子网的 运行 terraform,其中 2 个子网是 public,名称以“public”开头。

子网代码

私有子网

resource "aws_subnet" "private-subnet-az-a" {
  availability_zone = "us-east-1a"
  vpc_id = aws_vpc.vpc-homework2.id
  cidr_block = "10.0.1.0/24"
  map_public_ip_on_launch = false
}
resource "aws_subnet" "private-subnet-az-b" {
  availability_zone = "us-east-1b"
  vpc_id = aws_vpc.vpc-homework2.id
  cidr_block = "10.0.2.0/24"
  map_public_ip_on_launch = false
}
## Public subnet
resource "aws_subnet" "public-subnet-az-a" {
  availability_zone = "us-east-1a"
  vpc_id = aws_vpc.vpc-homework2.id
  cidr_block = "10.0.3.0/24"
  map_public_ip_on_launch = true
}
resource "aws_subnet" "public-subnet-az-b" {
  availability_zone = "us-east-1b"
  vpc_id = aws_vpc.vpc-homework2.id
  cidr_block = "10.0.4.0/24"
  map_public_ip_on_launch = true
}

创建负载均衡器时,我需要在 public 日落时附加它 - 我已经尝试了 For,正如您在示例中看到的那样,但它不起作用

## 创建 lb 代码; [对于 aws_subnet.public-[*].id 中的子网:子网]

resource "aws_lb" "nlb" {
    name               = "nlb-web"
    internal           = false
    load_balancer_type = "network"
    subnets            = [for subnet in aws_subnet.public-[*].id : subnet]
}

你不能构造这样的循环。这样做的正确方法是创建一个 map 并使用 for_each 创建您的子网:

variable "subnets"  {
  default = {
      private-subnet-az-a = {
          cidr_block = "10.0.1.0/24"
          map_public_ip_on_launch = false
          availability_zone = "us-east-1a"
      }
      private-subnet-az-a = {
          cidr_block = "10.0.1.0/24"
          map_public_ip_on_launch = false
          availability_zone = "us-east-1b"
      }
      # and so on      
  }
}

resource "aws_subnet" "subnet" {

  for_each = var.subnets

  availability_zone = each.value.availability_zone
  vpc_id = aws_vpc.vpc-homework2.id
  cidr_block = each.value.cidr_block
  map_public_ip_on_launch = each.value.map_public_ip_on_launch
}


resource "aws_lb" "nlb" {
    name               = "nlb-web"
    internal           = false
    load_balancer_type = "network"
    subnets            = [for key, subnet in aws_subnet.subnet : subnet.id if length(regexall("public.*", key)) > 0]
}