Terraform - ลูป

Nov 13 2020

เป็นไปได้ไหมที่จะสร้างลูปที่สร้างทรัพยากรนี้ มีการซ้ำซากของทรัพยากรเดียวกันจำนวนมาก ฉันลองใช้แผนที่เพื่อสร้างลูป แต่แผนที่ไม่ยอมรับบล็อกเริ่มต้นอื่น ๆ

หรือเป็นเรื่องปกติที่จะสร้างทรัพยากรทั้ง 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"]
}

คำตอบ

2 FedorPetrov Nov 13 2020 at 11:14

สำหรับจำนวนการค้นหานี้และ for_each ในเอกสาร Terraform นี่คือตัวอย่างวิธีที่คุณสามารถแทนที่ public-test-a และ public-test-b ด้วยการทดสอบสาธารณะแบบเดียว:

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 {
   x = aws_vpc.vpc-test-02.id
}

จากนั้นเข้าถึงค่าเช่น

local.x