Search code examples
ansibleansible-inventory

How to make Ansible playbook run on first host in the group?


How can I run a playbook only on first host in the group?

I am expecting something like this:

---
- name: playbook that only run on first host in the group
  hosts: "{{ groups[group_name] | first }}"

  tasks:
   - debug:
       msg: "on {{ inventory_hostname }}"

But this doesn't work, gives error:

'groups' is undefined

How can I make it work?


Solution

  • You can use:

    hosts: group_name[0]
    

    Inventory hosts values (specified in the hosts directive) are processed with a custom parser, which does not allow Jinja2 expressions like the regular template engine does.

    Read about Patterns.