1

How can I run a playbook only on one/first host in all the groups?

[tomcat]
tomcat123.com
tomcat34523.com
tomcats43523.com

[apache]
apache23452.com
apache32452.com

[sql]
sql21341.com
sql123414.com

[all]
tomcat
apache
sql

So, how can I run the playbook on one server or the first server from multiple groups listed above.

β.εηοιτ.βε
  • 33,893
  • 13
  • 69
  • 83
Harsha S
  • 11
  • 2
  • Regarding your comments "_the host names are not in any pattern_" and "_I have almost around 30 groups of servers., Is there any other way instead of doing the above method?_", can you provide more details about your inventory and the naming convention used for hosts and groups? It might be possible to answer your question then. – U880D Sep 30 '22 at 08:10
  • Here is [my answer](https://stackoverflow.com/questions/73944342/ansible-how-to-launch-playbook-only-on-the-first-host-of-each-inventory-group/73948688#73948688) for the same case – Khaled Oct 05 '22 at 07:33

1 Answers1

3

You can use subscripts to select individual hosts or ranges within the groups.

- name: Hello play
  hosts: "group1[0]:group2[0]:group3[0]"
  tasks:
    - name: Message
      debug: 
        msg: "hello world"

Documentation: https://docs.ansible.com/ansible/latest/user_guide/intro_patterns.html

β.εηοιτ.βε
  • 33,893
  • 13
  • 69
  • 83
iamlucas
  • 131
  • 4
  • May be I need to edit my question, the host names are not in any pattern – Harsha S Sep 29 '22 at 16:22
  • Oh okay, so i updated the answer. You can get the first hosts using subscripts group[0]. – iamlucas Sep 29 '22 at 16:43
  • Thank you, that helps if I have few groups, but I have almost around 30 groups of servers., Is there any other way instead of doing the above method? – Harsha S Sep 29 '22 at 16:44
  • @HarshaS, regarding "_Is there any other way instead of doing the above method?_" there is an answer available under [Ansible - How to launch playbook only on the first host of each inventory group?](https://stackoverflow.com/a/73947076/6771046), however, it is using "the method" (annot. _subscripts to select individual hosts or ranges within the groups_) and additionally a way to create the list of groups and ranges within the groups dynamically. – U880D Oct 04 '22 at 11:40