Skip to content

Instantly share code, notes, and snippets.

@icy
Forked from brikis98/main.tf
Created February 1, 2022 14:56
Show Gist options
  • Save icy/de14edea6629f299c5771247f8621108 to your computer and use it in GitHub Desktop.
Save icy/de14edea6629f299c5771247f8621108 to your computer and use it in GitHub Desktop.
A hacky way to create a dynamic list of maps in Terraform
# The goal: create a list of maps of subnet mappings so we don't have to statically hard-code them in aws_lb
# https://www.terraform.io/docs/providers/aws/r/lb.html#subnet_mapping
locals {
# These represent dynamic data we fetch from somewhere, such as subnet IDs and EIPs from a VPC module
subnet_ids = ["subnet-1", "subnet-2", "subnet-3"]
eips = ["eip-1", "eip-2", "eip-3"]
}
# Here's the hack! The null_resource has a map called triggers that we can set to arbitrary values.
# We can also use count to create a list of null_resources. By accessing the triggers map inside of
# that list, we get our list of maps! See the output variable below.
resource "null_resource" "subnet_mappings" {
count = "${length(local.subnet_ids)}"
triggers {
subnet_id = "${element(local.subnet_ids, count.index)}"
allocation_id = "${element(local.eips, count.index)}"
}
}
# And here's the result! We have a dynamic list of maps. I'm just outputting it here, but we should
# be able to take the same value and set it as the input to aws_lb's subnet_mapping param.
output "subnet_mappings" {
value = "${null_resource.subnet_mappings.*.triggers}"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment