Extract value from a range

Hi,

I have a variable metallb_vip_range and I would like terraform function to extract values from this range to use them.

For example, value for this range is 192.168.1.10-192.168.1.20 and I would like to get a list like this [192.168.1.10,192.168.1.11,....,192.168.1.20].

I check on terraform functions but didn’t find a way to do that.

Is it possible ?

Hi @lperrin-obs,
I’m not aware of a built-in function to do that. Depending on your input, even netmask might be important, too.
You could look into the external data source and use shell, python or ruby for the expansion. Within terraform it looks also reasonable to split the input string on -,. and iterate (e.g. count) on the difference of the last two items.

Terraform’s built-in functions for manipulating IP addresses (cidrsubnet, cidrhost, etc) are oriented around CIDR prefixes rather than arbitrary ranges, because that is typically how network equipment (both physical and virtual) expects to be configured. Terraform doesn’t have any functions for working with arbitrary ranges of IP addresses.

The closest approach I can imagine to what you described would be to use the cidrhost function with a network prefix and a range of host numbers under that prefix, perhaps something like this:

locals {
  cidr_block   = "192.168.1.0/24"
  host_numbers = range(10, 21)
  ip_addresses = [
    for n in local.host_numbers : cidrhost(local.cidr_block, n)
  ]
}

With the above configuration, local.ip_addresses should have the following value, which I think matches your requirement:

[
  "192.168.1.10",
  "192.168.1.11",
  "192.168.1.12",
  "192.168.1.13",
  "192.168.1.14",
  "192.168.1.15",
  "192.168.1.16",
  "192.168.1.17",
  "192.168.1.18",
  "192.168.1.19",
  "192.168.1.20",
]

This approach only works if all of the IP addresses you want to generate are consecutive host numbers under a particular CIDR prefix, which was true for your illustrative example but perhaps isn’t true for all situations your module will deal with. If your requirements aren’t compatible with CIDR-based address calcuations then I’d suggest to calculate the necessary list of IP addresses outside of Terraform and write the resulting list directly in Terraform, or (as @tbugfinder suggested) use the external data source to run some external code to perform the address calculations you need.

1 Like