hashicorp/terraform · error

invalid CIDR expression

Error message

invalid CIDR expression: %s

What it means

cidrhost() function error: the first argument (prefix) could not be parsed as a CIDR by ipaddr.ParseCIDR. The function builds a host IP inside a given network and needs a valid IPv4/IPv6 CIDR string as its first parameter; anything that fails CIDR parsing yields this wrapped parse error.

Solutions

  1. Provide a full CIDR string including the prefix length, e.g. "10.0.0.0/24".
  2. Validate the variable with a regex or cidrblock validation rule before passing to cidrhost.
  3. If only a host IP is known, derive the network with cidrnetmask/cidrsubnet or compute the /prefix from the resource.

Example fix

// before
locals { ip = cidrhost("10.0.0.5", 4) }

// after
locals { ip = cidrhost("10.0.0.0/24", 4) }
Defensive patterns

Strategy: validation

Validate before calling

// HCL variable validation block
variable "cidr" {
  type    = string
  validation {
    condition     = can(regex("^([0-9]{1,3}\\.){3}[0-9]{1,3}/[0-9]{1,2}$", var.cidr))
    error_message = "cidr must be a valid CIDR like 10.0.0.0/24."
  }
}

Prevention

When it happens

Trigger: Calling cidrhost(prefix, hostNum) where prefix is not a valid CIDR, e.g. "10.0.0.5" (host with no /prefix), "10.0.0.0/33" (out-of-range mask), "not-an-ip", or an empty string.

Common situations: Variable computed from another resource without a netmask, user supplies a bare IP instead of a network, trailing whitespace/newline in a variable, or a misformatted locals value.

Related errors


AI-assisted analysis of hashicorp/terraform@d32a084675 (2026-08-11). Data as JSON: /api/errors/b6e2f769cf8d6e89. Report an issue: GitHub.

Appendix: source

Thrown at internal/lang/funcs/cidr.go:40

		{
			Name: "prefix",
			Type: cty.String,
		},
		{
			Name: "hostnum",
			Type: cty.Number,
		},
	},
	Type:         function.StaticReturnType(cty.String),
	RefineResult: refineNotNull,
	Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) {
		var hostNum *big.Int
		if err := gocty.FromCtyValue(args[1], &hostNum); err != nil {
			return cty.UnknownVal(cty.String), err
		}
		_, network, err := ipaddr.ParseCIDR(args[0].AsString())
		if err != nil {
			return cty.UnknownVal(cty.String), fmt.Errorf("invalid CIDR expression: %s", err)
		}

		ip, err := cidr.HostBig(network, hostNum)
		if err != nil {
			return cty.UnknownVal(cty.String), err
		}

		return cty.StringVal(ip.String()), nil
	},
})

// CidrNetmaskFunc contructs a function that converts an IPv4 address prefix given
// in CIDR notation into a subnet mask address.
var CidrNetmaskFunc = function.New(&function.Spec{
	Params: []function.Parameter{
		{
			Name: "prefix",
			Type: cty.String,

View on GitHub (pinned to d32a084675)