Terraform AWS How to create count instance that every intance get self subnet?

Viewed 26

I create two subnets:

resource "aws_subnet" "ws_net_public-a" {
  vpc_id = aws_vpc.ws_net.id
  cidr_block = "10.0.10.0/24"
  map_public_ip_on_launch = true
  availability_zone = data.aws_availability_zones.available.names[0]
  tags = {
    "Name" = "WS Public-A"
  }
}

resource "aws_subnet" "ws_net_public-b" {
  vpc_id = aws_vpc.ws_net.id
  cidr_block = "10.0.20.0/24"
  map_public_ip_on_launch = true
  availability_zone = data.aws_availability_zones.available.names[1]
  tags = {
    "Name" = "WS Public-B"
  }
}

And create two instance with 'count' (i know how do that is simple without 'count', but do that with 'count'):

resource "aws_instance" "webserver" {
  count = 2
  ami = lookup(var.ec2_ami, var.region) 
  instance_type = lookup(var.instance_type, var.region)
  root_block_device {
    volume_type = "gp2"
    volume_size = 8
    encrypted = false
  }
  tags = {
    Name = "ws-${count.index}"
  }
  // key_name = var.key_name
  vpc_security_group_ids = [aws_security_group.ws_sg.id]
  subnet_id = format("%s/%s/%s",aws_subnet.ws_net_public-,var.zones[count.index],".id")
}

I get error: "A managed resource "aws_subnet" "ws_net_public" has not been declared in the root module". This is rightly. But how fix that? )

1 Answers

You have to use count meta-argument in both places, i.e., in the subnet and the instance code. So the changes you would have to make are:

resource "aws_subnet" "ws_net_public" {
  count                   = 2
  vpc_id                  = aws_vpc.ws_net.id
  cidr_block              = "10.0.${count.index+1}0.0/24"
  map_public_ip_on_launch = true
  availability_zone       = data.aws_availability_zones.available.names[count.index]
  tags = {
    "Name" = "WS Public-${count.index}"
  }
}

resource "aws_instance" "webserver" {
  count         = 2
  ami           = lookup(var.ec2_ami, var.region) 
  instance_type = lookup(var.instance_type, var.region)
  root_block_device {
    volume_type = "gp2"
    volume_size = 8
    encrypted = false
  }
  tags = {
    Name = "ws-${count.index}"
  }
  // key_name = var.key_name
  vpc_security_group_ids = [aws_security_group.ws_sg.id]
  subnet_id              = aws_subnet.ws_net_public[count.index].id
}
Related