Adding to yaml list using a loop
Ansible playbooks, vars files, etc. are not jinja2 templates, so as you said jinja2 constructs like {% for ... %}
won't work in them. But having said that, it would be a simple matter of simply moving the jinja2 code into the template where it should belong anyway.
If you look at firewall_additional_rules
in firewall.bash.j2 it's only referenced here:
# Additional custom rules.
{% for rule in firewall_additional_rules %}
{{ rule }}
{% endfor %}
All you need to do is either change this around or add another for loop before or after it that contains the exact code you already wrote:
{% for ip in white_listed_ips %}
- iptables -A INPUT -p tcp -s {{ ip }} --dport ssh -j ACCEPT
- iptables -A INPUT -p tcp -s {{ ip }} --dport 80 -j ACCEPT
{% endfor %}
Michael Mallett
Updated on June 04, 2022Comments
-
Michael Mallett almost 2 years
I am using the geerlingguy.firewall ansible galaxy role to add iptables rules. In that there is a firewall_additional_rules list variable where I am adding in some scripts to allow from certain ips, which I want to provide with a another list variable
white_listed_ips: - 1.1.1.1 - 1.1.1.2
etc
I want to be able to generate the firewall_additional_rules list from the white_listed_ips list, by looping through. However I can't find any way of doing this. Can you loop through variables and add to an array in yaml?
So I want to do something like this in a var file (I know this doesn't work, indulge me)
firewall_additional_rules: {% for ip in white_listed_ips %} - iptables -A INPUT -p tcp -s {{ ip }} --dport ssh -j ACCEPT - iptables -A INPUT -p tcp -s {{ ip }} --dport 80 -j ACCEPT {% endfor %}
This is to go into the jinja2 template in the role, you can see here: https://github.com/geerlingguy/ansible-role-firewall/blob/master/templates/firewall.bash.j2
-
nik.shornikov about 9 yearsYep. The only way to translate the ips into rules outside of the normal jinja context will involve
map
and regex. Much easier to do this in the template. Lists -> lists is just ugly with Ansible at the moment. -
Zasz about 9 yearsIts okay to edit roles that you downloaded off ansible-galaxy. It is not like jquery or some such library which should not be hacked. I think OP is trying to add custom rules without editing the downloaded role
-
Michael Mallett about 9 yearsThis isn't what I'm asking, I don't want to edit a role as that means it won't be usable elsewhere. I'm asking for more dynamic ways to alter variables in yaml...is there no way to add to an array/list/whatever? I put the jinja2 syntax in there as an example of what I am trying to do in a var file. If I can't do this, is there a way of overriding the jinja2 template locally in my project?
-
Brad over 7 yearsI have exactly the same challenge as @MichaelMallett.