Reputation: 23811
I am really new to terraform and want to make this work. I am able to create the vpc, public subnets and get their ids, now I want to create an ec2 instance inside each of this subnet, when I try to run the ec2 module, it only create the instance inside the first subnet and ignore the other subnet(s). Here is snippet of my code.
OUTPUT the subnet ids:
output "public_subnets_id" {
value = "${join(",", aws_subnet.public.*.id)}"
}
here the example output of this:
public_subnets_id = subnet-84aae6f4,subnet-a12124e8
Here is my my code, where I am trying to split it and create the instance inside each subnet but can only create to the first subnet.
subnet_id = "${element(split(",", var.subnet_id), count.index)}"
Upvotes: 5
Views: 10067
Reputation: 4879
I spread out EC2 instances in different availability zones like this:
variable "zones" {
default = {
zone0 = "us-east-1a"
zone1 = "us-east-1b"
zone2 = "us-east-1c"
}
}
variable "cidr_blocks" {
default = {
zone0 = "172.32.0.0/20"
zone1 = "172.32.16.0/20"
zone2 = "172.32.32.0/20"
}
}
variable "dockerhost_instances" {
default = "5"
}
resource "aws_subnet" "public-subnet" {
...
cidr_block = "${lookup(var.cidr_blocks, format("zone%d", count.index))}"
availability_zone = "${lookup(var.zones, format("zone%d", count.index))}"
count = 3
}
resource "aws_instance" "host" {
...
subnet_id = "${element(aws_subnet.public-subnet.*.id,count.index)}"
count = "${var.dockerhost_instances}"
}
Because the ${element(...)}
function wraps around, the result is three subnets and five hosts spread out over the subnets:
us-east-1a : host.0 host.3
us-east-1b : host.1 host.4
us-east-1c : host.2
Upvotes: 11
Reputation: 45333
Seems the problem is at resource "aws_instance"
define,
count ="${length(split(",", var.subnet_id))}"
If you directly set count to 2, will you get two instances?
My understand is, the count for ec2 resource should be set as default, such as 2, or define ec2_num
to a number in variable.tf directly, then call it by var.ec2_num
in resource ec2
Upvotes: 1