Home > Blockchain >  The "count" object can only be used in "module", "resource", and "
The "count" object can only be used in "module", "resource", and "

Time:06-30

I'm trying to deploy a subnet to each of 3 availability zones in AWS. I have my public subnet resource block have a count of 3 to deploy 3 subnets, one to each az

resource "aws_subnet" "public_subnet" {
  count                   = length(var.azs)
  vpc_id                  = aws_vpc.vpc.id
  cidr_block              = var.public_cidrs[count.index]
  availability_zone       = var.azs[count.index]
  map_public_ip_on_launch = true

  tags = {
    Name = "${var.name}-public-subnet"
  }
}

That worked fine, now I'm trying to deploy a nat gateway to each subnet and that's where I'm having issues. Here's my nat gateway resource block

resource "aws_nat_gateway" "nat_gateway" {
  allocation_id = aws_eip.nat_eip.id
  subnet_id     = aws_subnet.public_subnet[count.index].id

  tags = {
    Name = "${var.name}-NAT-gateway"
  }

It's giving me this error

│ Error: Reference to "count" in non-counted context
│
│   on main.tf line 48, in resource "aws_nat_gateway" "nat_gateway":
│   48:   subnet_id     = aws_subnet.public_subnet[count.index].id
│
│ The "count" object can only be used in "module", "resource", and "data" blocks, and only when the "count"       
│ argument is set.

I know that this error is occurring because I don't have a count argument in my NAT gateway resource block, but on Terraforms docs, I can't use count as an argument for NAT gateways. So how exactly do I accomplish what I'm trying to do? I want 3 NAT gateways, one in each subnet and I can't figure out how to achieve that

CodePudding user response:

You can create NAT for each subnest as follows:

resource "aws_nat_gateway" "nat_gateway" {

  count         = length(aws_subnet.public_subnet)

  allocation_id = aws_eip.nat_eip.id
  subnet_id     = aws_subnet.public_subnet[count.index].id

  tags = {
    Name = "${var.name}-NAT-gateway"
  }

You will have problem with EIP, as you can't reuse the same EIP for three different NATs. But this is an issue for a new question.

  • Related