如何为Ansible Playbook中远程主机的Shell任务设置超时?
解决Ansible远程Shell任务及SSH连接超时问题
你的问题核心是混淆了async的用途——它是用来实现异步任务执行(让Ansible不用一直等待任务完成),而非控制远程SSH连接或命令执行的超时时间。针对你的需求,以下是几种直接有效的解决方式:
1. 控制SSH连接超时
在inventory文件或playbook中设置ansible_ssh_timeout参数,限制Ansible与远程主机建立SSH连接的最长等待时间:
在inventory中配置(针对所有主机或单台主机):
[all] your_host ansible_ssh_timeout=10或者在playbook中直接定义:
--- - name: Check timeout error hosts: all ignore_errors: yes gather_facts: false vars: ansible_ssh_timeout: 10 # SSH连接超时设为10秒 tasks: - name: test if server is connecting within 10 seconds become: True shell: id register: id_result
2. 控制提权(become)超时
你预期的错误是提权超时,可通过become_timeout参数限制等待sudo/提权提示的时间:
--- - name: Check timeout error hosts: all ignore_errors: yes gather_facts: false vars: ansible_ssh_timeout: 10 become_timeout: 10 # 提权超时设为10秒 tasks: - name: test privilege escalation timeout become: True shell: id register: id_result
当提权等待超过10秒时,会触发你预期的类似错误:{"msg": "Timeout (10s) waiting for privilege escalation prompt: "}
3. 给远程Shell命令本身加超时
如果需要限制命令执行的时间(而非连接/提权阶段),可以用系统自带的timeout命令包裹目标命令:
- name: test command execution timeout become: True shell: timeout 10s id register: id_result
这样远程主机上的id命令如果运行超过10秒,会被强制终止,Ansible会捕获到命令非零退出码。
内容的提问来源于stack exchange,提问作者gjvignesh
相关产品推荐
相关产品推荐

