Long time ago while I was rewriting our salt formula I got problems with getting value outside for loop.
After some investigation and reading documentation I got next text to get what I need:
{%- set dc_name = ['jotunheimr'] %}
{%- for s_group, s_details in pillar.get('server-groups', {}).items() %}
{%- set s_srvs = pillar.get('server-groups', {}) %}
{%- for srv in s_srvs[s_group] %}
{%- if srv == grains['id'] %}
{%- do dc_name.append(s_group) %}
{%- endif %}
{%- endfor %}
{%- endfor %}
{%- if dc_name|length > 1 %}
{%- endif %}
{%- set bacula_path = salt['pillar.get']('datacenters:%s:srv_ip' % dc_name|last, '127.0.0.1') %}
So lets take a closer look on this code.
We use some group name which won’t exist in our infrastructure. I decided to go with jotunheimr
. Now create a list with such value inside.
Next in for loop we check if our server name is in specific server group in pillar and if yes we need to run:
{%- do dc_name.append(s_group) %}
As result if our server is in any defined group from pillar we will get list with two or more values.
Since I need only one server group, I just run dc_name|last
and get last element from my list.