How to use hosts listed in a group in a template, excluding the current host.

I’m new to Ansible and want use it to configure a NTP service. here is my situation:

my hosts file:

[ntp_servers]
s1.aaa.com
s2.aaa.com
s3.aaa.com
s4.aaa.com

The “/taskts/mail.yaml” for role “ntp_server”:

  • name: install ntp
    apt: name=ntp state=present

  • name: config ntpd
    template: src=ntp.conf dest=/etc/ntp.conf

The “templates/ntp.conf” for role “ntp_server”:


restrict {{ ntp_net }} mask {{ ntp_netmask }} nomodify notrap
{% for svr in servers %}
peer svr
{% endfor %}

My questions are about for loop in the template file (please leave along the NTP specific things):

  1. How to refer the hosts defined in the hosts file from within the template file? In another words, I need the value of “servers” variable in the for loop to be a list of “s1.aaa.com”, “s2.aaa.com” …

  2. How to know the current host so that the for loop could exclude it(it should not be peer to itself) ?

Thanks and Regards
John

Try something like this:

{% for svr in groups.ntp_servers %}
  {% if not svr == inventory_hostname %}
  peer svr
  {% endif %}
{% endfor %}

also:

{% for svr in groups.ntp_servers|difference([inventory_hostname]) %}
  peer svr
{% endfor %}

I know it should be simple, but never imagine it is soooo simple. Thanks guys.