在 Ansible 中,尝试在 Windows 主机上使用 sudo 权限提升时,可能会遇到“PowerShell shell family is incompatible with the sudo become plugin”错误。这是因为 Windows 主机使用的是 PowerShell,而 sudo 是基于 Unix 的权限提升工具,不适用于 Windows 环境。

错误示例

以下是一个会导致“PowerShell shell family is incompatible with the sudo become plugin”错误的 Ansible Playbook 示例:

---
- name: win_reboot module demo
  hosts: all
  become: true
  tasks:
    - name: reboot host(s)
      ansible.windows.win_reboot:

错误信息

运行上述 Playbook 时,可能会遇到以下错误:

$ ansible-playbook -i win/inventory troubleshooting/incompatiblesudo_error.yml
PLAY [win_reboot module demo] **************************************************
TASK [Gathering Facts] **************************************************
fatal: [WindowsServer]: FAILED! => {"msg": "The powershell shell family is incompatible with the sudo become plugin"}
PLAY RECAP *******************************************************************
WindowsServer              : ok=0    changed=0    unreachable=0    failed=1    skipped=0    rescued=0    ignored=0

问题原因

  1. 不兼容的权限提升方法:sudo 是基于 Unix 的权限提升工具,而 Windows 主机使用的是 PowerShell,不支持 sudo。
  2. 错误的 become 配置:在 Windows 主机上,不应使用 become: true,因为 Windows 不支持基于 Unix 的权限提升。

解决方法

  1. 禁用 become:在 Windows 主机上,将 become 设置为 false,因为 Windows 不需要使用 sudo 来提升权限。
  2. 使用正确的权限提升方法:如果需要在 Windows 上进行权限提升,可以使用 runas 或其他适用于 Windows 的方法。

修复后的 Playbook 如下所示:

---
- name: win_reboot module demo
  hosts: all
  become: false
  tasks:
    - name: reboot host(s)
      ansible.windows.win_reboot:

修复步骤

  1. 禁用 become:将 become 设置为 false。
  2. 重新运行 Playbook:验证修复是否有效。

验证修复

修复问题后,重新运行 Playbook:

$ ansible-playbook -i win/inventory troubleshooting/incompatiblesudo_fix.yml
PLAY [win_reboot module demo] **************************************************
TASK [Gathering Facts] **************************************************
ok: [WindowsServer]
TASK [reboot host(s)] ****************************************************
changed: [WindowsServer]
PLAY RECAP *******************************************************************
WindowsServer              : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

总结

Ansible 中的“PowerShell shell family is incompatible with the sudo become plugin”错误通常是由于以下原因导致的:

  1. 不兼容的权限提升方法:sudo 是基于 Unix 的权限提升工具,不适用于 Windows。
  2. 错误的 become 配置:在 Windows 主机上,不应使用 become: true。

通过以下步骤可以有效解决这种错误:

  1. 禁用 become:在 Windows 主机上,将 become 设置为 false。
  2. 使用正确的权限提升方法:如果需要在 Windows 上进行权限提升,可以使用 runas 或其他适用于 Windows 的方法。
  3. 重新运行 Playbook:验证修复是否有效。

如果问题仍未解决,可以参考 Ansible 的 官方文档或社区支持获取更多帮助。