Split the output excluding the port number

I have a terraform code like below

variable “records”{
default = example1.com:2181,example2.com:2181,example3.com:2181
}

resource “aws_route53_record” “database” {
count = var.enable ? 1 : 0

zone_id = var.private_zone_id
name = var.subdomain_name
type = “CNAME”
ttl = “300”
records = [var.records]
}

where I want to pass all those values in records excluding the : and port number

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 != ""]
  }

Thanks Nic for your help. Its working now for a single domain, but say if I have 3 domain names each has to be mapped to a single resource in record like the first domain name should be mapped to the first record, the second to second and the thrid to third.

I have a terraform code like below

variable “records”{
default = example1.com:2181,example2.com:2181,example3.com:2181
}

variable “subdomain_name” {
default = apps1.com,apps2.com,apps3.com
}
resource “aws_route53_record” “database” {
count = var.enable ? 1 : 0

zone_id = var.private_zone_id
name = var.subdomain_name
type = “CNAME”
ttl = “300”
records = [var.records]
}