James Sapam
James Sapam

Reputation: 16940

Puppet regex not match with variable name

I m not able to figure why this regex is not matching, here I am trying to match all the eth0 from the $all_interfaces, but it doesn't match:

          $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}": }
              }
          }

Output:

not found virtual interface

Can someone let me know what is wrong with this puppet snippet.

I am running on puppet version: 4.8.1

Thanks

Upvotes: 1

Views: 740

Answers (1)

John Bollinger
John Bollinger

Reputation: 180236

Can someone let me know what is wrong with this puppet snippet.

Sure: a regex literal is an atomic unit, not an expression for constructing a regex from a string. Thus, the characters between the slashes all serve as literal characters of the regex. There is no variable interpolation applied to the contents, and quotation marks within are ordinary pattern characters. Naturally, the resulting regex matches an entirely different set of strings than you're looking for.

You can probably make your example work as intended by removing the / characters, so that the right-hand side of the =~ expression is a string, not a regex:

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

. Or I expect you could even use ...

              if ( $iface =~ $interface_name ) {

..., since variable interface_name already refers to a string. In this context, Puppet 4+ will interpret the string on the right-hand side of the expression as a "stringified regular expression" -- that is, the text of a regular expression body contained in a string. Puppet will construct a regular expression from the string contents to match against the left-hand operand.

Upvotes: 2

Related Questions