terraform,

Terraform output with loops: count and for_each

Jul 09, 2022 · 1 min read · 25 views · Post a comment

It’s not a new thing to loop through Terraform outputs though, so here are a few solutions that could help since count can’t be used as part of the output itself.

Prerequisites

  • Terraform

using count

main.tf:

resource "aws_subnet" "private" {
  count = length(var.private_subnets)

  vpc_id            = aws_vpc.this.id
  cidr_block        = var.private_subnets[count.index]
  availability_zone = var.azs[count.index]

  tags = merge(
    {
      "Name" = format("%s-${var.private_subnet_suffix}-%s", var.name, element(var.azs, count.index))
    },
    var.private_subnet_tags,
  )
}

outputs.tf:

output "private_subnets" {
  description = "List of private subnet IDs."
  value       = aws_subnet.private.*.id
}

using for_each

main.tf:

locals {
  virtual_machines = [
    {
      ip_address = "192.168.10.1"
      name       = "vm-1"
    },
    {
      ip_address = "192.168.10.2"
      name       = "vm-2"
    }
  ]
}    

resource "google_compute_instance" "devcoops" {
  for_each   = {
    for i, vm in local.virtual_machines:
    vm.name => vm 
  }

  name       = each.value.name
  ip_address = each.value.ip_address
}

outputs.tf (as a list):

output "google_vms_list" {
  value = values(google_compute_instance.devcoops)[*].name
}

outputs.tf (as a map):

output "google_vms_map" {
  value = { for k, v in google_compute_instance.devcoops : k => v.name }
}

Conclusion

Tried everything and nothing works? Let me know. On a side note, follow our official channel on Telegram.