Programatically Comparing Versions Using Chef's Versioning Schemes

Featured image for sharing metadata for article

Chef's got some pretty great ways of definining version constraints of its dependencies, which can be used across cookbook dependencies, gem dependencies and supported platforms.

Today, I wanted to write some code that checked whether a cookbook supports RHEL7, but not RHEL8.

To do this, we would have our metadata.rb:

# not great
supports 'redhat', '< 8'
# better
supports 'redhat', '~> 7.0'

But how do we then determine this programatically? We can use Chef::VersionConstraint::Platform to parse the supported value, like so, and then compare it against a specific version:

require 'chef'

m = Chef::Cookbook::Metadata.new
m.from_file 'metadata.rb'
constraint = Chef::VersionConstraint::Platform.new m.platforms['redhat']
puts constraint.include? '6'
# => true
puts constraint.include? '7'
# => true
puts constraint.include? '7.5'
# => true
puts constraint.include? '7.5.0'
# => true
puts constraint.include? '8'
# => false

If you're comparing cookbook versions, you can just use Chef::VersionConstraint.new.

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.