using inventory group name as var?

I am sure that i am just glossing over this in the documentation, but here goes anyway:

i am tryingto identify how i can use a hosts group name

host_group_1:
host1:
host2:

in such a way that i can call it in a task and use the actual name of the group as a variable.

if i run a playbook against host1 from above and have a task that does a lineinfile on /etc/somefile:

line1
line2
line3
lineX

the line that i am inserting would be “host_group_1” that i would do an insertbefore “lineX”

i am trying to avoid for every host group, having some variable with the same name as the host group. seems silly, redundant and avoidable. I am guessing that i am just not searching for the right thing in the documentation. any pointers?

Hi Matthew,

Not sure if this is what you are looking for but I use the host group name to create a custom directory to store files (basically show command output from network devices).

I use the ansible facts group_name list which gives a list of all the groups to which the host belongs. In my case each hosts belongs to just a single group so that list will contain one element which I reference as you see by group_names[0] and use it to build my custom directory (which I also time stamps so I get something like logs_cisco_2019-05-13 as my directory). You do have to gather facts which might make your run a bit longer.

group_names is one of the Ansible “Magic” Variables and you can read more about those here:
https://docs.ansible.com/ansible/latest/reference_appendices/special_variables.html

group_names
List of groups the current host is part of

`

  • hosts: cisco
    gather_facts: yes

  • name: Create Directory
    file:
    path: ./logs_{{ group_names[0] }}_{{ ansible_date_time.date }}
    state: directory
    `

Not sure thats what you were looking for but thought I would suggest on the off chance it is.

ha…that did the trick!

thanks

-m