Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Conflicting Multiple Attribute Validation (ConflictsWith / ConflictingAttributes) #14

Closed
1 task done
bflad opened this issue May 16, 2022 · 1 comment · Fixed by #32
Closed
1 task done

Conflicting Multiple Attribute Validation (ConflictsWith / ConflictingAttributes) #14

bflad opened this issue May 16, 2022 · 1 comment · Fixed by #32
Assignees
Labels
enhancement New feature or request type/multi Multiple attribute validators type/schema Schema validators
Milestone

Comments

@bflad
Copy link
Contributor

bflad commented May 16, 2022

Terraform CLI and Framework Versions

Any Terraform CLI version; terraform-plugin-framework v0.8.0

Use Cases or Problem Statement

Provider developers should be able to generically validate that a set of attributes should all contain null configuration values, if a certain attribute has a non-null configuration value.

Proposal

These are not necessarily mutually exclusive proposals -- both types of implementations have been requested in the past.

Proposal 1 (AttributeValidator Style)

This would be similar to the helper/schema.Schema.ConflictsWith field implementation.

Inside a multivalidator package, create a new unexported type that satisfies the tfsdk.AttributeValidator interface:

var _ conflictsWithValidator = tfsdk.AttributeValidator

type conflictsWithValidator struct {
  attributePaths []AttributePath
}

func (v conflictsWithValidator) Description(ctx context.Context) string {/*...*/}
func (v conflictsWithValidator) MarkdownDescription(ctx context.Context) string {/*...*/}
func (v conflictsWithValidator) Validate(ctx context.Context, req tfsdk.ValidateAttributeRequest, resp *tfsdk.ValidateAttributeResponse) {/*...*/}

Then, create an exported function that returns it:

func ConflictsWith(attributePaths AttributePath...) AttributeValidator {/*...*/}

This would allow provider developers to declare attributes such as:

tfsdk.Attribute{
  // ... other fields ...
  Type: types.String{},
  Validators: tfsdk.AttributeValidators{
    multivalidator.ConflictsWith(
      tftypes.NewAttributePath().WithAttributeName("other"), // until attribute paths/matchers are native
    ),
  },
},

Proposal 2 (ConfigValidator Style)

Rather than being part of the schema, this would enable provider developers to create it at the top level of a resource, etc.

Inside a configvalidator package, create a new unexported type that satisfies the tfsdk.ResourceConfigValidator interface (allowing a configuration validator across data sources, providers, and resources would require an upstream breaking change to those interfaces):

var _ conflictingAttributesValidator = tfsdk.ResourceConfigValidator

type conflictingAttributesValidator struct {
  attributePaths []AttributePath
}

func (v conflictingAttributesValidator) Description(ctx context.Context) string {/*...*/}
func (v conflictingAttributesValidator) MarkdownDescription(ctx context.Context) string {/*...*/}
func (v conflictingAttributesValidator) Validate(ctx context.Context, req tfsdk.ResourceConfigValidatorRequest, resp *tfsdk.ResourceConfigValidatorResponse) {/*...*/}

Then, create an exported function that returns it:

func ConflictingAttributes(attributePaths AttributePath...) AttributeValidator {/*...*/}

This would allow provider developers to declare resources such as:

var _ tfsdk.ResourceWithConfigValidators = exampleResource{}

func (r exampleResource) ConfigValidators(ctx context.Context) []tfsdk.ResourceConfigValidator {
  return []tfsdk.ResourceConfigValidator{
    configvalidator.ConflictingAttributes(
      // attribute path 1
      // attribute path 2
    ),
  },
}

Additional Information

No response

Code of Conduct

  • I agree to follow this project's Code of Conduct
@bflad bflad added enhancement New feature or request type/multi Multiple attribute validators labels May 16, 2022
@detro detro self-assigned this May 25, 2022
@bflad bflad added this to the v0.4.0 milestone Jun 22, 2022
bflad added a commit to hashicorp/terraform-plugin-framework that referenced this issue Jun 28, 2022
Reference: #81
Reference: hashicorp/terraform-plugin-framework-validators#14
Reference: hashicorp/terraform-plugin-framework-validators#15
Reference: hashicorp/terraform-plugin-framework-validators#16
Reference: hashicorp/terraform-plugin-framework-validators#17
Reference: hashicorp/terraform-plugin-framework-validators#20

This introduces the concept of an attribute path expression, an abstraction on top of an attribute path, which enables provider developers to declare logic which might match zero, one, or more paths.

