Created
October 27, 2023 14:16
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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