Puppet 中区分大小写的字符串比较

Case-sensitive string comparison in Puppet

Puppet documentation 表示该语言的字符串与 == 的比较不区分大小写。当我需要区分大小写的字符串比较时该怎么办?有没有比像这样使用正则表达式更好的方法:

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

在内部 Puppet DSL 中,您不能使用 == 运算符进行区分大小写的字符串比较。您必须使用正则表达式运算符 =~ 来执行区分大小写的字符串比较。

但是,正如@JohnBollinger 所指出的,您可以编写一个自定义函数来为您执行此操作,方法是利用 Ruby 的区分大小写的字符串与其 == 运算符进行比较:https://puppet.com/docs/puppet/5.3/functions_ruby_overview.html.

自定义函数类似于:

# /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

然后您可以像这样使用此自定义函数:

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

根据上面的代码,字符串比较将区分大小写。