基础设施即代码 / 系统课时
管理用户、组与 SSH Key
管理用户、组与 SSH Key
系统账号最容易因为人工创建、临时加组和手工复制公钥而产生漂移。本课用 Ansible 建立一个可重复执行的访问基线:统一创建组和用户、锁定密码登录、维护 authorized_keys,并验证属主、权限与幂等结果。
学习目标
- 使用
group与user模块声明系统账号和组的目标状态 - 使用
ansible.posix.authorized_key幂等维护 SSH 公钥 - 验证账号组关系、SSH 目录权限和重复执行结果
先准备 SSH Key 管理能力
authorized_key 位于 ansible.posix collection,而不是 ansible-core 内置模块。控制端若尚未安装该 collection,先执行:
ansible-galaxy collection install ansible.posix预期输出会显示 collection 已成功安装;具体版本与安装路径可能不同。
Starting galaxy collection install process
ansible.posix:<VERSION> was installed successfully示例使用控制端的一把 Ed25519 公钥作为 deploy 用户的唯一授权 Key。若没有测试 Key,可先生成一把;私钥只留在控制端,不应复制到被管主机。
ssh-keygen -q -t ed25519 -f ./deploy_ansible -N "" -C "ansible-demo" && test -f ./deploy_ansible.pub && echo "key ready"预期输出只有确认文本;Key 内容本身每次生成都不同。
key ready声明组、用户与授权 Key
下面的 Inventory 以一个 linux 组为例,地址请替换为实际主机。
[linux]
node1 ansible_host=<IP>Playbook 先创建 ops 组,再创建 deploy 用户并加入该组。append: true 可避免覆盖系统可能已赋予的其他附加组;password_lock: true 禁止密码认证该本地账号,但不影响基于公钥的 SSH 登录。
- name: Enforce account access baseline
hosts: linux
become: true
vars:
managed_user: deploy
managed_group: ops
tasks:
# Group is created first so user membership can converge in one run.
- name: Ensure operations group exists
ansible.builtin.group:
name: "{{ managed_group }}"
state: present
- name: Ensure deploy user exists
ansible.builtin.user:
name: "{{ managed_user }}"
groups: "{{ managed_group }}"
append: true
create_home: true
shell: /bin/bash
password_lock: true
state: present
# One authoritative public key is used in this minimal example.
- name: Install the approved SSH public key
ansible.posix.authorized_key:
user: "{{ managed_user }}"
key: "{{ lookup('ansible.builtin.file', './deploy_ansible.pub') }}"
state: present
manage_dir: true
exclusive: true运行 Playbook:
ansible-playbook -i inventory.ini access-baseline.yml预期输出中主机应为可达且无失败;首次执行的变更数取决于目标机原状态。
PLAY RECAP
node1 : ok=<VALUE> changed=<VALUE> unreachable=0 failed=0 skipped=<VALUE> rescued=0 ignored=0验证账号与文件权限
状态管理完成后,检查用户所属组以及 .ssh、authorized_keys 的权限。这里使用 shell 只是为了把几个只读检查合并成一次验证,不用于实际账号变更。
ansible linux -i inventory.ini -b -m ansible.builtin.shell -a 'id deploy; stat -c "%a %U %G %n" /home/deploy/.ssh /home/deploy/.ssh/authorized_keys'预期结果应看到 deploy 属于 ops,SSH 目录和文件归属 deploy。不同系统可能还会显示其他组。
node1 | CHANGED | rc=0 >>
uid=<ID>(deploy) gid=<ID>(deploy) groups=<ID>(deploy),<ID>(ops)
700 deploy deploy /home/deploy/.ssh
600 deploy deploy /home/deploy/.ssh/authorized_keys再次执行同一 Playbook:
ansible-playbook -i inventory.ini access-baseline.yml若账号、组和 Key 均未被外部修改,第二次执行应收敛为 changed=0。
PLAY RECAP
node1 : ok=<VALUE> changed=0 unreachable=0 failed=0 skipped=<VALUE> rescued=0 ignored=0避免把访问基线变成锁门事故
exclusive: true 会删除目标用户 authorized_keys 中未声明的其他 Key,因此它适合“Ansible 是唯一权威来源”的场景。若同一用户需要多把 Key,应把所有允许的公钥一次性合并传给 key,不要在循环中逐把配合 exclusive: true 执行,否则后一次迭代会移除前一次写入的 Key。
删除用户时也要区分“撤销登录”与“删除数据”。state: absent 只是移除账号,搭配 remove: true 还会删除家目录等文件。生产变更应先保证仍有可用的管理通道,再收紧 Key 或移除账号;验证成功后,账号、组和授权 Key 才真正成为一致且可审计的访问基线。