come fare riferimento alle risorse create con for_each in terraform

Aug 20 2020

Questo è quello che sto cercando di fare. Ho 3 gateway NAT distribuiti in zone di disponibilità separate. Ora sto cercando di creare 1 tabella di route per le mie sottoreti private che puntano al gateway NAT. In terraform ho creato i gateway NAT utilizzando for_each. Ora sto cercando di associare questi gateway NAT a una tabella di instradamento privata e ricevo un errore perché ho creato i gateway NAT utilizzando for_each. In sostanza, sto cercando di fare riferimento a risorse create con for_each in una risorsa che non ho bisogno di usare "for_each". Di seguito è riportato il codice e il messaggio di errore. Tutto il consiglio sarebbe apprezzato.

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}"
  }
}

Errore

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.

Risposte

2 JDD Aug 20 2020 at 01:23

Il problema è che stai facendo riferimento each.keyalla nat_gateway_id proprietà della "aws_route_table" "nat"risorsa senza un for_eachpunto qualsiasi in quella risorsa o sottoblocco.

Aggiungi un for_each a quella risorsa e questo dovrebbe fare il trucco:

Ecco un esempio di codice (non testato):

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
  }
}