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

Question:

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 :

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 :

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:

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

Disclaimer: Did not test this code.

Leave a Reply