Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Terraform CIDR block variable validation

Terraform variable validation for CIDR, looking alternative for regex

Below is the tested code in Terraform version 13.0 is there any alternative way to achieve same thing with not using regex?

cidr block - start 172.28.0.0.0/16

    variable "vpc_cidr" {
      description = "Kubernetes cluster CIDR notation for vpc."
      validation {
        condition     = can(regex("^([0-9]{1,3}\\.){3}[0-9]{1,3}($|/(16))$", var.pod_cidr))
        error_message = "Vpc_cidr value must be greater than 172.0.0.0/16."
      }
    }

how to validate CIDR block 172.28.x.x/16 with cidrsubnet function? https://www.terraform.io/docs/language/functions/cidrsubnet.html

validation condition - if IP range is outof 172.28.x.x/16 then validation will be failed

like image 975
Manzoor Shaikh Avatar asked May 07 '26 15:05

Manzoor Shaikh


1 Answers

I prefer the solution from https://dev.to/drewmullen/terraform-variable-validation-with-samples-1ank

variable "string_like_valid_ipv4_cidr" {
  type    = string
  default = "10.0.0.0/16"

  validation {
    condition     = can(cidrhost(var.string_like_valid_ipv4_cidr, 32))
    error_message = "Must be valid IPv4 CIDR."
  }
}

Also note, as commented there, that the condition requires a modification to work for /32 addresses.

like image 72
cancellettopugno Avatar answered May 10 '26 13:05

cancellettopugno



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!