Turn map into string separated by "-"

I have two arrays of strings (colors, animals), that I want to randomize and concatonate into a single string using string interpolation (e.g. "red-goat")

# Input
colors=["red","green","blue"]
animals=["cat","dog","goat"]

# Output (randomized)
red-goat
blue-cat
red-dog
green-dog

The following produces a map where the key is a random color, and the value is a random animal. Which is what I’m looking for, except I want to turn these results into strings like "blue-cat" and "red-rabbit"

# terraform output foobar
foobar_result = {
  "blue" = "cat"
  "red" = "rabbit"
}
resource "random_shuffle" "color" {
  input        = ["purple", "red", "orange", "yellow", "green", "blue", "indigo", "violet"]
  result_count = 1
  count        = 3
}
resource "random_shuffle" "animal" {
  input        = ["tiger", "lion", "bear", "panther", "dog", "bunny", "rabbit", "cat", "bird", "fish"]
  result_count = 1
  count        = 3
}
locals {
  colors  = random_shuffle.color.*.result
  animals = random_shuffle.animal.*.result
  combined = zipmap(flatten(local.colors), flatten(local.animals))
}
output "foobar" {
  value = local.combined
}

Things I’ve tried

output "foobar1" {
  value =join("-", local.combined[*])
}
output "foobar2" {
  value = { for k,v in local.combined : key(k), value(v) }
}
output "foobar3" {
  value = { for k,v in local.combined : "${k}-${v}" }
}
output "foobar4" {
  value =join("-", one(local.colors.*), one(local.animals.*))
}
output "foobar5" {
  value = { for k,v in local.combined: format("%s-%s",k, v) }
}

How can I output with a format like ${k}-${v} ?

Nearly correct, but since you’re trying to produce a list not a map, you need [ ] instead of { }

1 Like

Thank you.

Both of these work exactly as I hoped.

output "foobar" {
  value = [ for k,v in local.combined: format("%s-%s",k, v) ]
}
output "foobar" {
  value = [ for k,v in local.combined : "${k}-${v}" ]
}
foobar_result = [
  "blue-cat",
  "red-rabbit",
]