如何在Ansible中通过Jinja2模板为Firewalld富规则批量配置源IP?
批量配置Firewalld富规则的几种可行方案
我来给你几个实用的批量配置方法,都是实际运维中验证过的,应该能解决你复用规则、批量添加不同源IP的问题:
方法1:直接在Playbook里定义IP列表变量,结合循环
这种方法最简单直观,把需要授权的IP列表直接写在Playbook的变量里,然后用loop循环每个IP生成对应的富规则:
- name: 批量配置firewalld ICMP允许规则 hosts: your_target_hosts vars: allowed_icmp_ips: - 192.168.1.10 - 192.168.1.20 - 10.0.0.50 tasks: - name: 添加ICMP允许的富规则 ansible.posix.firewalld: rich_rule: rule family='ipv4' source address='{{ item }}' protocol value='icmp' accept permanent: yes immediate: yes state: enabled loop: "{{ allowed_icmp_ips }}"
解释一下:loop会遍历allowed_icmp_ips里的每个IP,每次循环都生成一条独立的富规则,这样每个源IP就都有了对应的ICMP允许规则。
方法2:读取外部src.txt文件的IP列表,动态生成规则
如果你习惯把IP放在单独的文本文件里(比如你的src.txt),可以用Ansible的lookup插件读取文件内容,转成列表后再循环:
假设你的src.txt内容是每行一个IP:
192.168.1.10 192.168.1.20 10.0.0.50
对应的Playbook:
- name: 从文件读取IP批量配置firewalld规则 hosts: your_target_hosts tasks: - name: 获取src.txt里的IP列表 set_fact: allowed_icmp_ips: "{{ lookup('file', 'src.txt').splitlines() | reject('equalto', '') | list }}" delegate_to: localhost - name: 批量添加ICMP允许富规则 ansible.posix.firewalld: rich_rule: rule family='ipv4' source address='{{ item }}' protocol value='icmp' accept permanent: yes immediate: yes state: enabled loop: "{{ allowed_icmp_ips }}"
这里的splitlines()把文件内容按行拆分,reject('equalto', '')是为了过滤掉文件里的空行,避免生成无效规则。delegate_to: localhost是让Ansible在本地读取src.txt,不用把文件传到目标主机上。
方法3:如果需要更复杂的规则复用(比如不同协议/动作)
要是你以后需要复用不同的规则模板(比如有的IP允许ICMP,有的允许SSH),可以把规则模板和IP列表结合成字典变量:
- name: 批量配置多种firewalld规则 hosts: your_target_hosts vars: firewall_rules: - src_ip: 192.168.1.10 rule_template: "rule family='ipv4' source address='{{ item.src_ip }}' protocol value='icmp' accept" - src_ip: 192.168.1.20 rule_template: "rule family='ipv4' source address='{{ item.src_ip }}' service name='ssh' accept" - src_ip: 10.0.0.50 rule_template: "rule family='ipv4' source address='{{ item.src_ip }}' port port='8080' protocol='tcp' accept" tasks: - name: 批量添加自定义规则 ansible.posix.firewalld: rich_rule: "{{ item.rule_template }}" permanent: yes immediate: yes state: enabled loop: "{{ firewall_rules }}"
注意事项
- 确保目标主机已经安装了
firewalld服务,并且服务处于运行状态; - 如果你的规则不需要永久生效,可以把
permanent: yes改成no; - 要是需要删除规则,只需要把
state: enabled改成disabled即可; - 如果src.txt里有注释行,比如以
#开头的,可以再加个过滤:| reject('match', '^#'),这样就能忽略注释了。
内容的提问来源于stack exchange,提问作者Vithushan Rasalingam
相关产品推荐
相关产品推荐

