使用 Ansible 进行配置一致性检查,可以创建一个角色(role),用于验证集群中所有主机的配置文件是否与预期的标准配置一致。这通常涉及到检查文件内容、配置参数等。
以下是创建一个用于配置一致性检查的角色的示例:
首先,创建角色的基础目录结构:
config_consistency_check/
├── defaults
│ └── main.yml
├── files
│ └── (可能存放一些需要部署的配置文件)
├── handlers
│ └── main.yml
├── meta
│ └── main.yml
├── tasks
│ └── main.yml
└── vars
└── main.yml
以下是每个文件的内容示例:
tasks/main.yml
: 定义要执行的配置一致性检查任务。
---
# 配置一致性检查任务列表
- name: 检查 SSH 配置
ansible.builtin.lineinfile:
path: /etc/ssh/sshd_config
regexp: '^PermitRootLogin'
line: 'PermitRootLogin no'
state: present
- name: 检查 SELinux 状态
ansible.builtin.command: getenforce
register: selinux_status
failed_when: selinux_status.stdout != 'Enforcing'
- name: 验证配置文件一致性
ansible.builtin.assert:
that:
- 'item.file == expected_config[item.file]'
with_items: "{{ hosts }}"
vars:
hosts:
- file: '/etc/nginx/nginx.conf'
- file: '/etc/my.cnf'
expected_config:
'/etc/nginx/nginx.conf': 'expected nginx config content'
'/etc/my.cnf': 'expected mysql config content'
vars/main.yml
: 定义变量,存储预期的配置内容。
# 预期的配置内容
expected_configs:
'/etc/ssh/sshd_config': 'PermitRootLogin no'
'/etc/nginx/nginx.conf': 'server {...}'
# 更多配置文件和预期内容
defaults/main.yml
: 设置默认变量,可以为空。
# 默认变量文件,可以定义一些默认值供其他变量文件覆盖
handlers/main.yml
: 定义触发器,可以为空。
# 角色的触发器列表,通常用于处理任务状态变化
meta/main.yml
: 角色依赖和元数据,可以为空。
# 角色的元数据,可以定义角色依赖等信息
files/
: 目录中可以存放需要部署到远程主机上的配置文件。
要使用此角色,你需要在 Playbook 中引入它:
---
- name: 配置一致性检查
hosts: all
become: yes
roles:
- config_consistency_check
确保将此角色放置在正确的目录中,并且 Ansible 配置文件 ansible.cfg
或 Playbook 中指定了正确的角色搜索路径。
请注意,这只是一个示例,实际的配置一致性检查可能需要更详细的检查和复杂的逻辑。你可能需要根据你的具体需求和环境来调整和扩展角色中的任务。此外,Ansible 还提供了许多其他模块,如 stat
, file
, command
, assert
等,可以帮助你执行配置一致性检查。