stack overflow

Parsing YAML files on the command line using Ruby

I have been working on an infrastructure project that uses YAML files for all inventory and configuration management, and for the most part, if you're using tools like Ansible, CloudFormation, etc., then you don't ever have to worry about the actual parsing of a YAML file, and keys and values in the file are readily accessible since these tools parse them and get them into a readable structure for you.

But there's often little bits of glue code, or infrastructure build/cleanup jobs, where you need to grab one specific value out of a YAML file, and all you have readily available is bash. Luckily for me, I also have Ruby available in the particular environment where I needed to parse the YAML file, so doing this was as easy as:

  1. Defining a little bit of Ruby code which would load the YAML file, then grab a value out of it.
  2. Running that Ruby code using ruby -e (-e for 'evaluate this code), operating on the contents of a YAML file.

And here's how that looked, in my case: