2
votes

Terraform v0.10.7 AWS provider version = "~> 1.54.0"

Are there any examples how to translate a string or list into a map in Terraform?

We are setting up Consul key/value store like this:

consul kv put common/rules/alb/service1 name=service1,port=80,hcproto=http,hcport=80

I can access keys and values properly, and now I am trying to use values as a map in Terraform:

data "consul_key_prefix" "common" {
  path_prefix = "common/rules"
}

output "common"{
value = "${jsonencode(lookup(var.CommonRules,element(keys(var.CommonRules),1))) }"
}

$ terraform output

common = "{name=service1,port=80,hcproto=http,hcport=80}"

But when I try to access it as a map, it doesn't work:

output "common"{
value = "${lookup(jsonencode(lookup(var.CommonRules,element(keys(var.CommonRules),1))),"name") }"
}

$ terraform output

(no response)

I tried few things here - e.g. splitting these values and joining them again into a list, and then running "map" function but it doesn't work either:

$ terraform output

common = [
    name,
    service1,
    port,
    80,
    hcproto,
    http,
    hcport,
    80
]

and then trying to create map of that list:

output "common2" {
value = "${map(split(",",join(",",split("=",lookup(var.CommonRules,element(keys(var.CommonRules),1))))))}"
}

but it doesn't work either.

So my question would be - does anyone has working example where he did translated string (or list) into a map?

Thanks in advance.

1
Have you tried using the external data source as defined in this question. It looks like if you echo out the output from the consul_key_prefix data source in the external data source, the output of that will be a map based on its json output.SomeGuyOnAComputer
Yes, it would work with External data source, thanks, however for this one I wanted to see if there is any way to use only Terraform, but looks like there is not in Terraform < v0.12Igor

1 Answers

2
votes

jsondecode function in upcoming Terraform v0.12 would be the tool to solve this problem.

jsondecode function github issue