Skip to content

Instantly share code, notes, and snippets.

@brikis98
Last active March 14, 2023 23:43
Show Gist options
  • Star 57 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save brikis98/f3fe2ae06f996b40b55eebcb74ed9a9e to your computer and use it in GitHub Desktop.
Save brikis98/f3fe2ae06f996b40b55eebcb74ed9a9e 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}"
}
@Ak476024
Copy link

Ak476024 commented Jun 2, 2020

After I have switched from Terraform 0.11 to Terraform 0.12.. It's really got simple and easy to work with loops and other stuff. Try using this syntax

locals {
 parameters = [
           {     
                  name : "rds.force_ssl",
                  value : "1"
                  apply_method : "pending-reboot"
            },
            {     
                 name : "ssl",
                  value : "1",
                  apply_method : "pending-reboot"
            }
     ]
}

resource "aws_db_parameter_group" "parameter_group" {
  name   = var.name
  family = var.family

  dynamic "parameter" {
    for_each = var.parameters

    content {
      name   = parameter.value["name"]
      value  = parameter.value["value"]
      apply_method = parameter.value["apply_method"]
    }
  }
}`
```

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment