'Is there a programatic way to half a CIDR block in Terraform?
I have a CIDR block, and I would like to exactly half it, so that I have two ranges that I can use within my Terraform project.
e.g. 10.10.10.0/24
, which includes IPs in range 10.10.10.0 - 10.10.10.255
can be split to 10.10.10.0/25
& 10.10.10.128/25
I've tried looking at this with cidrsubnet function, but I don't really understand how to use it to get from the first range to the second range.
Any help on this would be appreciated!
Solution 1:[1]
This can be done with cidrsubnet
as you pointed out.
output "first_half" {
value = cidrsubnet("10.10.10.0/24", 1, 0) # 10.10.10.0/25
}
output "second_half" {
value = cidrsubnet("10.10.10.0/24", 1, 1) # 10.10.10.128/25
}
Explenation:
cidrsubnet
takes 3 arguments: cidrsubnet(prefix, newbits, netnum)
.
- The
prefix
is the actual CIDR range you want to cut in half. newbits
is the number of additional bits which you want to extend the prefix. For example, if you have/24
prefix and you want to have/25
prefixes,newbits
is the difference between 25 and 24:25 - 24 = 1
netnum
is a whole number which is no more thannewbits
binary digits. In our case it can be either0
or1
.0
will be the range of10.10.10.0/25
, while1
will represent the second half, being10.10.10.128/25
.
To give you another example, which makes it more understandable, lets cut 10.10.10.0/24
if 4 ranges:
We know, that we need /26
ranges, so 26 - 24 = 2
for the newbits
. For netnum
, we can have 0, 1, 2, 3, for which in the binary digits are 00
, 01
, 10
, 11
.
cidrsubnet("10.10.10.0/24", 2, 0) # 10.10.10.0/26
cidrsubnet("10.10.10.0/24", 2, 1) # 10.10.10.64/26
cidrsubnet("10.10.10.0/24", 2, 2) # 10.10.10.128/26
cidrsubnet("10.10.10.0/24", 2, 3) # 10.10.10.192/26
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |