6

I am not sure on how to find the first ansible hostname from group_names. Could you kindly advise me on how to do it?

hosts

[webservers]
server1
server2
server3

[webserver-el7]
server4
server5
server6

And i have 2 different playbook for each host groups

playbook1.yml

- name: deploy app
  hosts: webservers
  serial: 8
  roles:
    - roles1

playbook2.yml

- name: deploy app
  hosts: webservers-el7
  serial: 8
  roles:
    - roles1

the problem is that i have delegate task to first host of each group. previously i only used webservers group, so it was much easier by using the task below

- name: syncing web files to {{ version_dir }}
  synchronize:
    src: "{{ build_dir }}"
    dest: "{{ version_dir }}"
    rsync_timeout: 60
  delegate_to: "{{ groups.webservers | first }}"

If i have 2 different group_names, how can i select the first one of each group? so it can be more dynamic

AlamHo
  • 193
  • 1
  • 3
  • 12

2 Answers2

12

If you want the first host of current play to be a kind of master host to sync from, I'd recommend another approach: use one of play_hosts or ansible_play_hosts (depending on your Ansible version) variables. See magic variables.
Like delegate_to: "{{ play_hosts | first }}".

The thing is when you say hosts: webservers-el7 to Ansible webservers-el7 is a pattern here. Ansible search for hosts to match this pattern and feed them into Play. You may have written webservers-el* as well. So inside Play you don't have any variable that will tell you "I'm running this Play on hosts from group webserver-el7...". You may only make some guess work analyzing group_names and groups magic variables. But this become clumsy when you have one host in several groups.

For hosts in single group only, you may try: groups[group_names | first] | first

Community
  • 1
  • 1
Konstantin Suvorov
  • 65,183
  • 9
  • 162
  • 193
  • Just tried the play hosts and it would work perfectly unless i was not using serial deployment. i would like to use the master host to sync from but on the next serial play, the first play_hosts will change again. currently my hosts will only belong to single group only. do you know how to get the first hostname from group_names? i already tried several variable but still no luck – AlamHo Jan 10 '17 at 16:10
  • Updated answer with example. Also you may consider to use Ansible 2.2+ with `ansible_play_hosts` – it contains full lists for each serial run. – Konstantin Suvorov Jan 10 '17 at 16:17
  • Nice. it works really well. ansible_play_hosts would works too. Thanks a lot for your ansible expertise – AlamHo Jan 11 '17 at 00:28
  • @KonstantinSuvorov: How can we get second hostname of group – Suresh Mar 04 '21 at 09:58
1

To get any element from group, use group[group_name][0...n].

This will get the first element from the group.

- debug: msg="{{ groups['group_name'][0] }}"
Feroz
  • 13
  • 3