Ansible中使用delegate_to或local_action执行本地ping失败求助
问题描述
我希望在Ansible中使用delegate_to或local_action从localhost执行ping操作,但功能无法正常工作。我已尝试两种方式,对应的playbook代码如下:
--- - name: sampleplaybook hosts: all become: yes become_user: root tasks: - name: ping check #shell: ping -c 1 -w 2 {{ ansible_host }} local_action: ping -c 1 -w 2 {{ ansible_host }} #delegate_to: localhost ignore_errors: true
但运行该playbook时,系统仍尝试建立SSH连接并失败,请问有什么解决办法?
运行时的报错信息如下:
ansible-playbook sample.yml [WARNING]: 组名称中发现无效字符但未替换,使用 -vvvv 查看详情
PLAY [sampleplaybook]TASK [Gathering Facts]
************************************************************************************************************************************** 无法确认主机 '(IP#)' 的真实性。ECDSA密钥指纹为 SHA256:............................ ECDSA密钥指纹为 MD5:........................... 确定要继续连接吗(yes/no)? 无法确认主机 '(IP#)' 的真实性。
1. 禁用默认的Gathering Facts任务
报错来自Gathering Facts环节——Ansible默认会在play启动时连接远程主机收集系统信息,这和你后续的本地ping操作无关。要阻止不必要的SSH连接,需在play中添加gather_facts: no:
--- - name: sampleplaybook hosts: all gather_facts: no # 禁用默认远程信息收集 become: yes become_user: root tasks: - name: ping check local_action: shell ping -c 1 -w 2 {{ ansible_host }} ignore_errors: true
2. 修正local_action的语法
你之前的local_action: ping -c 1 -w 2 {{ ansible_host }}存在错误:这里的ping会被Ansible识别为内置的ping模块,而非系统的ping命令。要执行系统命令,必须指定shell或command模块:
- 正确的local_action写法:
或local_action: shell ping -c 1 -w 2 {{ ansible_host }}local_action: command ping -c 1 -w 2 {{ ansible_host }}
3. delegate_to的正确用法
如果倾向使用delegate_to,写法如下(同样需要禁用gather_facts):
--- - name: sampleplaybook hosts: all gather_facts: no become: yes become_user: root tasks: - name: ping check shell: ping -c 1 -w 2 {{ ansible_host }} delegate_to: localhost ignore_errors: true
额外提示
- 关于组名称无效字符的警告,可执行
ansible-playbook sample.yml -vvvv查看具体问题组名,修正inventory文件中的组名格式即可。
内容的提问来源于stack exchange,提问作者vinWin

