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

Ansible/AWX委派至localhost任务失败,求助如何强制使用SSH执行

问题:如何强制Ansible委派任务使用SSH连接localhost?

场景与问题详情

当前场景:Ansible角色在Windows主机Server1上执行,localhost为AWX服务器(Linux机器)。需在Windows主机执行流程中委派任务至localhost,但执行任务时出现异常。

相关代码与配置

任务代码

- name: execute localhost
  command: echo "Hello, localhost!"
  delegate_to: localhost
  connection: local

Inventory配置

[MyAPP]
Server1

[Windows:children]
MyApp

[WINDOWS:vars]
ansible_user=#{winrm_ansible_user}#
ansible_password=#{winrm_ansible_password}#
ansible_port=5985
ansible_connection=winrm
ansible_winrm_transport=basic

调用角色的main.yml

- hosts: all
  become: false
  roles:
    - role: pool_recycle

角色示例代码

- name: Get win local IP
  ansible.windows.win_powershell:
    script: |
      (Test-Connection -ComputerName $env:ComputerName  -Count 1).IPV4Address.ToString()
  register: get_ip

- name: execute localhost
  command: echo "Hello, localhost!"
  delegate_to: localhost
  connection: local

报错信息

fatal: [WINDOWS_SERVER_01 -> localhost]: UNREACHABLE! => {"changed": false, "msg": "basic: HTTPConnectionPool(host='localhost', port=5985): Max retries exceeded with url: /wsman (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7fdb9e8acac0>: Failed to establish a new connection: [Errno 111] Connection refused'))", "unreachable": true}

解决方案

问题根源是Inventory中为Windows组设置的ansible_connection=winrm变量会被继承到委派任务,导致Ansible尝试用WinRM连接localhost(而localhost是Linux机器,未监听WinRM的5985端口)。以下几种方法可解决:

方法1:在委派任务中显式覆盖连接变量

直接在任务内指定SSH连接所需变量,覆盖Windows组的默认配置:

- name: execute localhost
  command: echo "Hello, localhost!"
  delegate_to: localhost
  vars:
    ansible_connection: ssh
    ansible_port: 22  # 根据AWX服务器实际SSH端口调整,默认22
    ansible_user: "{{ awx_ssh_user }}"  # 替换为AWX服务器的SSH用户名

方法2:在Inventory中为localhost单独配置

在Inventory文件中添加localhost的专属配置,确保它优先使用SSH连接:

[localhost]
localhost ansible_connection=ssh ansible_port=22 ansible_user=your_awx_user

[MyAPP]
Server1

[Windows:children]
MyApp

[WINDOWS:vars]
ansible_user=#{winrm_ansible_user}#
ansible_password=#{winrm_ansible_password}#
ansible_port=5985
ansible_connection=winrm
ansible_winrm_transport=basic

此后所有委派到localhost的任务都会自动使用该配置,无需重复设置。

方法3:替换connection: local为connection: ssh

原任务中的connection: local可能与AWX执行环境冲突,直接指定使用SSH连接:

- name: execute localhost
  command: echo "Hello, localhost!"
  delegate_to: localhost
  connection: ssh
  vars:
    ansible_user: "{{ awx_ssh_user }}"

说明

方法1灵活性最高,仅针对单个任务生效;方法2适合长期固定使用localhost的场景,一次性配置即可。可根据实际需求选择。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 07:03:18