title: Improving use of add_host in ansible
body: <p>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.</p>
  
  <p>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 <code>add_host</code>, as add_host "<em>bypasses the host loop and only runs once for all the hosts in the play</em>" (I quote the documentation).</p>
  
  <p>simplified example:</p>
  
  <pre><code>---
  - 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:
  ...
  </code></pre>
  
  <p>The problem of this playbook is the <code>lineinfile</code> task seems buggy because not all servers are written in the control node file.</p>
  
  <pre><code>…
  TASK [lineinfile] ******************************************************************************
  changed: [toto.foo -&gt; 127.0.0.1]
  changed: [tata.foo -&gt; 127.0.0.1]
  changed: [titi.foo -&gt; 127.0.0.1]
  changed: [tutu.foo -&gt; 127.0.0.1]
  
  TASK [assign target to group] 
  changed: [toto.foo] =&gt; (item=tata.foo)
  changed: [toto.foo] =&gt; (item=tutu.foo)
  …
  </code></pre>
  
  <p>this is confirmed by checking the file content on the control node</p>
  
  <pre><code>cat /tmp/servers_foo.txt 
  tata.foo
  tutu.foo
  </code></pre>
  
  <p>I'm not sure why I have this problem (race condition on file access?) but to workaround this I added a <code>serial: 1</code> 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.</p>
  
  <p>Do you have a better and faster implementation of such use case or how could I fix the <code>lineinfile</code> task to not having the problem described.</p>