If you can rely on the first 3 octets of the IP range being the same then you can get away with using a combination of split
, slice
, join
, range
and formatlist
functions to do this natively inside Terraform with something like the following:
variable "ip_range" {
default = "192.168.1.10-192.168.1.20"
}
locals {
ip_range_start = split("-", var.ip_range)[0]
ip_range_end = split("-", var.ip_range)[1]
# Note that this naively only works for IP ranges using the same first three octects
ip_range_first_three_octets = join(".", slice(split(".", local.ip_range_start), 0, 3))
ip_range_start_fourth_octet = split(".", local.ip_range_start)[3]
ip_range_end_fourth_octet = split(".", local.ip_range_end)[3]
list_of_final_octet = range(local.ip_range_start_fourth_octet, local.ip_range_end_fourth_octet)
list_of_ips_in_range = formatlist("${local.ip_range_first_three_octets}.%s", local.list_of_final_octet)
}
output "list_of_ips_in_range" {
value = local.list_of_ips_in_range
}
This outputs the following:
list_of_ips_in_range = [
"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",
]
If you need to offset that range so you end up with IP addresses from .11
to .20
from the same input then you can do that by changing the local.list_of_final_octet
like so:
list_of_final_octet = range(local.ip_range_start_fourth_octet + 1, local.ip_range_end_fourth_octet + 1)
Unfortunately Terraform doesn't have any built in functions for doing more elaborate CIDR math beyond cidrhost
, cidrnetmask
, cidrsubnet
, cidrsubnets
functions so if you have more complex requirements then you may need to delegate this to an external script that can calculate it and be called via the external
data source.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…