How do you get group name of the executing role in ansible

Shreya Bhat picture Shreya Bhat · Mar 20, 2018 · Viewed 22.4k times · Source

I have a use case where I need to create a directory in all hosts in a group whose name will be the name of the group.

Eg : I create a dynamic inventory file with output of the form :

{
   "db": ["host1", "host2", "host3"],
   "logs": ["host2"],
   "misc": ["host4"]
}

I need to create a directory by the name db in every host of the group db and directory named log in every host of the group log.

My playbook so far looks like :

- hosts: db
  tasks:
  - name: create db directory
    file: path=db state=directory

- hosts: logs
  tasks:
  - name: create logs directory
    file: path=logs state=directory

The number of groups is at least 10+. This may grow in the future. I want to write something that will be easily extendable and manageable for the future groups.

I read that ansible doesn't provide a default fact or variable for group name for the task. I see that this can be best done if I provide a variable like groupname in host.

Is there a better solution that could use looping instead of repeating the same task?

Answer

Darney picture Darney · Mar 20, 2018

You can use the magic variable group_names. The variable is a list (array) of all the groups the current host is in. More information is available per the documentation

- hosts: all
  tasks:
  - name: create db directory
    file: 
      path: "{{ item }}" 
      state: directory
    with_items: "{{ group_names }}"

Disclaimer: Did not test this code.