slide

Terraform fot d cidrnetmask()

Ned Bellavance
2 min read

Cover

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 cidrnetmask() function. The example file is on GitHub here.

What is it?

Function name: cidrnetmask(iprange)

Returns: Takes an IP address range in CIDR notation and returns the netmask value in X.X.X.X type notation.

Example:

variable "cidrnetmask" {
  default = "10.0.1.0/16"
}

# Returns 255.255.0.0
output "cidrnetmask" {
  value = "${cidrnetmask(var.cidrnetmask)}"
}

Example file:

##############################################
# Function: cidrnetmask
##############################################
##############################################
# Variables
##############################################
variable "iprange" {
  default = "10.0.0.0/16"
}

##############################################
# Resources
##############################################

##############################################
# Outputs
##############################################
output "1_iprange" {
  value = "${var.iprange}"
}

output "2_cidrnetmask_output" {
  value = "${cidrnetmask(var.iprange)}"
}

Run the following from the cidrnetmask folder to get example output for a number of different cases:

terraform apply -var "iprange=172.16.0.0/8"

terraform apply -var "iprange=172.16.0.0/16"

terraform apply -var "iprange=1.1.1.1/24"

terraform apply -var "iprange=156.25.42.0/0"

terraform apply -var "iprange=172.16.2.128/32"

#Fails with invalid CIDR expression
terraform apply -var "iprange=172.16.2.128/33"

#Fails with missing mask
terraform apply -var "iprange=172.16.0.0"

Why use it?

There are many systems out there that expect their IP address and subnet mask to be in dot notation instead of CIDR. In my experience most of the cloud-native stuff would prefer CIDR notation, and so there needs to be someway of converting one to the other. This is the way, and the truth, and the… well, it’s the way at least. Combine this with the cidrhost function and you’re off to the IP addressing races.

Lessons Learned

You have to give the function a valid mask value (0-32). Anything else will throw an error. Omitting the mask value also throws an error. The function tests the IP address itself too, so if you give it something like 500.500.1.1/24 it will also throw an error.

Coming up next is the cidrsubnet() the last of what might be my favorite series of functions thus far.