Hi,
There are two ways of doing this, the first and is to use the regexall
function.
regexall
will return the result of a regular expression as a list of capture groups:
So given the regex ([^:^/]*)(:\\d*)?(,)?
, when used on your string you would get the following output:
regexall("([^:^/]*)(:\\d*)?(,)?", var.records)
[
[
"example1.com",
":2181",
",",
],
[
"example2.com",
":2181",
",",
],
[
"example3.com",
":2181",
null,
],
]
You can then use the splat operator to select the first element from this list of lists and return a new list like so:
regexall("([^:^/]*)(:\\d*)?(,)?", var.records)[*][0]
[
"example1.com",
"example2.com",
"example3.com",
]
Another way to achieve the same thing would be to use a for expression, personally I think this is cleaner to read (mainly because I struggle with regex).
What we are doing in the following example is splitting the original string on a ,
, and looping over that list. We then split each element on :
if not blank and return the first index which is the URI.
[for s in split(",", var.records) : split(":", s)[0] if s != ""]
[
"example1.com",
"example2.com",
"example3.com",
]
Both of these examples require Terraform 0.12, below is an example of some Terraform config which demonstrates their use:
variable "records" {
default = "example1.com:2181,example2.com:2181,example3.com:2181"
}
output "list_regex" {
value = regexall("([^:^/]*)(:\\d*)?(,)?", var.records)[*][0]
}
output "list_for" {
value = [for s in split(",", var.records) : split(":", s)[0] if s != ""]
}