如何使用ansible regexp将新字符串插入到telegraf.conf的inputs.ping中 [英] How to Insert a new string into telegraf.conf's inputs.ping using ansible regexp
问题描述
我正在尝试使用 ansible 来更新 telegraf.conf 的 [[inputs.ping]].
I'm trying to use ansible to update telegraf.conf's [[inputs.ping]].
telegraf.conf 如下所示:
telegraf.conf looks like the following:
[[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-temp4"
之后添加 ,"tac-temp10"
.
I'm trying to add ,"tac-temp10"
after ,"tac-temp4"
in line 2 shown above.
- 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"
替换整行.预期输出:
regexp: '^((.*)"] #tac$)'
is replacing the whole line with ,"tac-temp10"
. Expected output:
[[inputs.ping]]
urls = ["tac-temp1","tac-temp2", "tac-temp3","tac-temp4","tac-temp10"] #tac
count = 30
timeout = 15.0
[inputs.ping.tags]
name = "tac"
推荐答案
警告:前面的正则表达式很丑.谨防下一个进行维护的人(包括经过一段时间后的你......)的不可预测的理解.
Warning: Ugly regexp ahead. Beware of unpredictable understanding for next guys (including you after time passed by...) doing maintenance.
如果您的服务器尚未存在(列表中的任何位置),则以下内容会将您的服务器添加到列表末尾.
The following will add your server at the end of the list if it is not already present (anywhere in the list) with a single idempotent task.
- 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
所以我可以很容易地回到原始版本进行测试.随意放下它.
You need to use backreferences to put back on the line the already matched parts of the expression. I used backup: yes
so I could easily come back to the original for my tests. Feel free to drop it.
正如您所看到的(正如我在警告中所建议的),对于任何必须快速阅读代码的人来说,这几乎是不可能理解的.如果您必须做任何更花哨/更复杂的事情,请考虑使用模板并将您的服务器列表存储在某个变量中.
As you can see (and as advised in my warning) this is pretty much impossible to understand for anyone having to quickly read the code. If you have to do anything more fancy/complicated, consider using a template and storing your server list in a variable somewhere.
这篇关于如何使用ansible regexp将新字符串插入到telegraf.conf的inputs.ping中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!