Ansible 中 firewalld 模块
firewalld模块介绍
Ansible使用firewalld模块配置防火墙规则。所有服务都是基于TCP或UDP的某些端口,比如http服务基于TCP80端口,配置服务器的防火墙,只需要在防火墙规则中添加或删除服务或端口即可。防火墙设置默认规则为拒绝,没有明确开放的,都默认拒绝。
firewalld模块常用选项:
- port:声明端口
- permanent:永久生效,但不会立即生效
- immediate:立即生效,临时生效
- state:enabled,放行;disabled拒绝
配置防火墙规则,放行http协议,代码示意如下:
[root@pubserver ansible]# vim firewall.yml
---
- name: configure webservers
hosts: webservers
tasks:
- name: install nginx pkg
yum: # 调用yum模块安装nginx
name: nginx
state: present
- name: start nginx service
service: # 开启nginx服务,并设置开机自启
name: nginx
state: started
enabled: yes
- name: install firewalld pkg
yum: # 调用yum模块安装firewalld
name: firewalld
state: present
- name: start firewalld service
service: # 启动firewalld服务,并设置开机自启
name: firewalld
state: started
enabled: yes
- name: set firewalld rules
firewalld: # 设置防火墙,开启80端口
port: 80/tcp
permanent: yes
immediate: yes
state: enabled
# 运行playbook
[root@pubserver ansible]# ansible-playbook firewall.yml
PLAY [configure webservers] ***********************************************************************************************************************
TASK [Gathering Facts] ****************************************************************************************************************************
ok: [web2]
ok: [web1]
TASK [install nginx pkg] **************************************************************************************************************************
changed: [web2]
changed: [web1]
TASK [start nginx service] ************************************************************************************************************************
changed: [web2]
changed: [web1]
TASK [install firewalld pkg] **********************************************************************************************************************
ok: [web2]
ok: [web1]
TASK [start firewalld service] ********************************************************************************************************************
ok: [web2]
ok: [web1]
TASK [set firewalld rules] ************************************************************************************************************************
changed: [web2]
changed: [web1]
PLAY RECAP ****************************************************************************************************************************************
web1 : ok=6 changed=3 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
web2 : ok=6 changed=3 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0