Using the magic variable groups

25 views
Skip to first unread message

Harrymosco

unread,
Aug 9, 2019, 11:11:41 AM8/9/19
to Ansible Project
Can I use a variable to insert inventory group when using groups; e.g.  groups['$groupname']?

Brian Coca

unread,
Aug 13, 2019, 2:46:12 PM8/13/19
to Ansible Project
no, that is what group_by action is for, that variable is a copy and
modifications won't persist


----------
Brian Coca

Harrymosco

unread,
Aug 14, 2019, 2:24:06 PM8/14/19
to Ansible Project
Thank you Brian.

I have looked at "group_by" and I am still trying to figure out how to use it in my case.

Maybe you can help me with how to make the piece of code below to be more generically used for any <group_name>.
I am using it in a template, to build a list of IP of hosts in a group so that I can use them to configure a cluster of servers.

Or if there is a better way of achieving the same purpose, please let me know.


 {%for host in groups['<group_name>']%}"{{hostvars[host]['ansible_default_ipv4']['address']}}"{% if not loop.last %},{% endif %}{% endfor %}


I want to achieve having a config line like below:
#discovery.zen.ping.unicast.hosts: ["IP_Node1","< IP_Node2 >",“<IP_Node3>"]

where there are 3 hosts in the <group_name>.

Thanks.

Kai Stian Olstad

unread,
Aug 14, 2019, 5:14:41 PM8/14/19
to ansible...@googlegroups.com
On 14.08.2019 20:24, Harrymosco wrote:
> Thank you Brian.
>
> I have looked at "group_by" and I am still trying to figure out how to
> use
> it in my case.
>
> Maybe you can help me with how to make the piece of code below to be
> more
> generically used for any <group_name>.
> I am using it in a template, to build a list of IP of hosts in a group
> so
> that I can use them to configure a cluster of servers.
>
> Or if there is a better way of achieving the same purpose, please let
> me
> know.
>
>
> {%for host in
> groups['<group_name>']%}"{{hostvars[host]['ansible_default_ipv4']['address']}}"{%
> if not loop.last %},{% endif %}{% endfor %}

Lets say you have a variable myvar that contain the group name you can
do groups[myvar]


--
Kai Stian Olstad

Harrymosco

unread,
Aug 15, 2019, 8:20:50 PM8/15/19
to Ansible Project
Thanks Kai Stian,

Absolutely what I want. Fantastic!!

All I am doing now is use "--extra-vars" and assign any  <group_name> I want to configure to the variable, and that's it.
The code does not need to be modified anymore for different <group_name>s.

Appreciated!!

-Harrymosco.  

On Friday, August 9, 2019 at 10:11:41 AM UTC-5, Harrymosco wrote:
Reply all
Reply to author
Forward
0 new messages