Puppet validate_json_schema function

A few projects ago we had a JSON app with quite a fiddly config file that was undergoing rapid iteration. Although we never deployed an invalid JSON config we hit a couple of snags with config files that didn’t quite match up to the applications expectations. A proposed solution was to produce a JSON Schema document we could use in both integration tests and to ensure the JSON we generated in Puppet was both well formed and, more importantly, valid for that version of the application.

Now I’ve had a little bit of spare time I decided to write a validate_json_schema puppet function that I can potentially use the next time this issue arises. Using it is simple -

    # install the module
    $ puppet module install deanwilson-validate_json_schema

    # install the JSON validate gem in the puppet master
    $ bin/puppetserver gem install json-schema --no-ri --no-rdoc

and then use it in your manifests.

    class json_tester {

      $json_data   = file('json_tester/valid-json.json')
      $json_schema = file('json_tester/valid-schema.json')

      if validate_json_schema($json_data, $json_schema, true) {
        file { '/tmp/valid_json':
          content => $json_data,
        }
      }
    }

I’ve included a full validate_json_schema puppet example module that shows each of the moving parts in a trivial use case. If you supply invalid JSON then you’ll see an error similar to the below in you client runs.

    Error: Could not retrieve catalog from remote server:
    Error 400 on SERVER: Evaluation Error: 
    Error while evaluating a Function Call, Invalid JSON: ["The property
        '#/elements' of type String did not match the following type:
        integer in schema 5fe3442c-38ba-5365-a5ae-39a9c406c715#"] at 
        modules/json_tester/manifests/init.pp:6:6
        on node puppettester.example.com

At the moment this is only a proof of concept but I think it would have helped solved the problem we had and might prove useful to someone else.