Parse nested YAML config file

if you have a complex config schema, you may need to store it in a YAML or JSON format

having been used to .INI style configs, I recently had to store nested values and INI style gets very complex, very fast.

For instance in YAML:

--- person: Joe: age: 32 children: - Katie - Frank Bob: age: 43 children: - Lisa

to get the names of Joe’s children, in JSON or YAML would look something like this,

data['person']['Joe']['children'] ['Katie','Frank']

in INI, this would be something like,

[person] [person/joe] age=32 children=Katie,Frank

This is really ugly and not nested visually. To get an individual child’s name, you would need to additionally parse a comma separated string. Fugly.

Much better to use YAML. I prefer YAML over JSON because its much easier for human readability, although the language interpreter converts YAML into JSON during run-time

Heres a Python and Ruby example on how to parse this sample Config file

config.yaml

--- scanners: hostname: web01.nyc.mycorp.com: port: 9900 scans: - "cisco scan" - "network sec scan" - "windows sec scan" web05.tex.mycorp.com: port: 9923 scans: - "tex network" - "infra scan"

Ruby

#!/usr/bin/env rubyrequire 'rubygems'require 'yaml'# get config file valuedef get_config(*args) conf = YAML.load_file($config_file) # get section section = args[0] # check if Config file has Section if not conf.has_key?(section) puts "Config file does not have section information for #{section}") break end # remove 1st element, "section" args.shift parsepath = "conf[\"#{section}\"]" args.each do |arg| parsepath = parsepath+"[\"#{arg}\"]" end # Handle errors begin return eval(parsepath) rescue puts "Config file does not have information for #{parsepath}") exit(1) endend #EOFscans = get_config('scanners','hostname','web05.tex.mycorp.com','scans')puts scans

['tex network', 'infra scan']