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

이 검색 횟수와 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 {
   x = aws_vpc.vpc-test-02.id
}

다음과 같은 값에 액세스하십시오.

local.x