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' ?

有帮助吗?

解决方案 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

其他提示

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top