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

Jakim picture Jakim · Mar 22, 2017 · Viewed 15.6k times · Source

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?

Answer

techraf picture techraf · Mar 22, 2017

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.