基础设施即代码 / 系统课时
使用 Become 控制权限提升
使用 Become 控制权限提升
Ansible 不需要让所有自动化都以 root 登录。更稳妥的做法是用普通账号建立 SSH 连接,仅在安装软件、写系统目录或管理服务等确实需要管理员权限的任务上启用 become。
学习目标
- 区分 SSH 登录身份与
become之后的目标身份。 - 在任务级精确启用
become,避免整套 Play 长期处于高权限状态。 - 使用交互式 sudo 密码并验证哪些任务实际发生了权限提升。
理解连接身份与提升身份
ansible_user 决定 Ansible 先以谁连接远端主机;become_user 决定权限提升后切换到谁,常见目标是 root。只有 become: true 的任务才会触发提权,单独设置 become_method 或 become_user 并不会自动提升权限。
默认的 Linux 场景通常使用 sudo 作为 become_method。如果远端 sudo 策略要求密码,可以运行 Playbook 时加 --ask-become-pass,避免把 sudo 密码直接写进清单或普通变量文件。
只给必要任务启用 Become
下面的清单让 Ansible 始终以普通账号 ops 建立连接。Playbook 在 Play 级明确保持 become: false,然后只让安装软件和写入 /etc 的任务提权。
[app]
app01 ansible_host=<IP>
app02 ansible_host=<IP>
[app:vars]
ansible_user=ops- name: Apply privileged changes selectively
hosts: app
gather_facts: false
become: false
become_method: sudo
become_user: root
tasks:
- name: Show normal connection identity
ansible.builtin.command: id -un
register: normal_identity
changed_when: false
- name: Print normal connection identity
ansible.builtin.debug:
var: normal_identity.stdout
- name: Install Nginx
become: true
ansible.builtin.apt:
name: nginx
state: present
update_cache: true
- name: Ensure Nginx is started
become: true
ansible.builtin.systemd_service:
name: nginx
state: started
enabled: true
- name: Write a root-owned marker
become: true
ansible.builtin.copy:
dest: /etc/ansible-managed.conf
owner: root
group: root
mode: "0644"
content: |
managed_by=ansible
- name: Check Nginx without privilege escalation
ansible.builtin.uri:
url: http://127.0.0.1/
status_code: 200
return_content: false这里的身份查询和 HTTP 检查都以 ops 执行;只有安装软件、管理服务与写 /etc/ansible-managed.conf 的任务会切换到 root。这样既满足系统变更需要,也减少了高权限任务的覆盖范围。
执行并验证提升边界
如果 sudo 需要密码,使用交互式提示执行;若已经为自动化账号配置了受限 NOPASSWD 规则,则可以省略该参数。
ansible-playbook -i inventory.ini become.yml --ask-become-pass预期输出
BECOME password:
TASK [Show normal connection identity] ******************************
ok: [app01]
ok: [app02]
TASK [Print normal connection identity] *****************************
ok: [app01] => {
"normal_identity.stdout": "ops"
}
ok: [app02] => {
"normal_identity.stdout": "ops"
}
TASK [Install Nginx] ***********************************************
ok: [app01]
ok: [app02]
TASK [Ensure Nginx is started] *************************************
ok: [app01]
ok: [app02]
TASK [Write a root-owned marker] ***********************************
changed: [app01]
changed: [app02]
TASK [Check Nginx without privilege escalation] ********************
ok: [app01]
ok: [app02]软件已经存在时 Install Nginx 可能显示 ok 而不是 changed;文件首次创建时通常是 changed。验收重点是普通任务仍显示连接身份 ops,而需要 root 权限的软件安装、服务管理和系统文件写入都能成功完成。
选择任务级、块级还是 Play 级
只在少量任务需要管理员权限时,优先使用任务级 become: true。若一组连续任务共同需要同一种权限,可以在 block 上启用,减少重复配置。只有当几乎整个 Play 都必须以管理员身份执行时,才适合在 Play 级开启。
如果任务出现 Missing sudo password,说明提权路径需要密码却没有提供;如果出现 is not in the sudoers file 或 not allowed to execute,则应修正远端 sudoers,而不是改成 root 直接 SSH 登录。把连接账号保持低权限,再按任务边界临时提升,才能让 Playbook 的权限需求清晰、可审计,也更容易发现不必要的高权限操作。