Reputation: 133
I have a template file iptables.j2
which contains a few core rules (e.g. allowing SSH connections). However depending on the role of a node, that template will contain additional rules which cannot be managed using variables. e.g. mongo nodes will need to open port 27000 and nginx nodes ports 80 & 443 etc..
Are there examples of conditional includes of extra content into a base template that can solve my problem ?
Upvotes: 1
Views: 2378
Reputation: 20739
Would having your iptables.j2 file look something like this work?
# default SSH rules, etc.
{% if inventory_hostname in groups['nginx'] %}
# rules for nginx servers
{% endif %}
{% if inventory_hostname in groups['mongo'] %}
# rules for mongo servers
{% endif %}
Of course this would depend on your hosts being in the appropriate groups.
Upvotes: 3
Reputation: 35139
You can check if inventory_hostname
varaible in desired group
.
For example:
---
- hosts: all
gather_facts: no
tasks:
- name: Custom iptables
template: src=iptables.j2 dest="./table-{{ inventory_hostname }}"
delegate_to: 127.0.0.1
[all-hosts]
ansible ansible_ssh_host=192.168.42.2
webapp ansible_ssh_host=192.168.42.10
postgresql ansible_ssh_host=192.168.42.20
[ansible-host]
ansible
[webapp-hosts]
webapp
[postgresql-hosts]
postgresql
Then your template would look similar to this one:
-A INPUT -p tcp --tcp-flags ALL NONE -j DROP
-A INPUT -p tcp ! --syn -m state --state NEW -j DROP
-A INPUT -p tcp --tcp-flags ALL ALL -j DROP
{% if inventory_hostname in groups['webapp-hosts'] %}
Open 443 port
{% endif %}
{% if inventory_hostname in groups['postgresql-hosts'] %}
Open 5432 port
{% endif %}
If you run the above playbook it will generate 3 files each of them will be different.
Upvotes: 2