我正在使用
terraform-plugin-framework
。
这是一个人为的示例,但假设我有一个类似的资源:
type R struct {
IsAdmin types.Bool
F1 types.String
}
如何定义一个模式:
a. 如果
IsAdmin
为 true,则 F1
必须 为空字符串
b. 如果
IsAdmin
为 false,则 F1
不能 为空字符串
一个简单的方法是在模式中将
F1
设置为 Optional
,然后在 Create
处理程序中进行验证。 我认为这不是正确的方法。 Schema
函数不应该这样做吗?
您可以使用 ValidateConfig 来完成此操作:
func (_ *RResource) ValidateConfig(ctx context.Context, req resource.ValidateConfigRequest, resp *resource.ValidateConfigResponse) {
// determine input values
var state R
resp.Diagnostics.Append(req.Config.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
// return if either field member/attribute is unknown
if state.IsAdmin.IsUnknown() || state.F1.IsUnknown() {
return
}
// validate F1
if state.IsAdmin.ValueBool() && len(state.F1.ValueString()) > 0 {
resp.Diagnostics.AddAttributeError(
path.Root("f1"),
"Invalid Attribute Value",
"Parameter 'f1' cannot be assigned a value if parameter is_admin is assigned a value of 'true'",
)
} else {
if !state.IsAdmin.ValueBool() && len(state.F1.ValueString()) == 0 {
resp.Diagnostics.AddAttributeError(
path.Root("f1"),
"Invalid Attribute Value",
"Parameter 'f1' must be assigned a value if parameter is_admin is assigned a value of 'false'",
)
}
}
}
此解决方案假设资源的属性模式遵循数据模型结构字段成员小写的典型约定,因为它在问题中未共享。