Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

loop over the variable in terraform

Tags:

terraform

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)}"
like image 496
Arbab Nazar Avatar asked Dec 15 '22 08:12

Arbab Nazar


1 Answers

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
like image 54
jpsecher Avatar answered Dec 30 '22 10:12

jpsecher