Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I configure /etc/hosts with ansible 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 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:

# 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 when I run

ansible-playbook foo.yml 

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

My question is:

How can I get all hosts in the inventory when I run playbook against only one of them?

Or could you suggest some alternatives as I get the wrong idea at the first place.

The alternatives come to my mind are:

Make hosts configuration an individual playbook against all hosts like

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

  roles:
    - hosts

The drawback is I need to run this playbook before others and this seems not a right way to use roles.

like image 272
Yugang Zhou Avatar asked Nov 14 '14 03:11

Yugang Zhou


1 Answers

Indeed this is weird, since even the docs say :

If, at this point, you haven’t talked to that host yet in any play in the playbook or set of playbooks, you can get at the variables, but you will not be able to see the facts.

I understand from this that you might not get gathered facts if host hasn't been "queried" yet, but you still should see variables defined in inventory (and group/host vars). May be you should push that to the mailing list.

In the mean time, you can solve your problem using groups['all'] to loop over your hosts instead :

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 %}
like image 92
leucos Avatar answered Sep 22 '22 02:09

leucos