using inventory group name as var?

16 views
Skip to first unread message

Matthew Arguin

unread,
May 10, 2019, 3:08:01 PM5/10/19
to ansible...@googlegroups.com
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?


Claudia de Luna

unread,
May 13, 2019, 9:27:16 AM5/13/19
to Ansible Project
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.

Matthew Arguin

unread,
May 14, 2019, 7:51:49 AM5/14/19
to ansible...@googlegroups.com
ha..that did the trick! 

thanks
-m

--
You received this message because you are subscribed to the Google Groups "Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email to ansible-proje...@googlegroups.com.
To post to this group, send email to ansible...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/ansible-project/7bbeca1d-19b7-46c5-94de-bc07d24311d4%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Reply all
Reply to author
Forward
0 new messages