Greetings everyone!
I’m using the following libraries to develop a plugin:
github.com/hashicorp/terraform-plugin-framework v1.1.1
github.com/hashicorp/terraform-plugin-framework-validators v0.10.0
Is there a way to set up validation to verify that an attribute at the given pass has a specific value?
Example
The validation should pass when graph.code
block exists and the graph.mode
equals code
.
- Should pass (
code
block exists, mode =code
):
data "gdashboard_text" "test" {
title = "Test"
graph {
mode = "code"
code {
language = "sql"
}
}
}
- Should pass (
code
block does not exist, so the value of themode
does not matter):
data "gdashboard_text" "test" {
title = "Test"
graph {
mode = "markdown"
}
}
- Should fail (
code
block exists, mode !=code
):
data "gdashboard_text" "test" {
title = "Test"
graph {
mode = "markdown"
code {
language = "sql"
}
}
}
Implementation attempts
The entire codebase is available on GitHub.
Here is my definition of the graph
block:
func graphBlock() schema.Block {
return schema.ListNestedBlock{
NestedObject: schema.NestedBlockObject{
Blocks: map[string]schema.Block{
"code": schema.ListNestedBlock{
NestedObject: schema.NestedBlockObject{
Attributes: map[string]schema.Attribute{
"language": schema.StringAttribute{
Optional: true,
},
},
Validators: []validator.Object{
objectvalidator.ConflictsWith(
path.MatchRoot("graph").AtAnyListIndex().AtName("mode").AtSetValue(types.StringValue("markdown")),
),
},
},
},
},
Attributes: map[string]schema.Attribute{
"mode": schema.StringAttribute{
Optional: true,
Validators: []validator.String{
stringvalidator.OneOf("markdown", "code"),
},
},
},
},
}
}
The validation is defined as:
objectvalidator.ConflictsWith(
path.MatchRoot("graph").AtAnyListIndex().AtName("mode").AtSetValue(types.StringValue("markdown"))
)
If I get it right, the validation will fail if the graph[*].mode
== markdown
. Since the validation is defined in the code
nested object, it’s triggered only when the code
block is defined.
Unfortunately, it fails with:
The Terraform Provider unexpectedly provided a path expression that does not
match the current schema. This can happen if the path expression does not
correctly follow the schema in structure or types. Please report this to the
provider developers.
Path Expression: graph[*].mode[Value("markdown")]
The path (before AtSetValue
) is correct, because switching to:
path.MatchRoot("graph").AtAnyListIndex().AtName("mode")
gives me a reasonable error:
Attribute "graph[0].mode" cannot be specified when "graph[0].code[0]" is specified
So, is there a way to validate that the attribute at the given path has a specific value?