You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ansible执行sudo命令时报错‘Missing sudo password’求助

问题描述

我有一个简易Ansible Playbook:

---
- name: test
  hosts: all
  tasks:
     - name: testing
       shell: /usr/bin/whoami
       register: testing

     - name: show the result
       debug:
          msg: "{{ testing.stdout }}"

用user1执行这个Playbook时,能得到预期输出user1。

但我需要通过root用户运行shell命令(类似sudo whoami的效果),于是修改了Playbook:

---
- name: test
  hosts: all
  tasks:
     - name: testing
       shell: /usr/bin/whoami
       become: true
       register: testing

     - name: show the result
       debug:
          msg: "{{ testing.stdout }}"

修改后持续报错:

fatal: [xxxxxxxxx]: FAILED! => {
    "msg": "Missing sudo password"
}

为了允许user1以sudo切换到root执行命令,我已在sudoers文件中添加了以下条目:

user1 ALL=(ALL:ALL) /usr/bin/whoami

同时,为避免输入user1的密码,我在本地ansible.cfg中添加了配置:

[privilege_escalation]
become_ask_pass=False

但依旧出现上述错误,请问遗漏了什么配置?

解决方法
  • sudoers条目缺少免密参数:当前的sudoers配置仅允许user1执行指定命令,但仍需输入密码。要实现免密sudo,必须在条目里加上NOPASSWD:,修改后的sudoers条目应为:

    user1 ALL=(ALL:ALL) NOPASSWD: /usr/bin/whoami
    

    注意:务必用visudo命令编辑sudoers文件,避免语法错误导致sudo功能失效。

  • 验证sudo配置有效性:先在目标主机上用user1直接执行sudo /usr/bin/whoami,如果无需输入密码就返回root,说明sudo配置没问题;如果仍要求输入密码,需检查sudoers语法或重启sshd服务。

  • 确认Ansible配置逻辑:become_ask_pass=False只是让Ansible不主动询问sudo密码,但前提是sudo本身已经允许免密执行对应命令,这一步你已配置,只要sudo设置生效即可正常运行。

内容的提问来源于stack exchange,提问作者caveman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 17:56:06