Calculate Start and End IP address of a CIDR-block using Terraform

on
Oct 17, 2021
in

IP ranges are typically specified in CIDR notation. But what if your service requires start and end IPs? In this blog I’ll show how to use cidrhost to calculate the start and end IPs.

Terraform cidrhost Function

The cidrhost function calculates host IP addresses within a CIDR block. It accepts a network address prefix in CIDR notation, and returns the IP associated with the given host number.

> cidrhost("192.168.0.0/16", 10)
"192.168.0.10"
> cidrhost("192.168.0.0/16", 100)
"192.168.0.100"

Calculate Start and End IP

The start and end IP addresses are the first and last IP address of a CIDR block. In cidrhost terms this translates to host numbers 0 and -1. The latter uses a negative index to find the first element, starting at the end of IP address range.

> cidrhost("192.168.0.0/16", 0)
"192.168.0.0"
> cidrhost("192.168.0.0/16", -1)
"192.168.255.255"

Azure Sql Server Firewall Rule Example

The next Terraform configuration uses the cidrhost-function to configure the Azure Sql Server firewall rules.

variable "allowed_ips" {
  description = <<EOT
  IP addresses, in CIDR notation, allowed to access this Sql Server.

  Example:
  {
    CompanyHQ = "192.168.0.0/24"
  }
  EOT
  type    = map(string)
  default = {}
}

resource "azurerm_mssql_firewall_rule" "sql_server_firewall" {
  for_each = var.allowed_ips

  server_id        = azurerm_mssql_server.sql_server.id # Reference your own Sql server instance
  name             = each.key
  start_ip_address = cidrhost(each.value, 0)
  end_ip_address   = cidrhost(each.value, -1)
}

Conclusion

Terraform cidrhost calculates IP addresses within a CIDR block. Leverage negative indices to calculate the start and end IP addresses easily.

Photo by Anton Maksimov juvnsky on Unsplash

As a cloud consultant I enjoy taking software engineering practices to the cloud. Continuously improving the customers systems, tools and processes by focusing on integration and quality.
Share this article: Tweet this post / Post on LinkedIn