木偶正则表达式与变量名称不匹配

问题描述

我不知道为什么这个正则表达式不匹配,在这里我试图匹配 $all_interfaces 中的所有 eth0,但它不匹配:

          $interface_name = 'eth0'

          # $facts["interfaces"] = "eth0,eth0_1,eth0_2,eth0_3,eth1,lo"

          $all_interfaces = split($facts["interfaces"],',')
       
          $all_interfaces.each |$iface| {
              if ( $iface =~ /"${interface_name}"/ ) {
                  notify {"found virtual interface: ${iface}":}
              } else {
                  notify {"not found virtual interface: ${iface}": }
              }
          }

输出

not found virtual interface

谁能告诉我这个木偶片段有什么问题。

我在木偶版本上运行:4.8.1

谢谢

解决方法

谁能告诉我这个木偶片段有什么问题。

当然:正则表达式文字是一个原子单元,而不是从字符串构造正则表达式的表达式。因此,斜线之间的字符都用作正则表达式的文字字符。内容没有应用变量插值,里面的引号是普通的模式字符。自然地,生成的正则表达式匹配一组与您要查找的字符串完全不同的字符串。

您可以通过删除 / 字符使您的示例按预期工作,这样 =~ 表达式的右侧是一个字符串,而不是正则表达式:

              if ( $iface =~ "${interface_name}" ) {

。或者我希望你甚至可以使用 ...

              if ( $iface =~ $interface_name ) {

...,因为变量 interface_name 已经指向一个字符串。在此上下文中,Puppet 4+ will interpret the string on the right-hand side of the expression as a "stringified regular expression" -- 即包含在字符串中的正则表达式正文的文本。 Puppet 会根据字符串内容构造一个正则表达式来匹配左边的操作数。