Recommended way to regex replace multiple lines in a configuration file

2,609 views
Skip to first unread message

eskhool

unread,
Jan 4, 2014, 1:04:43 AM1/4/14
to ansible...@googlegroups.com
Hi,
 If we don't have the option to use templates as the file may vary across system, is there a way to find and replace multiple lines based on a regex...something like an option in lineinfile such as 'all'. What other mechanism can be recommended? Any reason to not have this option? And if contributed will such a change be accepted in ansible core?

Thanks

Michael DeHaan

unread,
Jan 4, 2014, 11:32:57 AM1/4/14
to ansible...@googlegroups.com
It seems you would just use the shell module and invoke sed.



--
You received this message because you are subscribed to the Google Groups "Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email to ansible-proje...@googlegroups.com.
To post to this group, send email to ansible...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.



--
Michael DeHaan <mic...@ansibleworks.com>
CTO, AnsibleWorks, Inc.
http://www.ansibleworks.com/

Philippe Eveque

unread,
Jan 4, 2014, 12:55:24 PM1/4/14
to ansible...@googlegroups.com
another way not as optimal as using sed like proposed by Michael is
to do it via 2 tasks.

tasks 1: count the number of lines to replace (via shell module using and grep -E <regexp> | wc -l )
 using register to remember the linecounted

task 2: using lineinfile and with_sequence: linecounted

one caveat is that with sequence does not accept a 0 count ( a potential future improvement ?)

so just add  1 to the count (you do not care about doing it one more time)

then you can run those 2 tasks multiples times

works for me on grub.conf








2014/1/4 Michael DeHaan <mic...@ansibleworks.com>

eskhool

unread,
Jun 10, 2014, 12:22:11 PM6/10/14
to ansible...@googlegroups.com
Sorry to dig out an old post but Michael would an enhancement to the regex plugin to do multi line be accepted? Seems like pretty useful functionality and the re module in python has a find_iter for just the task...

Michael DeHaan

unread,
Jun 11, 2014, 6:34:11 PM6/11/14
to ansible...@googlegroups.com
Like the filter plugin?

How might that look in a playbook?


Brian Coca

unread,
Jun 12, 2014, 8:43:43 AM6/12/14
to ansible...@googlegroups.com
for targets systems the 'replace' module can do this nicely, I would use that even in 'localhost' ​
Reply all
Reply to author
Forward
0 new messages