Programatically Determining the Version of a Chef Cookbook

Featured image for sharing metadata for article

If you're scripting around your Chef cookbooks, you may want to do things like work out the version of the cookbook, so you can i.e. use it for reporting, check if the cookbook is already uploaded, etc.

You may think, well, it's in the following format, why don't I just parse it with i.e. a regex:

version '2.1.0'

Well, unfortunately this won't work (aside from if you generally avoid regex) as the metadata.rb file, which stores the cookbook's metadata, is just plain Ruby, so it allows you to execute any Ruby code, such as looking it up from file, performing a long-running HTTP request, or anything really.

Fortunately, we can use the utility class Chef::Cookbook::Metadata to parse the metadata, resolve any arbitrary Ruby code, and give us the version number:

require 'chef'

m = Chef::Cookbook::Metadata.new
m.from_file 'metadata.rb'
puts m.version

This also works for any other metadata of the cookbook we want to retrieve.

Written by Jamie Tanna's profile image Jamie Tanna on , and last updated on .

Content for this article is shared under the terms of the Creative Commons Attribution Non Commercial Share Alike 4.0 International, and code is shared under the Apache License 2.0.

#blogumentation #chef #ruby.

This post was filed under articles.

Interactions with this post

Interactions with this post

Below you can find the interactions that this page has had using WebMention.

Have you written a response to this post? Let me know the URL:

Do you not have a website set up with WebMention capabilities? You can use Comment Parade.