Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string or array to map in Terraform?

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.

like image 543
Igor Avatar asked Jun 26 '26 13:06

Igor


1 Answers

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

jsondecode function github issue

like image 197
chenrui Avatar answered Jun 28 '26 11:06

chenrui



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!