我有一个代码
- name: Ansible replace string example
replace:
path: /etc/jitsi/videobridge/sip-communicator.properties contains
regexp: 'shard'
replace: "shard-1"但它不起作用
我中风了:
org.jitsi.videobridge.xmpp.user.shard.HOSTNAME=localhost
org.jitsi.videobridge.xmpp.user.shard.DOMAIN=auth.jc.name.com
org.jitsi.videobridge.xmpp.user.shard.USERNAME=name
org.jitsi.videobridge.xmpp.user.shard.PASSWORD=Hfr*7462
org.jitsi.videobridge.xmpp.user.shard.MUC_JIDS=JvbBredjoy@internal.auth.jc.name.com
org.jitsi.videobridge.xmpp.user.shard.MUC_NICKNAME=7896aee5-fgre-4b02-4569-0bcc75ed1d0d文件中的/etc/jitsi/videobridge/sip-communicator.properties
我应该在单词shard符号"-“之后加上数字(1,2,3)等,例如org.jitsi.videobridge.xmpp.user.shard-1.HOSTNAME=localhost。
在此之前,我应该检查-如果org.jitsi.videobridge.xmpp.user.shard-1.HOSTNAME=localhost行包含单词shard-1,那么我们将重命名为shard-2等等。
发布于 2021-10-27 15:04:11
要回答您的问题,我需要使用一个自定义过滤器插件来创建新值,以替换旧值:
在剧本文件夹中创建一个文件夹filter_plugins (我已将文件命名为myfilters.py和filter buildvalue)
过滤器:为了避免内存泄漏,使用“with”打开文件(感谢@mdaniel)
#!/usr/bin/python
import re
class FilterModule(object):
def filters(self):
return {
'buildvalue': self.buildvalue
}
def buildvalue(self, nfile, srch):
found = False
with open(nfile, 'r') as f:
lines = f.readlines()
for line in lines:
x = re.search(srch + '-*[0-9]*', line)
if x != None:
found = True
break
if found:
rep = srch + ('-1' if '-' not in x.group() else '-' + str((int(x.group().split('-')[1]) + 1)))
else:
rep = srch
return rep剧本:
tasks:
- name: replace
ansible.builtin.replace:
path: "{{ filename }}"
regexp: "{{ search }}-*[0-9]*"
replace: "{{ newvalue }}"
vars:
filename: 'files/fileregex.txt'
search: 'shard'
newvalue: "{{ filename | buildvalue(search) }}" https://stackoverflow.com/questions/69738282
复制相似问题