首页 > 解决方案 > Terraform - 循环

问题描述

是否可以创建一个循环来创建这些资源?相同的资源有很多重复。我尝试使用地图创建一个循环,但地图不接受任何其他默认块。

或者手动创建所有4个资源是否正常?只是一些建议作为答案就足够了,我正在尝试自己学习。

resource "aws_subnet" "public-test-a" {
  vpc_id = aws_vpc.vpc-test-02.id
  cidr_block = "10.0.0.16/28"
  map_public_ip_on_launch = true
  availability_zone = var.AZ[1]

  tags = {
    Name = var.subnets_names[index]
  }
}

resource "aws_subnet" "public-test-b" {
  vpc_id = aws_vpc.vpc-test-02.id
  cidr_block = "10.0.0.16/28"
  map_public_ip_on_launch = true
  availability_zone = var.AZ[1]

  tags = {
    Name = "public-test-b"
  }
}

resource "aws_subnet" "private-test-a" {
  vpc_id = aws_vpc.vpc-test-02.id
  cidr_block = "10.0.0.32/28"
  availability_zone = var.AZ[0]

  tags = {
    Name = "private-test-a"
  }
}


resource "aws_subnet" "private-test-b" {
  vpc_id = aws_vpc.vpc-test-02.id
  cidr_block = "10.0.0.48/28"
  availability_zone = var.AZ[1]

  tags = {
    Name = "private-test-b"
  }
}

我正在尝试这样的事情,但它似乎无效。

我们也不能aws_vpc.vpc-test-02.id在变量内部使用,因为它是另一个 tf.

variable "subnets" {
  type = map

  default = {
    vpc_id = aws_vpc.vpc-test-02.id
  }

  public-test-a = {
    map_public_ip_on_launch = true
    availability_zone = var.AZ[0]
  }

  public-test-b = {
    map_public_ip_on_launch = true
    availability_zone = var.AZ[1]
  }

  private-test-a = {
    availability_zone = var.AZ[0]
  }

  private-test-b = {
    availability_zone = var.AZ[1]
  }
}

variable "AZ" {
  type = list
  default = ["ap-south-1a", "ap-south-1b", "ap-south-1c"]
}

variable "subnets_cird" {
  type = list
  default = ["10.0.0.0/28", "10.0.0.16/26", "10.0.0.32/28", "10.0.0.48/28"]
}


variable "subnets_names" {
  type = list
  default = ["public-test-a", "public-test-b", "private-test-a", "private-test-b"]
}

标签: loopsterraform

解决方案


对于 terraform 文档中的此搜索计数和 for_each。下面是一个示例,您可以如何将 public-test-a 和 public-test-b 替换为一个 public-test:

variable "number_of_subnets" {
default = 2
}

resource "aws_subnet" "public-test" {
  count = var.number_of_subnets
  vpc_id = aws_vpc.vpc-test-02.id
  cidr_block = "10.0.0.16/28"
  map_public_ip_on_launch = true
  availability_zone = var.AZ[1]

  tags = {
    # here you pick the right name according to the subnet index, where e.g subnets_names = ["public-test-a","public-test-b"]
    Name = var.subnets_names[count.index]
  }
}

对 private_test 也可以这样做。

关于你尝试过的事情。变量不能被分配另一个变量。要实现此功能,请使用 locals:

locals {
   x = aws_vpc.vpc-test-02.id
}

然后访问像

local.x

推荐阅读