在子句后的人偶 file_line 中正则表达式匹配括号的正确方法

Correct way to regex match parenthesis in puppet file_line after clause

使用 Puppet 修改 listener.ora 文件:

file_line { 'addFloatingListenerTCPS':
  ensure  => present,
  path    => "${LSNR_PATH}/listener.ora",
  line    => "      (ADDRESS = (PROTOCOL = TCPS)(HOST = ${FLOATING_IP})(PORT = 1522))",
  after   => "^\s+(ADDRESS = (PROTOCOL = TCPS)(HOST = DB)(PORT = 1522))",
  require => Class["othernode"]
}

这不会导致任何人偶错误,但会将新条目一直放在文件末尾,而不是在它应该在的侦听器块内。 (对我来说,这表明 after 属性值与文件内容不匹配,因此 puppet 默认为追加模式)。

更改 after 属性值以转义所有括号:

after   => "^\s+\(ADDRESS = \(PROTOCOL = TCPS\)\(HOST =  DB\)\(PORT = 1522\)\)",

在控制台中生成多个警告:

Warning: Unrecognised escape sequence '\(' in file /etc/puppet/modules/test_conf/manifests/init.pp at line 30
Warning: Unrecognised escape sequence '\(' in file /etc/puppet/modules/test_conf/manifests/init.pp at line 30
Warning: Unrecognised escape sequence '\)' in file /etc/puppet/modules/test_conf/manifests/init.pp at line 30
Warning: Unrecognised escape sequence '\(' in file /etc/puppet/modules/test_conf/manifests/init.pp at line 30
Warning: Unrecognised escape sequence '\)' in file /etc/puppet/modules/test_conf/manifests/init.pp at line 30
Warning: Unrecognised escape sequence '\(' in file /etc/puppet/modules/test_conf/manifests/init.pp at line 30
Warning: Unrecognised escape sequence '\)' in file /etc/puppet/modules/test_conf/manifests/init.pp at line 30
Warning: Unrecognised escape sequence '\)' in file /etc/puppet/modules/test_conf/manifests/init.pp at line 30

使其无法在卫星中使用。然而,执行确实完成了,之后新条目在块内它应该在的地方。

这引发了多个问题:

  1. 括号是否被解释为特殊字符,如果是,为什么它们不能被转义?
  2. puppet stdlib 正则表达式是否处理反向引用?

是的,您确实需要在 file_line 资源的 after 属性中转义正则表达式中的括号。括号用于正则表达式中以捕获表达式的一部分以供稍后变量使用。但是,出现警告是因为您的正则表达式字符串有双引号 (")。这导致 Puppet 解析器最初将 \ 解释为内插字符串转义而不是正则表达式转义。因此,您需要将正则表达式值更改为文字字符串,以便解析器正确解释它。

after   => '^\s+\(ADDRESS = \(PROTOCOL = TCPS\)\(HOST =  DB\)\(PORT = 1522\)\)',

这将删除您的 Puppet 警告。

以上解释也回答了您的另外两个问题,但这里是一个快速重复的总结:

  1. 是;他们可以而且是。

顺便说一下,puppet-lint 也会为您捕捉到这个:https://github.com/rodjek/puppet-lint