Using the magic variable groups

Can I use a variable to insert inventory group when using groups; e.g. groups[‘$groupname’]?

no, that is what group_by action is for, that variable is a copy and
modifications won't persist

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.

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

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.