Nur1
Nur1

Reputation: 480

Interfaces/Default-Definitions for YAML files

I have a configuration file and want to standardize the keys. So when other developers create their own configurations, they will be validated.

When using programming languages you use interfaces.

I also know that somehow some YAML-based Tools like Ansible also have defaults/definitions to ensure you are writing your stuff correctly. But as far as I know, they also work with addons and such...

So is there are a way to achieve this kind of effect in YAML files?

I mean I could programmatically validate it somehow, but maybe there is something better.

Upvotes: 2

Views: 911

Answers (1)

flyx
flyx

Reputation: 39738

You have two options:

  • Use JSON Schema. Some editors and validators offer direct YAML support, for others you need to transform the YAML to JSON first to validate (which can be done automatically). See implementations. This will restrict you to use only features available in JSON (e.g. no complex keys, anchors & aliases being resolved etc).
  • Use the target type as schema. YAML is a serialization language, this means that the native type in the programming language of your choice serves as schema. This obviously doesn't work well in languages with dynamic typing, like Python or JavaScript. It does work in Java (via SnakeYAML), C# (via YamlDotNet) and others. You don't get automatic editor support but you can write a small validator tool and even writing a validator tool for your favorite editor is simple today with LSP.

Ansible (and lots of other YAML-based frameworks) isn't really a good example because it uses Jinja on top of YAML and therefore is far more complex to validate.

Upvotes: 1

Related Questions