Paths are directly convertable into path expressions as exact expression steps. The builder-like syntax for exact expression steps matches the syntax for path steps, such as `AtName()` in both cases always represents an exact transversal into the attribute name of an object. Additional expression steps enable matching any list, map, or set element, such as `AtAnyListIndex()`. It also supports relative attribute path expressions, by supporting a parent expression step `AtParent()` or starting an expression with `MatchParent()` which can be combined with a prior path expression.

The framework will automatically expose path expressions to attribute plan modifiers and validators, so they can more intuitively support relative paths as inputs to their logic. For example, the `terraform-plugin-framework-validators` Go module will implement support for `terraform-plugin-sdk` multiple attribute schema behaviors such as `ConflictsWith`. It is expected that the downstream implementation can allow provider developers to declare the validator with expressions such as:

```go
tfsdk.Attribute{
	// ... other fields ...

	Validators: []AttributeValidators{
		schemavalidator.ConflictsWith(
			// Example absolute path from root
			path.MatchRoot("root_attribute"),

			// Example relative path from current attribute
			// e.g. another attribute at the same list index of ListNestedAttributes
			path.MatchParent().AtName("another_same_level_attribute"),
		),
	},
}
```

Then the logic within the validator can take the `ValidateAttributeRequest.AttributePathExpression` and use the `(path.Expression).Append()` method to combine the current attribute expression with any incoming expressions.

While this introduction will expose the expression types and make them available to attribute plan modifiers and validators, there is not yet a simple methodology for getting valid paths within data stored in `tfsdk.Config`, `tfsdk.Plan`, and `tfsdk.State` that match the expression. This will be added after this initial expression API is reviewed and approved.
bflad added a commit to hashicorp/terraform-plugin-framework that referenced this issue Jun 29, 2022
Reference: #81
Reference: hashicorp/terraform-plugin-framework-validators#14
Reference: hashicorp/terraform-plugin-framework-validators#15
Reference: hashicorp/terraform-plugin-framework-validators#16
Reference: hashicorp/terraform-plugin-framework-validators#17
Reference: hashicorp/terraform-plugin-framework-validators#20

This introduces the concept of root and relative attribute path expressions, abstractions on top of an attribute path, which enables provider developers to declare logic which might match zero, one, or more paths.

Paths are directly convertible into path expressions as exact expression steps. The builder-like syntax for exact expression steps matches the syntax for regular path steps, such as `AtName()` in both cases always represents an exact transversal into the attribute name of an object. Additional expression steps enable matching any list, map, or set element, such as `AtAnyListIndex()`. It also supports relative attribute path expressions, by supporting a parent expression step `AtParent()` and starting an expression with `MatchRelative()` so it can be combined with a prior path expression.

The framework will automatically expose path expressions to attribute plan modifiers and validators, so they can more intuitively support relative paths as inputs to their logic. For example, the `terraform-plugin-framework-validators` Go module will implement support for `terraform-plugin-sdk` multiple attribute schema behaviors such as `ConflictsWith`. It is expected that the downstream implementation can allow provider developers to declare the validator with expressions such as:

```go
tfsdk.Attribute{
	// ... other fields ...

	Validators: []AttributeValidators{
		schemavalidator.ConflictsWith(
			// Example absolute path from root
			path.MatchRoot("root_attribute"),

			// Example relative path from current attribute
			// e.g. another attribute at the same list index of ListNestedAttributes
			path.MatchRelative().AtParent().AtName("another_same_level_attribute"),
		),
	},
}
```

Then the logic within the validator can take the `ValidateAttributeRequest.AttributePathExpression` and use the `(path.Expression).Merge()` method to combine the current attribute expression with any incoming expressions.

To find matching attribute paths based on a path expression within `tfsdk.Config`, `tfsdk.Plan`, and `tfsdk.State`, a `PathMatches(path.Expression)` method has been added to each type. The resulting paths can then be used to fetch data via existing functionality, such as the `GetAttribute()` method of each type.
@detro detro added the type/schema Schema validators label Jul 8, 2022
@detro detro closed this as completed in #32 Jul 12, 2022
@github-actions
Copy link

I'm going to lock this issue because it has been closed for 30 days ⏳. This helps our maintainers find and focus on the active issues.
If you have found a problem that seems similar to this, please open a new issue and complete the issue template so we can capture all the details necessary to investigate further.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators Aug 12, 2022
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
enhancement New feature or request type/multi Multiple attribute validators type/schema Schema validators
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants