Hello list,
while playing around with Ansible and looking at the code i noticed, that the module lineinfile
cannot replace a line found by regexp with an arbitrary line, there's an explicit check in it.
another thing: it would be great if lineinfile can replace lines found by regexp with
backreferences. for instance, i want disable by commenting out the splashscreen in grub.conf but the
line can vary from host to host.
^s(plashimage=.*)$
to
#\1
same can be used to comment stuff in or comment stuff in and change some values.
As i'm no python developer, this is my humble approach to tackle the problem:
diff --git a/library/lineinfile b/library/lineinfile
index ed5e28b..dd3b8e9 100644
--- a/library/lineinfile
+++ b/library/lineinfile
@@ -139,8 +139,8 @@ def present(module, dest, regexp, line, insertafter, insertbefore, create, backu
msg = ""
mre = re.compile(regexp)
- if not mre.search(line):
- module.fail_json(msg="usage error: line= doesn't match regexp (%s)" % regexp)
+# if not mre.search(line):
+# module.fail_json(msg="usage error: line= doesn't match regexp (%s)" % regexp)
if insertafter is not None and insertafter not in ('BOF', 'EOF'):
insre = re.compile(insertafter)
@@ -152,9 +152,12 @@ def present(module, dest, regexp, line, insertafter, insertbefore, create, backu
# index[0] is the line num where regexp has been found
# index[1] is the line num where insertafter/inserbefore has been found
index = [-1, -1]
+ m = None
for lineno in range(0, len(lines)):
- if mre.search(lines[lineno]):
+ a = mre.search(lines[lineno])
+ if a:
index[0] = lineno
+ m = a
elif insre is not None and insre.search(lines[lineno]):
if insertafter:
# + 1 for the next line
@@ -165,11 +168,11 @@ def present(module, dest, regexp, line, insertafter, insertbefore, create, backu
# Regexp matched a line in the file
if index[0] != -1:
- if lines[index[0]] == line + os.linesep:
+ if lines[index[0]] == m.expand(line) + os.linesep:
msg = ''
changed = False
else:
- lines[index[0]] = line + os.linesep
+ lines[index[0]] = m.expand(line) + os.linesep
msg = 'line replaced'
changed = True
# Add it to the beginning of the file