How to set up / etc / hosts with orchestration

The application needs the following hosts:

[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 

      

I need to set up hosts on foo server and bar server, as they need to access mysql and mongodb. To achieve this, I present a role named hosts:

# 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 %}

      

The problem is that I am running

ansible-playbook foo.yml 

      

In this case, / etc / hosts on the target server only contains the ip and hostname of the current host, foo-server.

My question is:

How can I get all hosts in my inventory when I run a playbook against just one of them?

Or could you suggest some alternatives as I am getting the wrong idea in the first place.

Alternatives come to my mind:

Make hosts a separate play configuration for all hosts such as

---
- name: Configuring hosts
  hosts: all
  user: root

  roles:
    - hosts

      

The downside is that I need to run this workbook in front of others, and this seems like the wrong way to use roles.

+4


source to share


2 answers


Indeed, this is strange as even the docs say:

If at this point you haven't talked to this host yet in any playbook or slot machine set, you might get the variables, but you won't be able to see the facts.

My understanding from this is that you might not get the collected facts if the host has not yet been "requested", but you should still see the variables defined in the inventory (and in the groups / hosts). Maybe you should push this to the mailing list.



At the same time, you can solve your problem by using groups['all']

to loop over your hosts:

127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6

{% for item in groups['all'] %}
{{ hostvars[item]['ansible_ssh_host'] }} {{ item }}
{% endfor %}

      

+6


source


127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6

{% for host in groups['all'] %}

{{ hostvars[host].ansible_default_ipv4.address }} {{ host  }}   {{ hostvars[host].ansible_fqdn }}

{% endfor  %}

      



0


source







All Articles