terraform에서 for_each로 생성 된 리소스를 참조하는 방법

Aug 20 2020

이것이 제가하려는 것입니다. 별도의 AZ에 3 개의 NAT 게이트웨이를 배포했습니다. 이제 NAT 게이트웨이를 가리키는 프라이빗 서브넷에 대해 1 개의 라우팅 테이블을 생성하려고합니다. terraform에서 for_each를 사용하여 NAT 게이트웨이를 만들었습니다. 이제 for_each를 사용하여 NAT 게이트웨이를 생성했기 때문에 이러한 NAT 게이트웨이를 프라이빗 라우팅 테이블과 연결하려고하는데 오류가 발생합니다. 기본적으로 "for_each"를 사용할 필요가없는 리소스에서 for_each로 만든 리소스를 참조하려고합니다. 다음은 코드 및 오류 메시지입니다. 조언을 주시면 감사하겠습니다.

resource "aws_route_table" "nat" {
  vpc_id = aws_vpc.main.id

  route {
    cidr_block     = "0.0.0.0/0"
    nat_gateway_id = aws_nat_gateway.main[each.key].id
  }

  tags = {
    Name = "${var.vpc_tags}_PrivRT" } } resource "aws_eip" "main" { for_each = aws_subnet.public vpc = true lifecycle { create_before_destroy = true } } resource "aws_nat_gateway" "main" { for_each = aws_subnet.public subnet_id = each.value.id allocation_id = aws_eip.main[each.key].id } resource "aws_subnet" "public" { for_each = var.pub_subnet vpc_id = aws_vpc.main.id cidr_block = cidrsubnet(aws_vpc.main.cidr_block, 8, each.value) availability_zone = each.key map_public_ip_on_launch = true tags = { Name = "PubSub-${each.key}"
  }
}

오류

Error: Reference to "each" in context without for_each



on vpc.tf line 89, in resource "aws_route_table" "nat":
  89:     nat_gateway_id = aws_nat_gateway.main[each.key].id

The "each" object can be used only in "resource" blocks, and only when the
"for_each" argument is set.

답변

2 JDD Aug 20 2020 at 01:23

문제는 해당 리소스 또는 하위 블록에 없는 리소스 속성 each.key에서 참조 하고 있다는 것 입니다.nat_gateway_id "aws_route_table" "nat"for_each

해당 리소스에 for_each를 추가하면 트릭을 수행해야합니다.

다음은 몇 가지 샘플 코드입니다 (테스트되지 않음).

resource "aws_route_table" "nat" {
  for_each = var.pub_subnet

  vpc_id = aws_vpc.main.id

  route {
      cidr_block     = "0.0.0.0/0"
      nat_gateway_id = aws_nat_gateway.main[each.key].id
  }
}