Improving use of add_host in ansible [duplicate]

孤街醉人 提交于 2019-12-24 23:15:43

问题


I want to put hosts based on info I found on it in a in-memory group that I'll use on a later play.

I use this way based on writing the hostname of the target on the control node and then using this list to loop over with add_host, as add_host "bypasses the host loop and only runs once for all the hosts in the play" (I quote the documentation).

simplified example:

---
- hosts: servers
  tasks:

   - name: check if this server has foo role based on file presence
     stat:
       path: /tmp/foo
     register: role

   - name: write server name in file on control node
     lineinfile:
       path: /tmp/servers_foo.txt
       state: present
       line: "{{ inventory_hostname }}"
     delegate_to: 127.0.0.1
     when: role.stat.isfile is defined and role.stat.isfile

   - name: assign target to group
     add_host:
       name: "{{ item }}"
       groups:
         - foo
     with_lines: cat /tmp/servers_foo.txt

- hosts: foo
  tasks:

  - name: test which servers are part of foo
    ping:
...

The problem of this playbook is the lineinfile task seems buggy because not all servers are written in the control node file.

…
TASK [lineinfile] ******************************************************************************
changed: [toto.foo -> 127.0.0.1]
changed: [tata.foo -> 127.0.0.1]
changed: [titi.foo -> 127.0.0.1]
changed: [tutu.foo -> 127.0.0.1]

TASK [assign target to group] 
changed: [toto.foo] => (item=tata.foo)
changed: [toto.foo] => (item=tutu.foo)
…

this is confirmed by checking the file content on the control node

cat /tmp/servers_foo.txt 
tata.foo
tutu.foo

I'm not sure why I have this problem (race condition on file access?) but to workaround this I added a serial: 1 to the first play, so this way it works but this is terribly slow if I have tens of servers and different check to implement.

Do you have a better and faster implementation of such use case or how could I fix the lineinfile task to not having the problem described.

来源:https://stackoverflow.com/questions/51338376/improving-use-of-add-host-in-ansible

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!