Search code examples
regexstringpuppet

Case-sensitive string comparison in Puppet


The Puppet documentation indicates that the language's string comparisons with == are case-insensitive. What can I do when I need case-sensitive string comparisons? Is there a better way than taking refuge in regular expressions like so:

if $string =~ /^VALUE$/ {
  # ...
}

Solution

  • Within the intrinsic Puppet DSL, you cannot do case sensitive string comparisons with the == operator. You must use the regular expression operator =~ to perform case sensitive string comparisons.

    However, as @JohnBollinger has pointed out, you can write a custom function to do this for you by leveraging Ruby's case sensitive string comparison with its == operator: https://puppet.com/docs/puppet/5.3/functions_ruby_overview.html.

    The custom function would look something like:

    # /etc/puppetlabs/code/environments/production/modules/mymodule/lib/puppet/functions/mymodule/stringcmp.rb
    Puppet::Functions.create_function(:'mymodule::stringcmp') do
      dispatch :cmp do
        param 'String', :stringone
        param 'String', :stringtwo
        return_type 'Boolean' # omit this if using Puppet < 4.7
      end
    
      def cmp(stringone, stringtwo)
        stringone == stringtwo
      end
    end
    

    You can then utilize this custom function like:

    if stringcmp($string, 'VALUE') {
      # ...
    }
    

    given your code from above, and the string comparison will be case sensitive.