CIDR to IP range

Is there a function to get the first and last IP of a CIDR block?

Given I want to get the IP range.

cidrhost function can be of help. cidrhost - Functions - Configuration Language - Terraform by HashiCorp

Hi @deasunk,

As @deshaks noted, the cidrhost function is the main way to go from subnet addresses in CIDR notation to specific host addresses within that subnet.

Getting the starting IP address is easier because we know its number will always be zero:

> cidrhost("", 0)

Getting the ending IP address is harder because we need to calculate the largest number we can represent in the remaining bits. Terraform doesn’t have a dedicated function for that but it has some building blocks you can use to get there:

# Find the prefix length part of the CIDR notation
> parseint(regex("/(\\d+)$", "")[0], 10)

# Subtract from the total number of bits in the address
# to get the number of remaining bits.
# I'm assuming IPv4 here, which has a total of 32 bits.
> 32 - 16

# Find the 16th power of 2, which is the number of
# host addresses we can assign with 16 bits of
# host address space.
> pow(2, 16)

# The final host address is therefore one less than
# that result, because the first host address is
# numbered zero.
> cidrhost("", 65536-1)

(The examples above are terraform console output where I was working through this. To use this in your real configuration you can write these expressions out as local values, and possibly combine some of the steps together into a more complex expression since you likely won’t need the intermediate results anywhere else in your module.)

1 Like

Hi @deasunk and @apparentlymart,
no need for all that fancy regex and converting, cidrhost has it built-in:

> cidrhost("", 0)
> cidrhost("", -1)

And so on and so forth, e.g. for the last host IP in a subnet:

> cidrhost("", -2)