Skip to content

Any/Or Attribute Validators (Pass If At Least One Attribute Validator Passes) #28

@bflad

Description

@bflad

Terraform CLI and Framework Versions

Any Terraform CLI version and v0.8.0

Use Cases or Problem Statement

terraform-plugin-sdk/v2 implemented validation.Any(...schema.SchemaValidateFunc), which allowed provider developers to specify the equivalent of OR boolean logic for validation.

Some examples from various providers:

validation.Any(
	validation.IntBetween(1, 9),
	validation.IntInSlice([]int{12, 24, 36, 48, 60}),
)

validation.Any(
	validation.IntAtLeast(10485760),
	validation.IntInSlice([]int{0}),
),

validation.Any(
	validation.IntInSlice([]int{10, 30}),
	validation.IntDivisibleBy(60),
)

validation.Any(
	verify.ValidAccountID,
	verify.ValidARN,
)

validation.Any(
	validation.IsCIDR,
	validation.IsIPv4Address,
)

validation.Any(
	azure.ValidateResourceID,
	mgValidate.ManagementGroupID,
)

validation.Any(
	validate.ClusterID,
	msiValidate.UserAssignedIdentityID,
)

validation.Any(
	validation.StringInSlice([]string{"any"}, false),
	validation.StringMatch(serverRegexp, "must be a valid server ID"),
	validation.StringMatch(serverGroupRegexp, "must be a valid server group ID"),
	validation.StringMatch(loadBalancerRegexp, "must be a valid load balancer ID"),
	validation.IsCIDR,
	validation.IsIPAddress,
)

Proposal

This could be implemented in a number of ways.

Proposal 1 (Single Meta Validator)

In a metavalidator or attrvalidator package, create an Any(...AttributeValidator) or an Or(...AttributeValidator) function. If any of the given AttributeValidator returns without error diagnostics, it should return early with no diagnostics.

This has at least one particular quirk which may be problematic in that it could swallow unrecoverable errors, such as implementing an incorrect type validator intermixed with any valid one. e.g.

Any(
	stringvalidator.LengthBetween(1, 10),
	int64validator.Between(11, 20),
)

To enable additional use cases, such as the following logic (A && B) || (C && D), this may require an All(...AttributeValidator) or an And(...AttributeValidator) implementation as well. All AttributeValidator diagnostics would be aggregated and returned, without returning early. This wasn't necessary before as schema validation already defaults to AND boolean logic at the top level.

Proposal 2 (Per Type Validators)

Similar to the above, but created in each type package.

Additional Information

No response

Code of Conduct

  • I agree to follow this project's Code of Conduct

Metadata

Metadata

Assignees

Labels

enhancementNew feature or request

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions