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 comparison code in Puppet manifest
v1 < v2 versioncmp(v1, v2) < 0
v1 <= v2 versioncmp(v1, v2) <= 0
v1 = v2 versioncmp(v1, v2) = 0
v1 >= v2 versioncmp(v1, v2) >= 0
v1 > v2 versioncmp(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.