Puppet [SOLVED]: Case-sensitive string comparison in Puppet

Puppet [SOLVED]: Case-sensitive string comparison in Puppet

Home Forums Automation Tools Puppet Puppet [SOLVED]: Case-sensitive string comparison in Puppet

Tagged: , ,

Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #229299

    Cloudy Point
    Keymaster

    QuestionQuestion

    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$/ {
      # ...
    }
    

    #229300

    Cloudy Point
    Keymaster

    Accepted AnswerAnswer

    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.

    Source: https://stackoverflow.com/questions/47408091/case-sensitive-string-comparison-in-puppet
    Author: Matt Schuchard
    Creative Commons License
    This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.