Link to home
Start Free TrialLog in
Avatar of Jasmin shahrzad
Jasmin shahrzad

asked on

editing task.yml in ansible

i have a task in my ansible like that

-name: edit hostfile

     path: '/etc/hosts'

      regexp:'10.2.2.1 fileserver.domain'

      replace : 10.2.2.1 fileserver.domain nextcloud'

Then every time ansible running is add nextcloud to my host file. 

how to say if not exist then add nextcloud.

Avatar of David Favor
David Favor
Flag of United States of America image

1) Well, this might or might not work as the 10.X.X.X series of addresses are normally... implicitly reserved by all manner of software...

When means, you might get everything working, then a reboot or OS upgrade may break all your work when the 10.X.X.X addresses used change completely.

2) The simple answer to your question is to use a pipeline... many ways to do this... 1x approach is something like this...

grep -q -P /etc/hosts "10.2.2.1 fileserver.domain nextcloud" || echo "10.2.2.1 fileserver.domain nextcloud" >> /etc/hosts

Open in new window


I'm unsure if there's a facility in ansible which duplicates this logic.

If not, use a pipeline.
ASKER CERTIFIED SOLUTION
Avatar of simon3270
simon3270
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Jasmin shahrzad
Jasmin shahrzad

ASKER

ok thanks,
but if it running more than 1 it's always find ip and fileserver.domain and adding nextcloud or what?
if i run 2 times then host file has a line like that:
10.2.2.1 fileserver.domain nextcloud nextcloud because they always file the first part and adding second
Or what?

What I think it does is find any line matching "10.2.2.1 fileserver.domain" (with any amount of text following it on the line) and replaces the entire line with "10.2.2.1 fileserver.domain nextcloud", so however many times it does it, the line ends up as just "10.2.2.1 fileserver.domain nextcloud".

There are things you can do to use the original line as a basis for the replacement line (look at the "backrefs" option in "lineinfile"), but that might lead to the very problem you had with adding "nextcloud" each time you ran the playbook. There are other Ansible modules for replacing multiple lines, or for creating a file from a template, which may be more appropriate for what you are trying to do.
you right correct. i run it and it's not adding .