Sometimes the easiest tasks can drive us mad. Mainly because we try to adapt our existing knowledge of some tools to the new tools we’re using.
If you try to use Terraform like any other programming language, you are setting yourself up for failure.
Way too many times I’ve googled “loops in terraform” or “conditions in terraform”. Thankfully, eventually some sort of repetition was introduced, but it still does not work like one would expect coming from an imperative language.
Using string interpolation
Up to Terraform 0.12, the only way to concatenate strings was actually using interpolation, which is not too bad:
locals {
s1 = "interpolation"
s2 = "concatenation-through-${locals.s1}-bye"
}
Using join
Lately the join
function was introduced. It works very much as you would expect
it to work in Javascript or Ruby. The first argument is a delimiter. The second argument is a single list of strings to be joined. Here’s an example:
locals {
s1 = "join"
s2 = join("-", ["concatenation", "through", locals.s1, "bye"])
}
Of course this also works with variables or any other expression that returns a string:
locals {
str = join("-", ["concatenation", "through", var.type, "bye"])
}