Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Terraform map to string value

How do you parse a map variable to a string in a resource value with Terraform12?

I have this variable:

variable "tags" {
  type                = map
  default = {
    deployment_tool   = "Terraform"
    code              = "123"
  }
}

And want this: {deployment_tool=Terraform, code=123}

I've tried the following without success:

resource "aws_ssm_parameter" "myparamstore" {
  ***
  value = {
    for tag in var.tags:
      join(",",value, join("=",tag.key,tag.values))
  }
}
like image 931
Luis Avatar asked Sep 30 '20 09:09

Luis


People also ask

How do I get MAP value in Terraform?

You can use terraform lookup() function to get value of an element from a map based on key. lookup() retrieves the value of a single element from a map, given its key. If the given key does not exist, the given default value is returned instead.

What is Tomap in Terraform?

» tomap Function tomap converts its argument to a map value. Explicit type conversions are rarely necessary in Terraform because it will convert types automatically where required. Use the explicit type conversion functions only to normalize types returned in module outputs.


2 Answers

Replacing ":" with "=" is not a perfect solution, just consider a map with such a value: https://example.com - it becomes https=//example.com. That's not good.
So here is my solution:

environment_variables = join(",", [for key, value in var.environment_variables : "${key}=${value}"])
like image 109
mlukasik Avatar answered Oct 20 '22 22:10

mlukasik


Your requested output is just malformed JSON string. So you can convert your variable to json using jsonencode, and then remove " and change : into =:

value = replace(replace(jsonencode(var.tags), "\"", ""), ":", "=")
like image 9
Marcin Avatar answered Oct 20 '22 22:10

Marcin