【问题标题】:Ansible 2.5.5 - before attribute in 'replace' module not workingAnsible 2.5.5 - “替换”模块中的属性之前不起作用
【发布时间】:2021-11-05 13:05:28
【问题描述】:

我试图只替换特定字符串之后的第一个匹配项。然而,ansible 总是匹配所有出现的。这是文件:

这是我的 ansible 任务:

    - name: Update minPoolSize for CWTxDataSource dataSource
      replace:
        dest: "{{ op_db_path }}"
        after: ".*CWTxDataSourceXA"
        regexp: "^.*minPoolSize=.*$"
        replace: '        <connectionManager maxPoolSize="750" minPoolSize="20" />'
        backup: yes
    <dataSource jndiName="CWTxDataSource">
        <connectionManager maxPoolSize="750" minPoolSize="1" />
    </dataSource>

    <dataSource jndiName="UMDataSource">
        <connectionManager maxPoolSize="750" minPoolSize="1" />
    </dataSource>

在上面的示例中,两个connectionManager 标签都会得到更新,这不是我们想要的行为吗?如何更新我的regexp 以仅更新第一场比赛?我尝试了 replace 模块中的 before 选项作为解决方法,但由于某种原因这对我不起作用。

【问题讨论】:

  • 真正的答案是使用为处理结构化数据而设计的xml:。也就是说,您是否已经尝试使用before: 来进一步限制其搜索空间?
  • 我会试试xml,谢谢!是的,关于before 选项。
  • 对于xml,它依赖于目标虚拟机上的lxml pip 模块,这对于我的情况来说不是最佳维护:"msg": "The xml ansible module requires the lxml python library installed on the managed machine"
  • 那么我猜你有两个臭的选项:slurp:(或fetch:)文件到控制节点,按照设计使用xml:对其进行变异,然后将其推回被管节点;或将文件读入内存,去掉换行符,使模式为CWTxDataSource"(.+?) minPoolSize="1" 并以这种方式修补它
  • 感谢您的回复!我明白了,我的意思是如果正则表达式只适用于匹配第一次出现,我会使用它但不能让它只匹配第一次出现。

标签: regex ansible ansible-2.x regexp-replace


【解决方案1】:

我在 ansible docs 中找到了以下行:

# Prior to Ansible 2.7.10, using before and after in combination did the opposite of what was intended.

所以为了让我使用 after before 作为解决方法,我必须颠倒它们的值:

    - name: Update minPoolSize for CWTxDataSource dataSource
      # after / before values are reversed in ansible < 2.7
      replace:
        path: "{{ op_db_path }}"
        before: 'jndiName="CWTxDataSource"'
        after: "</dataSource>"
        regexp: 'minPoolSize="\d+"'
        replace: 'minPoolSize="{{ CWTxDS_minPoolSize }}"'

请注意 after before 的值实际上没有意义,但它确实有效!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-09
    • 2012-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-16
    • 2021-11-27
    相关资源
    最近更新 更多