Question

In the lineinfile module, it replaces the full line.

If the line is long I have to repeat the whole line again.

Let us suppose I want to replace the single word in the file:

#abc.conf
This is my horse

this is the playbook:

 - lineinfile: dest=abc.conf
               state=present
               regexp='horse'
               line='This is my dog'
               backup=yes

is there any way to achieve someting like sed 's/horse/dog/g' ?

Était-ce utile?

La solution 2

You can use backreferences to retrieve other parts(that should not be changed) of the line:

 - lineinfile: dest=abc.conf
               state=present
               regexp='^(.*)horse(.*)$'
               line='\1dog\2'
               backup=yes
               backrefs=yes

Autres conseils

New module replace available since 1.6 version:

- replace:
    dest=abc.conf
    regexp='horse'
    replace='dog'
    backup=yes

If you need to do more replace operations in one block and you have the file locally, you might want to consider using template, which substitutes variables in the template file and copies the file to the remote:

- template: src=/mytemplates/foo.j2 dest=/etc/file.conf

In the local file you can write a variable with ansible sintax like

{{variable}}

and it will be substituted if it is in the scope of the script. Here the docs.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top