如何使用 Ansible 的 seboolean 模块自动化启用或禁用 Linux 系统中的 SELinux 布尔值(例如 httpd_use_nfs),并确保更改在重启后仍然有效?以下是一个示例,展示如何通过 Ansible Playbook 实现这一目标。
Ansible 模块 seboolean 概述
模块名称:ansible.posix.seboolean
功能:切换 SELinux 布尔值
ansible.posix.seboolean 是 Ansible POSIX 模块集合的一部分,用于管理 SELinux 布尔值。
该模块非常稳定,已经存在多年,支持多种 Linux 发行版和 POSIX 系统。
目标系统需要安装 python3-libsemanage 或 libsemanage-python 包。
参数介绍
name(字符串):SELinux 布尔值的名称。state(布尔值):是否启用或禁用该布尔值(true或false)。persistent(布尔值):是否将更改应用于下次启动(true或false)。ignore_selinux_state(布尔值):是否忽略当前 SELinux 状态,适用于无法获取当前状态的场景(如 chroot 环境)。
示例:使用 Ansible Playbook 启用或禁用 SELinux 布尔值
Playbook 文件:selinux_boolean.yml
---
- name: seboolean module demo
hosts: all
become: true
vars:
selinux_boolean: "httpd_use_nfs" # SELinux 布尔值名称
selinux_value: true # 布尔值状态
tasks:
- name: 确保依赖包已安装
ansible.builtin.package:
name: "python3-libsemanage"
state: present
- name: 设置 SELinux 布尔值
ansible.posix.seboolean:
name: "{{ selinux_boolean }}"
state: "{{ selinux_value }}"
persistent: true
执行命令
$ ansible-playbook -i virtualmachines/demo/inventory selinux/selinux_boolean.yml
执行结果
PLAY [seboolean module demo] ****************************************************
TASK [Gathering Facts] *****************************************************
ok: [demo.example.com]
TASK [确保依赖包已安装] *****************************************************
changed: [demo.example.com]
TASK [设置 SELinux 布尔值] *****************************************************
changed: [demo.example.com]
PLAY RECAP *********************************************************************
demo.example.com : ok=3 changed=2 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
执行前后对比
执行前:
$ ssh devops@demo.example.com
[devops@demo ~]$ sudo su
[root@demo devops]# sestatus
SELinux status: enabled
SELinuxfs mount: /sys/fs/selinux
SELinux root directory: /etc/selinux
Loaded policy name: targeted
Current mode: enforcing
Mode from config file: enforcing
Policy MLS status: enabled
Policy deny_unknown status: allowed
Memory protection checking: actual (secure)
Max kernel policy version: 33
[root@demo devops]# getsebool httpd_use_nfs
httpd_use_nfs --> off
[root@demo devops]#
执行后:
$ ssh devops@demo.example.com
[devops@demo ~]$ sudo su
[root@demo devops]# getsebool httpd_use_nfs
httpd_use_nfs --> on
[root@demo devops]# reboot
Connection to demo.example.com closed by remote host.
Connection to demo.example.com closed.
$ ssh devops@demo.example.com
[devops@demo ~]$ sudo su
[root@demo devops]# getsebool httpd_use_nfs
httpd_use_nfs --> on
[root@demo devops]#
注意事项
- 依赖包:确保目标系统已安装
python3-libsemanage包。 - 持久化:
persistent: true确保更改在重启后仍然有效。 - 幂等性:如果布尔值状态未发生变化,任务将不会重复执行,确保 Playbook 的幂等性。
希望这个示例对您有帮助!