Bool validator AtLeastOneOf vs AlsoRequires

Hello,

I am trying to use a validator on a bool argument so that it requires at least one of other 2 attributes to be set. I am trying to use AtLeastOneOf, but it’s not working.

Schema:

Attributes: map[string]schema.Attribute{
	"enabled": schema.BoolAttribute{
		Description: fmt.Sprintf("Whether the DHCP server is enabled. Defaults to `%t`", CONFIG_DHCP_ENABLED),
		Computed:    true,
		Optional:    true,
		Default:     booldefault.StaticBool(CONFIG_DHCP_ENABLED),
		Validators: []validator.Bool{
			boolvalidator.AtLeastOneOf(path.Expressions{
				path.MatchRelative().AtParent().AtName("ipv4_settings"),
				path.MatchRelative().AtParent().AtName("ipv6_settings"),
			}...),
		},
	},

If I replace AtLeastOneOf with AlsoRequires, the validation works, but that means I need to supply both attributes, which is not the case:

│ Error: Invalid Attribute Combination
│ 
│   with adguard_config.test,
│   on main.tf line 79, in resource "adguard_config" "test":
│   79: resource "adguard_config" "test" {
│ 
│ Attribute "dhcp.ipv4_settings" must be specified when "dhcp.enabled" is specified
╵
╷
│ Error: Invalid Attribute Combination
│ 
│   with adguard_config.test,
│   on main.tf line 79, in resource "adguard_config" "test":
│   79: resource "adguard_config" "test" {
│ 
│ Attribute "dhcp.ipv6_settings" must be specified when "dhcp.enabled" is specified

What am I doing wrong here?

Thank you

AtLeastOneOfValidator{} isn’t AdditionallyAtLeastOneOfValidator{} (not a real validator, I’m just trying to illustrate the distinction).

The first thing AtLeastOneOfValidator{} does when running is exit if this value is set because it’s looking for at least one of: enabled, ipv4_settings and ipv6_settings. In this case, enabled is set, so the minimum threshold (one) is reached.

You might find my AtMostNOfValidator{} interesting (convert it to AtLeastNOf and use it with n = 2 (enabled plus one of ipv4/ipv6 settings gets you to 2).

edit: Y’know, an AtMostNOfValidator{} won’t solve the problem because it doesn’t rely on the DHCP service being enabled. You’ll need an AlsoRequiresNOf{}.

Ahhh gotcha, I misinterpreted what the validator would do. Guess I don’t have a good way to prevent an error from the practitioner then. The underlying API will complain with a meaningful response, and I guess that will suffice.

Thanks!