Skip to content

Instantly share code, notes, and snippets.

@JohnLBevan
Created October 27, 2023 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JohnLBevan/58bee0cd24c584a8d62d16826841d4a8 to your computer and use it in GitHub Desktop.
Save JohnLBevan/58bee0cd24c584a8d62d16826841d4a8 to your computer and use it in GitHub Desktop.
Terraform Validate CIDR. Checks that the format is correct, and that the prefix matches the first IP in the range (thus it's a valid prefix)
variable "demoIpv4Cidr" {
type = string
default = "10.0.0.1/16" # try "10.0.0.0/16" for a valid value or "10.0.0.x/16" for an invalidly formatted cidr
validation {
condition = (
can(cidrhost(var.demoIpv4Cidr, 0)) &&
try(cidrhost(var.demoIpv4Cidr, 0), null) == split("/", var.demoIpv4Cidr)[0]
)
# the above could be simplified to:
# condition = cidrhost(var.demoIpv4Cidr, 0) == split("/", var.demoIpv4Cidr)[0]
# ...though that would throw `Error in function call` instead of `Invalid value for variable`
# if an invalid cidr (10.0.0.x/16) were used
error_message = "Must be valid IPv4 CIDR."
}
}
output demo {
value = try(cidrhost(var.demoIpv4Cidr, 0), null)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment