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

Ansible无法连接内存清单中定义的Azure Windows主机

解决Ansible尝试用SSH连接Windows主机的问题

你的问题核心很明确:Ansible默认对Linux主机使用SSH连接,但管理Windows主机必须用WinRM协议,如果不明确指定连接方式,Ansible就会用默认的SSH去连Windows,自然会失败。下面是完整的解决方案,包含调整后的Playbook和关键配置说明:

调整后的完整Playbook

这个Playbook会完成创建Azure Windows VM、将其加入内存Inventory、并通过WinRM连接执行测试任务的全流程:

- name: 创建并配置Windows VM
  hosts: localhost
  vars:
    nicName: "Blue-xxxx"
    vmName: "Blue-xxxx"
    vmPubIp: "51.141.x.x"
    resource_group: "AnsibleVMxxx"
    admin_username: "your-admin-account"
    admin_password: "your-secure-password"
  tasks:
    - name: 创建Windows虚拟机
      azure_rm_virtualmachine:
        resource_group: "{{ resource_group }}"
        name: "{{ vmName }}"
        vm_size: Standard_B2ms
        storage_account: vmstoragedisksxxx
        admin_username: "{{ admin_username }}"
        admin_password: "{{ admin_password }}"
        os_type: Windows
        image:
          offer: WindowsServer
          publisher: MicrosoftWindowsServer
          sku: 2019-Datacenter
          version: latest
        network_interfaces: "{{ nicName }}"
        # 确保Azure VM开启WinRM HTTPS服务
        winrm:
          protocol: https
          port: 5986

    - name: 将Windows VM添加到内存Inventory
      add_host:
        name: "{{ vmPubIp }}"
        groups: windows_hosts
        # 关键:指定WinRM连接参数,替代默认的SSH
        ansible_connection: winrm
        ansible_winrm_transport: ntlm
        ansible_winrm_server_cert_validation: ignore  # 测试环境可用,生产建议配置可信证书
        ansible_user: "{{ admin_username }}"
        ansible_password: "{{ admin_password }}"
        ansible_port: 5986

- name: 在Windows主机上执行测试任务
  hosts: windows_hosts
  tasks:
    - name: 验证WinRM连接可用性
      win_ping:

关键配置说明

  1. 强制指定WinRM连接

    • ansible_connection: winrm:这是最核心的配置,直接告诉Ansible用WinRM而非SSH连接该主机
    • ansible_winrm_transport: ntlm:Windows常用的认证方式,适配Azure Windows VM的默认设置
    • ansible_winrm_server_cert_validation: ignore:Azure默认给WinRM用自签名证书,测试环境可以临时忽略验证;生产环境建议上传可信证书并改为validate
  2. Azure VM侧的必要配置

    • 创建VM时必须指定os_type: Windows,让Ansible模块正确配置Windows相关服务
    • 确保Azure网络安全组(NSG)开放5986端口(WinRM HTTPS)的入站流量,否则Ansible无法建立连接
    • 管理员账号密码要符合Windows的复杂度要求,避免创建VM时失败
  3. 内存Inventory的动态添加

    • 通过add_host模块将新VM的公网IP加入临时Inventory,并直接附加连接参数,后续Play针对windows_hosts组执行时就会自动使用WinRM

常见排查点

  • 检查Azure NSG的入站规则,确认WinRM端口(5986)未被拦截
  • 验证Windows VM的管理员账号密码是否正确,且账号拥有管理员权限
  • 如果使用HTTPS连接,可先尝试用ansible_winrm_server_cert_validation: ignore排除证书问题,再逐步配置可信证书

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:00:30