【问题标题】:Terraform - loopsTerraform - 循环
【发布时间】:2020-11-13 19:23:30
【问题描述】:

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

或者手动创建所有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"]
}

【问题讨论】:

    标签: loops terraform


    【解决方案1】:

    对于这个搜索计数和 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
    

    【讨论】:

      猜你喜欢
      • 2021-03-02
      • 1970-01-01
      • 2020-12-24
      • 2021-07-08
      • 2021-12-08
      • 2020-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多