8

How can I transform a string "foo, bar, xid, uid" to a list ["foo", "bar", "xid", "uid"]?

I'm assigninng to variable value from Consul which is a string

my_var = "foo, bar, xid, uid"

Now I would like to convert my_var to a list that will look like this:

my_list = ["foo", "bar", "xid", uid"]

How can I achieve that? I was trying to use formatlist and the splat operator for that but no success

my_list = ${formatlist(<put magic here>, var.my_var)

2 Answers 2

11

You can use the split function here:

my_list = ${split(",", var.my_var)}
Sign up to request clarification or add additional context in comments.

1 Comment

If you found the answer useful and it completely solved your problem you should consider accepting the answer to show that to others who might have the same issue.
8

ydaetskcoR's answer is essentially correct, but in Terraform 0.12 syntax has changed, and the split function line should read:

my_list = split(",", var.my_var)

1 Comment

We probably want to have a think as a community about how we handle things that are pure syntax updates due to HCL2. I am unsure whether we should leave things as is or whether we should follow the Terraform docs and move everything to HCL2 with a series of edits of existing posts once they consider 0.12 and HCL2 adoption to be complete enough that the provider docs all change. I don't think there's a huge amount of value in duplicating every HCL1 post with the HCL2 syntax.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.