Terraform 0.11 — dynamic creation of a map.

Jacek Kikiewicz
1 min readDec 12, 2018

--

Problem:

You need a resource that as an input requires a map which can be populated by a list output from another resource. I came across this issue a couple of times, but most recently when I tried to build backend service (google_compute_backend_service) which as input takes an array of maps with instance group links (google_compute_instance_group.default.self_link).

Example:

When I create an instance groups with ‘count > 1’ and need to use their self_link attribute as input for another resource, I can get a list of them like this:

google_compute_instance_group.default.*.self_link

above list will have:

google_compute_instance_group.default.0.self_link = http://instance1
google_compute_instance_group.default.1.self_link = http://instance2
google_compute_instance_group.default.2.self_link = http://instance3

and so on… a normal list.

As input for my backend service
(resource: google_compute_backend_service) I need a map in following format:

backend {
group = "${google_compute_instance_group.default.0.self_link}"
}
backend{
group = "${google_compute_instance_group.default.0.self_link}"
}

So tricky question is, how to convert one into the other in a dynamic way?

Solution:

Use a null_resource triggers to create a dynamic map and then use that as input:

// Creating a dynamic map
resource "null_resource" "default" {
count = 3
triggers {
group = "${element(google_compute_instance_group.default.*.self_link, count.index)}"
}
}

and then in your resource:

// Using dynamic map
backend = ["${null_resource.default.*.triggers}"]

Also, have a look at my other Terraform articles on medium!

--

--