从一点管理 iptables 并能够在本地服务器上编辑某些内容的最佳方法是什么。
我们需要在所有服务器上集中添加一些规则,但是我们有具有特定要求的特定服务器,它们应该有自己的规则集。
我想到了具有多个包含的 bash 脚本,它由 ansible 集中管理,并在本地服务器上管理。这是好方法吗?或者也许有更好的东西?
我们无法为ansible创建yml2模板,因为特定主机之间的差异太大。
请提供iptables集中管理的例子。
Ant*_*des 25
Ansible
有一个ufw
模块来处理防火墙规则。在roles/common/tasks/main.yml
包含在我所有服务器中的 中,我有(除其他外):
- name: Install ufw
apt: name=ufw
- name: Allow ssh through firewall
ufw: proto=tcp port=22 rule=allow
- name: Set ufw policy
ufw: state=enabled direction=incoming policy=deny
Run Code Online (Sandbox Code Playgroud)
编辑:在将默认策略设置为“拒绝”之前必须允许 ssh(最初与上面相反),否则您可能会在两个步骤之间被锁定。
然后,在每个角色中,我都有针对该角色的附加防火墙规则。例如,在roles/nginx/tasks/main.yml
,我有(除其他外)这个:
- name: Allow nginx firewall
ufw: proto=tcp port=80 rule=allow
- name: Allow nginx ssl firewall
ufw: proto=tcp port=443 rule=allow
Run Code Online (Sandbox Code Playgroud)
所以我所有的 nginx 服务器都打开了端口 80 和 443。
通过这种方式,您可以构建所需的任何通用配置,并在更具体的角色中添加其他规则。
如果您有ufw
无法处理的规则,我认为可以很好地工作的一种解决方案是ferm
;它几乎可以做任何事情,你可以配置它来读取目录等规定/etc/ferm/input.d/
,/etc/ferm/output.d/
,/etc/ferm/forward.d/
等你可以让你的common
角色做准备的基本ferm
配置,然后有其他角色在这些目录中拖拽文件。
ansible
除了以另一种方式指定的规则之外,您还要求指定规则是不寻常的,并且显然违背了使用ansible
. 不幸的是,除了使用 plain 之外iptables
,我看不到任何其他方法,这会非常难看。这是在roles/nginx/tasks/main.yml
(未经测试)中打开端口 80 的示例:
- name: Check if port 80 is allowed
shell: iptables -L | grep -q "Allow http" && echo -n yes || echo -n no
register: check_allow_http
changed_when: no
always_run: yes
- name: Allow port 80
command: >
iptables -A INPUT -p tcp -m tcp --dport 80
-m comment --comment "Allow http" -j ACCEPT
when: check_allow_http.stdout == "no"
notify:
- Save iptables
Run Code Online (Sandbox Code Playgroud)
哪里Save iptables
是执行iptables-save
. 以上所有写起来都相当乏味,但它可能是合适的,特别是如果你只有几条规则需要管理ansible
。
Phi*_*son 12
如果您想在 iptables 配置中管理规则而不覆盖现有规则或在模板中集中管理 iptables,请使用 Ansible 的 lineinfile 模块:
- name: ensure iptables allows established and related traffic
lineinfile:
dest=/etc/sysconfig/iptables
state=present
regexp="^.*INPUT.*ESTABLISHED,RELATED.*ACCEPT"
insertafter="^:OUTPUT " line="-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT"
backup=yes
notify: restart iptables
- name: ensure iptables is configured to allow ssh traffic (port 22/tcp)
lineinfile:
dest=/etc/sysconfig/iptables
state=present
regexp="^.*INPUT.*tcp.*22.*ACCEPT"
insertafter="^.*INPUT.*ESTABLISHED,RELATED.*ACCEPT" line="-A INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT"
backup=yes
notify: restart iptables
Run Code Online (Sandbox Code Playgroud)
这是“重启 iptables”处理程序:
- name: restart iptables
service: name=iptables state=restarted
Run Code Online (Sandbox Code Playgroud)