【问题标题】:What is the correct syntax for search & replace within an Ansible playbook?Ansible playbook 中搜索和替换的正确语法是什么?
【发布时间】:2016-04-07 14:38:53
【问题描述】:

我正在编写一个 Ansible 剧本,它将安装和配置我公司使用的某些监控系统的代理。 成功配置代理所需的步骤之一是将 Nagios “log_rotation_method”配置为每天。 nagios.cfg 文件中的相关行是: log_rotation_method=h 我希望 Ansible 将其更改为 log_rotation_method=d

剧本的相关部分如下所示:

- name: Set Nagios rotation method to daily
  replace: dest=/etc/nagios3/nagios.cfg regexp='log_rotation_method=h' replace='log_rotation_method=d' 

在 bash 中我会这样写:

sed -i 's/^log_rotation_method.*/log_rotation_method=d/g' nagios.cfg

但我很难理解应该如何用基于 Python 的 Ansible 编写它。

知道应该怎么写吗? 一个解释将是非常受欢迎的。

【问题讨论】:

  • 试试replace: dest=/etc/nagios3/nagios.cfg regexp='(?m)^log_rotation_method.*' replace='log_rotation_method=d'(或删除(?m)
  • 请注意,它应该如何写在template中。 lineinfile 模块意味着您无法确保 nagios 配置的其余部分得到管理。

标签: regex ansible ansible-playbook


【解决方案1】:

我会用 lineinfile 做到这一点:

- lineinfile: dest=/etc/nagios3/nagios.cfg regexp='^log_rotation_method.*' line='log_rotation_method=d'

【讨论】:

    【解决方案2】:

    您可以编写与您在 bash 中编写的内容非常相似的内容(它们最终都是正则表达式):

       replace: dest=/etc/nagios3/nagios.cfg regexp='^log_rotation_method.*' replace='log_rotation_method=d' 
    

    它实际上应该以与您编写的方式相同的方式工作。在正则表达式的情况下,它将只匹配该确切字符串而不是多个字符串。

    【讨论】:

      猜你喜欢
      • 2021-09-28
      • 2010-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-27
      • 2013-12-17
      • 1970-01-01
      • 2018-02-07
      相关资源
      最近更新 更多