Learning Terraform: Can you use nested loops to create clusters of instances?

I have recently been learning Terraform and have been looking for an answer to this. Can I use nested loops to create clusters of instances?

My thoughts are that I could loop around the clusters with “for_each”, then (this is the bit i don’t understand how to do) I could loop around a list of node IDs in each cluster and create a number of instances related to each node ID record.

Below is my pseudo code which may better explain what i’m trying to do:

### main.tf ##
module "ec2_instance" {
  loop around 'clusters'. Use for_each?
    loop around 'node_ids'. How?
      create the current node instance with name of "'cluster_name'.'node_id[i]'" of type 'node_type[i]' here.

### variables.tf ##
variable "clusters" {

  type = map(object({
    node_id    = list(string)
    node_type  = list(string)

  default = {
    "cluster_name" = {
      node_id   = ["node-a", "node-b", "node-c"]
      node_type = ["t3.micro", "t3.small", "t3.medium"]

### stuff.tfvars ##
clusters = {
  cluster01 = {
    node_ids = ["a", "b", "c"]
    node_types = ["t3.micro", "t3.small", "t3.medium"]
  cluster02 = {
    node_ids = ["x", "y", "z"]
    node_types = ["t3.medium", "t3.small", "t3.small"]

Any help or insight would be greatly appreciated. I’m very new to Terraform, so this may have been a silly question, but i’ve been stuck trying to do this so figured i’d ask for help.

I’m hoping that if I get an answer to this, I can use it to go one step further and use a list of disks sizes for each node. So that Terraform would be able to create multiple clusters of nodes, each node having different disk sizes.

It’s kind of possible, but not particularly nice, or easy.

You do indeed use for_each, but this is only capable of one level of looping. Which means that you have to use the Terraform expression language to flatten all the looping you want to do into a single map - and pass that to for_each.

Here is an example I wrote recently: Multiple iteration in one resource - #2 by maxb

1 Like

Thanks, i’ll have a read through that. Yes, i’ve heard it might be a bit unwieldy due to the way Terraform handles loops.