Need help to refer child group in jinja2 template file

Hello All,

Please help or suggest how I can solve this problem.
I will pass

-e group=“1” when calling playbook.

Playbook - file.yml

hosts: servers_{{group}}

  • task:

inventory

[servers_grp1]
server1

[servers_grp2]
server2

[mainservers_1:children]
[servers_grp1]
[servers_grp2]
[servers_grp3]
[servers_grp4]

[mainservers_2:children]
[servers_grp5]
[servers_grp6]
[servers_grp7]
[servers_grp8]

In Jinja2 template file, I am trying to assign a value to variable “pod_num”. But I am unable to get this

If (servers_grp1) is in mainservers_1
then
pod_num = 2
else
pod_num = 4

I tried a couple of things but did not work out.

{% if hosts is in groups[mainservers_1]
{% set pod_num = 2 %}

{% else %}
{% set pod_num = 4 %}

Thanks for helping and guiding.

Hello All,

Please help or suggest how I can solve this problem.
I will pass

-e group="1" when calling playbook.

*Playbook* - file.yml

hosts: servers_{{group}}

This will give you servers_1, but your host is servers_grp1, typo?

- task:
....
.....

*inventory*

[servers_grp1]
server1

[servers_grp2]
server2

....

[mainservers_1:children]
[servers_grp1]
[servers_grp2]
[servers_grp3]
[servers_grp4]

[mainservers_2:children]
[servers_grp5]
[servers_grp6]
[servers_grp7]
[servers_grp8]

In Jinja2 template file, I am trying to assign a value to variable
"pod_num". But I am unable to get this

If (servers_grp1) is in mainservers_1
then
pod_num = 2
else
pod_num = 4

I tried a couple of things but did not work out.

{% if hosts is in groups[mainservers_1]
{% set pod_num = 2 %}

{% else %}
{% set pod_num = 4 %}

This work great, but the variable is only available in the template, not outside of it.
You'll see it work by this code

{% if hosts is in groups[mainservers_1]
{% set pod_num = 2 %}

{% else %}
{% set pod_num = 4 %}
{{ pod_num }}

If you need the variable in the scope of Ansible global you should check out group_vars.
Create a file group_vars/servers_grp1.yml and group_vars/servers_grp1.yml with the appropriate and variables with values.