如何使用ansible regexp将新字符串插入telegraf.conf的inputs.ping

时间:2019-06-14 11:35:19

标签: regex ansible telegraf-inputs-plugin

我正在尝试使用ansible更新telegraf.conf的[[inputs.ping]]。

telegraf.conf如下所示:

[[inputs.ping]]
  urls = ["tac-temp1","tac-temp2", "tac-temp3","tac-temp4"] #tac
  count = 30
  timeout = 15.0
  [inputs.ping.tags]
  name = "tac"

[[inputs.ping]]
  urls = ["prod-temp1","prod-temp2", "prod-temp3","prod-temp4"] #prod
  count = 30
  timeout = 15.0
  [inputs.ping.tags]
  name = "prod"

[[inputs.ping]]
  urls = ["test-temp1","test-temp2", "test-temp3","test-temp4"] #test
  count = 30
  timeout = 15.0
  [inputs.ping.tags]
  name = "test"

我试图在上述第2行的,"tac-temp10"之后添加,"tac-temp4"

- hosts: Servers
  become: yes
  become_method: sudo
  tasks:
    - name: Loading telegraf.conf content for search
      shell: cat /tmp/telegraf.conf
      register: tele_lookup

    - name: Adding Server to  /tmp/telegraf.conf if does not exists
      lineinfile:
             path: /tmp/telegraf.conf
             state: present
             regexp: '^((.*)"] #tac$)'       
             line: ',"tac-temp10"'      
             backup: yes
      when: tele_lookup.stdout.find('tac-temp10') != '0'

regexp: '^((.*)"] #tac$)'将整个行替换为,"tac-temp10"。预期输出:

[[inputs.ping]]
  urls = ["tac-temp1","tac-temp2", "tac-temp3","tac-temp4","tac-temp10"] #tac
  count = 30
  timeout = 15.0
  [inputs.ping.tags]
  name = "tac"

1 个答案:

答案 0 :(得分:0)

警告:前面的正则表达式很丑。谨防接下来的人(包括经过一段时间的您之后)会对您进行不可理解的了解。

如果没有单个幂等任务,则以下内容会将您的服务器添加到列表的末尾。

    - name: add our server if needed
      lineinfile:
        path: /tmp/test.conf
        backup: yes
        state: present
        regexp: '^( *urls *= *\[)(("(?!tac-temp10)([a-zA-Z0-9_-]*)",? *)*)(\] #tac)$'
        backrefs: yes
        line: '\1\2, "tac-temp10"\5'

您需要使用反向引用将表达式中已经匹配的部分放回一行。我使用了backup: yes,因此可以轻松返回到原始版本进行测试。随意放下它。

正如您所看到的(并在我的警告中建议),对于必须快速阅读代码的人来说,这几乎是不可能理解的。如果您需要做更多更复杂的事情,请考虑使用模板并将服务器列表存储在某个位置的变量中。