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

Ansible含become: true的任务执行卡住问题求助

Ansible become: true 任务卡住无响应的解决方法

运行Ansible剧本时,带有become: true的任务会卡住,像是在等待用户输入。试过用--ask-become-pass参数,或者通过--extra-vars传入ansible_become_pass变量,问题依旧存在。

任务代码示例

- name: copy the ansible-am project cron to /etc/cron.d/
  become: true
  timeout: 5
  ignore_errors: true
  ansible.builtin.shell:
    cmd: |
      cp {{ ansible_am_cron_absfilepath }} {{ root_ansible_am_cron_filepath }}

  register: task1_result
  failed_when: task1_result.rc != 0

剧本调用命令示例

ansible-playbook -vvvvvv --extra-vars='ansible_become_pass=mypassword' playbooks/my_playbook.yml

ansible-playbook -vvvvvv --ask-become-pass playbooks/my_playbook.yml

错误日志信息

提升日志级别后发现密码并未传入,任务超时终止:

Check if the string is present in the file...    
Using module file /home/my_path/ansible-venv/lib/python3.7/site-packages/ansible/modules/command.py    
Pipelining is enabled.
<127.0.0.1> ESTABLISH LOCAL CONNECTION FOR USER: my_user
<127.0.0.1> EXEC /bin/sh -c 'sudo -H -S  -p "[sudo via ansible, key=eusofmetqrwweecthgwo] password:" -u root /bin/sh -c '"'"'echo BECOME-SUCCESS-eusofmetqrwweecthgwo ; /home/my_path/ansible-venv/bin/python3.7'"'"' && sleep 0'
  localhost failed: {
    "changed": false,
    "msg": "The shell action failed to execute in the expected time frame (5) and was terminated"
}

解决方法

  • 检查sudoers配置
    确保执行剧本的用户在sudoers文件中有免密码权限,或配置无需tty的选项。用visudo编辑/etc/sudoers:

    my_user ALL=(ALL) NOPASSWD: ALL
    

    若不需要全权限,可指定具体命令:

    my_user ALL=(ALL) NOPASSWD: /bin/cp
    

    若系统默认要求sudo需要tty,添加Defaults !requiretty(针对该用户或全局)。

  • 验证become变量优先级
    Ansible变量有优先级,确保ansible_become_pass未被其他配置覆盖,可在任务中显式指定:

    - name: copy cron file
      become: true
      become_pass: "{{ ansible_become_pass }}"
      ansible.builtin.shell:
        cmd: cp {{ ansible_am_cron_absfilepath }} {{ root_ansible_am_cron_filepath }}
    
  • 关闭pipelining尝试
    日志显示pipelining已启用,部分环境下该特性会导致sudo交互异常。在ansible.cfg中关闭:

    [defaults]
    pipelining = False
    

    或针对单个任务设置:

    - name: copy cron file
      become: true
      pipelining: false
      ansible.builtin.shell: ...
    
  • 改用copy模块替代shell命令
    避免用shell执行cp,直接使用Ansible内置的copy模块,更可靠且符合最佳实践:

    - name: copy the ansible-am project cron to /etc/cron.d/
      become: true
      timeout: 5
      ignore_errors: true
      ansible.builtin.copy:
        src: "{{ ansible_am_cron_absfilepath }}"
        dest: "{{ root_ansible_am_cron_filepath }}"
        remote_src: true
      register: task1_result
      failed_when: task1_result.failed
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 03:43:17