Skip to content

Puppet versioncmp mnemonic

With the release of the Future Parser in Puppet 4 the type system got a complete overhaul. Comparing a string to an integer is no longer an accepted language contruct. This is a good thing because it prevents unforeseen errors. But your legacy code may contain comparisons between facts facts like $operatingsystemmajrelease and (numeric) version numbers. For Puppet 4 this code should use the versioncmp function instead.

The versioncmp function takes two strings representing version numbers. The two version numbers are compared and one of the values -1, 0 or 1 is returned to indicate the result of the comparison. See the following examples for the mapping.

versioncmp('1.0', '1.1') = -1
versioncmp('1.1', '1.1') = 0
versioncmp('1.2', '1.1') = 1

Here is my mnemonic trick to use the function without looking into the documentation every time. I always compare the function result to the result code zero using the same relational operator that would be suitable for the two version number strings as they are written.

designated comparisoncode in Puppet manifest
v1 < v2versioncmp(v1, v2) < 0
v1 <= v2versioncmp(v1, v2) <= 0
v1 = v2versioncmp(v1, v2) = 0
v1 >= v2versioncmp(v1, v2) >= 0
v1 > v2versioncmp(v1, v2) > 0

This works pretty well when coding: write the call the to the versioncmp function and the two arguments you need to compare. Then look back at the two function arguments and decide which relational operator would have to go in between to achieve the correct comparison. Then just write this operator and the literal zero. That's it.


No Trackbacks


Display comments as Linear | Threaded

No comments

Add Comment

Standard emoticons like :-) and ;-) are converted to images.
Textile-formatting allowed
E-Mail addresses will not be displayed and will only be used for E-Mail notifications.

To prevent automated Bots from commentspamming, please enter the string you see in the image below in the appropriate input box. Your comment will only be submitted if the strings match. Please ensure that your browser supports and accepts cookies, or your comment cannot be verified correctly.

Form options

Submitted comments will be subject to moderation before being displayed.