深色模式
配置管理基线:统一 OS 与内核参数
摘要:同一批机器参数不一致,是排查不尽的玄学故障源头。本文用 Ansible 把内核参数、资源限制、时间同步、SSH 安全配置固化成 baseline role,并可持续校正漂移。
适用环境
- 多台 Linux 服务器(AlmaLinux 9 / Ubuntu 22.04 均可)
- 已配置 SSH 免密与 inventory
- 有 root 或 sudo 权限
操作步骤
1. 内核参数(sysctl)
yaml
# roles/baseline/defaults/main.yml
baseline_sysctl:
net.core.somaxconn: 65535
net.ipv4.tcp_syncookies: 1
vm.swappiness: 10
fs.file-max: 10000001
2
3
4
5
6
2
3
4
5
6
yaml
- name: Apply sysctl settings
ansible.posix.sysctl:
name: "{{ item.key }}"
value: "{{ item.value }}"
sysctl_file: /etc/sysctl.d/99-baseline.conf
reload: true
loop: "{{ baseline_sysctl | dict2items }}"1
2
3
4
5
6
7
2
3
4
5
6
7
需先装集合:ansible-galaxy collection install ansible.posix。
2. 资源限制与时间同步
yaml
- name: Set nofile and nproc limits
ansible.builtin.lineinfile:
path: /etc/security/limits.d/99-baseline.conf
create: true
line: "{{ item }}"
mode: '0644'
loop: ["* - nofile 655350", "* - nproc 65535"]
- name: Install and start chrony
ansible.builtin.package: { name: chrony, state: present }
- name: Ensure chronyd running
ansible.builtin.service: { name: chronyd, state: started, enabled: true }1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
3. SSH 安全基线
yaml
- name: Harden sshd config
ansible.builtin.lineinfile:
path: /etc/ssh/sshd_config
regexp: "^{{ item.key }}\\s"
line: "{{ item.key }} {{ item.value }}"
validate: '/usr/sbin/sshd -t -f %s'
loop:
- { key: "PermitRootLogin", value: "no" }
- { key: "PasswordAuthentication", value: "no" }
notify: reload sshd1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
危险
禁用 PasswordAuthentication 前必须确认密钥登录已验证可用,且保留一个已登录的会话不退出,否则会把所有机器锁在外面。
4. 落地策略:先观测再强制
bash
ansible-playbook -i inventory.ini baseline.yml --check --diff # 只看不改
ansible-playbook -i inventory.ini baseline.yml --limit web01 # 灰度 1 台
ansible-playbook -i inventory.ini baseline.yml # 观察无异常后全量1
2
3
2
3
验证
bash
ansible all -i inventory.ini -m command -a 'sysctl net.core.somaxconn'
ansible all -i inventory.ini -m command -a 'chronyc tracking'1
2
2
- [ ] 所有机器 sysctl 返回值一致
- [ ]
chronyc sources有可用时间源,偏差在毫秒级 - [ ] 再次执行 playbook
changed=0(基线已稳定)
常见坑
limits 改了不生效
limits.conf 只对通过 PAM 登录的新会话生效,systemd 服务不受其控制。服务级限制要在 unit 里加 LimitNOFILE=。
sysctl 参数名因内核而异
例如 net.ipv4.tcp_tw_recycle 在新内核已被移除。写基线前先 sysctl -a | grep 确认。
全量推基线导致批量故障
内核参数会立即生效。严禁一次性对所有生产机器推未验证参数,必须灰度 + 观察。