title: Ansible: how to call module `add_host` for all hosts of the play
body: <p>I'm creating a playbook with this play:</p>
  
  <p>On hosts <code>hypervisors</code>:</p>
  
  <ul>
  <li>retrieve list of virtual machines from all hosts</li>
  <li>use module <code>add_host</code> to add all of them in a new inventory group called <code>guests</code></li>
  </ul>
  
  <p>My inventory:</p>
  
  <pre><code>[hypervisors]
  host1
  host2
  </code></pre>
  
  <p>My playbook:</p>
  
  <pre><code>- hosts: hypervisors
    - shell: virsh list | awk 'NR&gt;2' | awk '{print $2}'
      register: result_virsh
    - add_host:
        name: "{{ item }}"
        group: "guests"
      with_items: "{{ result_virsh.stdout_lines }}"
  </code></pre>
  
  <p>Module <code>add_host</code> <a href="http://docs.ansible.com/ansible/add_host_module.html#notes" rel="noreferrer">bypasses the play host loop and only runs once for all the hosts in the play</a>.</p>
  
  <p>Then it is called once (for host1), it's a particular case of the use of this module (see link above), as if the variable <code>run_once</code> was implicitly fixed to <code>true</code>.</p>
  
  <p>How can I use it for all hosts in group <code>hypervisors</code> ?</p>
  
  <p><strong>EDIT: Example to reproduce it on your computer with only localhost</strong></p>
  
  <p>Create file <em>/tmp/host1_test</em> to simulate a return of guests <em>vm1</em> and <em>vm2</em>:</p>
  
  <pre><code>vm1
  vm2
  </code></pre>
  
  <p>Create file <em>/tmp/host2_test</em> to simulate a return of guests <em>vm3</em> and <em>vm4</em>:</p>
  
  <pre><code>vm3
  vm4
  </code></pre>
  
  <p>Use this inventory (<em>test_add_host.ini</em>) with two hosts, both with fixed IP address <em>127.0.0.1</em>:</p>
  
  <pre><code>[hypervisors]
  host1 ansible_host=127.0.0.1 test_filename=/tmp/host1_test
  host2 ansible_host=127.0.0.1 test_filename=/tmp/host2_test
  </code></pre>
  
  <p>Use this playbook (<em>test_add_host.yml</em>):</p>
  
  <pre><code>- hosts: hypervisors
    gather_facts: no
    tasks:
    - shell: "cat {{ test_filename }}"
      register: result_virsh
    - add_host:
        name: "{{ item }}"
        group: "guests"
      with_items: "{{ result_virsh.stdout_lines }}"
  
  - hosts: guests
    gather_facts: no
    tasks:
    - local_action: ping
  </code></pre>
  
  <p>Call this playbook locally with command:</p>
  
  <pre><code>ansible-playbook -c local -i test_add_host.ini test_add_host.yml
  </code></pre>
  
  <ul>
  <li>First play call hosts <em>host1</em> and <em>host2</em></li>
  <li>Second play call hosts <em>vm1</em> and <em>vm2</em></li>
  </ul>
  
  <p>What should I do to call all hosts (<em>vm1</em>, <em>vm2</em>, <em>vm3</em> and <em>vm4</em>) in second play ?</p>