title: How can I configure /etc/hosts with ansible orchestration
body: <p>The application needs the following hosts:</p>
  
  <pre><code>[foo-servers]
  foo-server ansible_ssh_host=192.168.50.2 
  
  [bar-servers]
  bar-server ansible_ssh_host=192.168.50.3 
  
  [mysql-servers]
  mysql-server ansible_ssh_host=192.168.50.4 
  
  [mongodb-servers]
  mongodb-server ansible_ssh_host=192.168.50.5 
  </code></pre>
  
  <p>I need to configure hosts on foo server and bar server as they need to access mysql and mongodb. To achieve this, I introduce a role named hosts:</p>
  
  <pre><code># roles/hosts/tasks/main.yml
  ---
  - name: change hosts
  template: src=hosts.j2 dest=/etc/hosts
  
  # roles/hosts/templates/hosts.j2
  127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
  ::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
  
  {% for item in hostvars %}
  {{ hostvars[item]['ansible_ssh_host'] }} {{ item }}
  {% endfor %}
  </code></pre>
  
  <p>The problem is when I run </p>
  
  <pre><code>ansible-playbook foo.yml 
  </code></pre>
  
  <p>The /etc/hosts on the target only contains the ip and hostname of the current host, foo-server in this case.</p>
  
  <p>My question is:</p>
  
  <p>How can I get all hosts in the inventory when I run playbook against only one of them?</p>
  
  <p>Or could you suggest some alternatives as I get the wrong idea at the first place.</p>
  
  <p>The alternatives come to my mind are:</p>
  
  <p>Make hosts configuration an individual playbook against all hosts like </p>
  
  <pre><code>---
  - name: Configuring hosts
    hosts: all
    user: root
  
    roles:
      - hosts
  </code></pre>
  
  <p>The drawback is I need to run this playbook before others and this seems not a right way to use roles.</p>