Introduction
Validating YAML values to be of specific data types is a common need for many situations. Ensuring that the values in your YAML file are valid is essential to avoid configuration-related errors. This How-to Guide checks and ensures each value in a YAML file is the data type it’s supposed to be, using the CUE command line.
Prerequisites
- You have CUE installed
locally. This allows you to run
cuecommands
Requirements
- Using the command line or terminal
- File editing
Steps
Create a YAML file called x.yaml with the following:
people:
Gopher:
name: Gopher
age: 12
address: Mountain View
Ken:
name: Ken
age: 21
address: The Blue SkyCreate a CUE file named x.cue
The following CUE creates a CUE definition that describes the data type constraints for every person.
#Person: {
name: string
age: int
address: string
}
people: [X=string]: #Person & {
name: X
}Run the following cue command in your:
$ cue vet -c x.cue x.yamlNOTE: cue vet is silent when run successfully. Output will only show on error.
Add another person to your YAML data.
people:
Gopher:
name: Gopher
age: 12
address: Mountain View
Ken:
name: Ken
age: 21
address: The Blue Sky
Rob:
name: Rob
age: 42.2
address: CUEtopiaValidate again with cue vet
$ cue vet -c x.cue x.yaml
people.Rob.age: conflicting values 42.2 and int (mismatched types float and int):
./x.cue:3:11
./x.yaml:12:10The command output shows validation errors where the YAML violates the (type) constraints that you have declared.
Fix up the YAML
people:
Gopher:
name: Gopher
age: 12
address: Mountain View
Ken:
name: Ken
age: 21
address: The Blue Sky
Rob:
name: Rob
age: 42
address: CUEtopiaValidate with cue vet again
$ cue vet -c x.cue x.yamlThe cue vet command will show no output on success.
Well done! Any future data errors on names, ages, and addresses in your YAML will be detected. This is especially helpful with YAML files with 100s (and even 1000s) of lines.