yaml-cel is a lightweight Go library for evaluating CEL (Common Expression Language) expressions embedded in YAML templates. It allows you to create dynamic configuration templates and evaluate them against runtime data, producing strongly typed Go structs.
- Define CEL expressions inline in YAML using
!celtag - Built-in
distinct()function to deduplicate string arrays - Evaluate templates into any Go struct using generics
go get github.com/k8shell-io/yaml-cel/pkg/yamlcelgo test -v ./...user:
username: !cel "username"
uid: !cel "uid"
org:
name: !cel "org.name"
roles: !cel "distinct(roles)"
valid: truetype User struct {
Username string
UID int
Org struct {
Name string
}
Roles []string
Valid bool
}tmpl := yamlcel.CELTemplate{}
_ = yaml.Unmarshal([]byte(yamldoc), &tmpl)
resource := map[string]any{
"username": "john",
"uid": 1001,
"org": map[string]any{
"name": "k8shell",
},
"roles": []string{"admin", "user", "admin"},
}
user, err := yamlcel.EvalToStruct[User](&tmpl, resource, nil, "user")
if err != nil {
log.Fatal(err)
}
fmt.Println(user.Username) // "john"
fmt.Println(user.Roles) // ["admin", "user"]func EvalToStruct[T any](
t *CELTemplate,
resource map[string]any,
extraFields map[string]string,
root string,
) (*T, error)resource: runtime input data (map)extraFields: optional additional string variablesroot: optional root key (use""for top-level mapping)
Apache 2.0
Built with ❤️ by the k8shell.io team.