This is part of an ongoing series of posts documenting the built-in interpolation functions in Terraform. For more information, check out the beginning post. In this post I am going to cover the cidrhost() function. The example file is on GitHub here.
Function name: cidrhost(iprange, hostnumber)
Returns: Takes an IP address range in CIDR notation and finds the specified hostnumber in the range. The hostnumber is an int value, and it accepts positive or negative values. The negative values cycle down from the top of the range. The return value will be an IP address.
Example:
variable "cidrhost" {
default = "10.0.1.0/16"
}
# Returns 10.0.1.2
output "chomp" {
value = "${cidrhost(var.cidrhost,2)}"
}
##############################################
# Function: cidrhost
##############################################
##############################################
# Variables
##############################################
variable "iprange" {
default = "10.0.0.0/16"
}
variable "hostnum" {
default = 2
}
##############################################
# Resources
##############################################
##############################################
# Outputs
##############################################
output "1_iprange" {
value = "${var.iprange}"
}
output "2_hostnum" {
value = "${var.hostnum}"
}
output "3_cidrhost_output" {
value = "${cidrhost(var.iprange,var.hostnum)}"
}
Run the following from the cidrhost folder to get example output for a number of different cases:
terraform apply -var "iprange=172.16.0.0/24" -var "hostnum=2"
terraform apply -var "iprange=172.16.0.0/19" -var "hostnum=12"
terraform apply -var "iprange=192.168.0.1/25" -var "hostnum=17"
terraform apply -var "iprange=156.25.42.0/19" -var "hostnum=100"
terraform apply -var "iprange=172.16.2.128/27" -var "hostnum=-5"
#Fails with missing mask
terraform apply -var "iprange=172.16.0.0" -var "hostnum=2"
#Fails with no available ip address
terraform apply -var "iprange=172.16.0.0/32" -var "hostnum=2"
Dealing with IP Addresses is notoriously difficult. I think I only truly understood all the subnet math when I was studying for the CCNA, and then promptly found the IP Subnet Calculator and discarded most of what I knew to the dustbin of history. If you’ve ever tried to work with IP Addresses in CloudFormation or ARM Templates, you will immediately understand what a godsend this function is. Put together with a count loop and you can assign static IP Addresses like a champ.
Even if you feed the function the wrong starting value for a CIDR range, it still figures it out for you. The broadcast address (255) is included in the count, so just remember that while the function will return it, you shouldn’t use it.
Coming up next is the cidrnetmask() which does not include any type of cider, hard or otherwise.
October 18, 2024
What's New in the AzureRM Provider Version 4?
August 27, 2024
Debugging the AzureRM Provider with VSCode
August 20, 2024
State Encryption with OpenTofu
August 1, 2024