如何在Ansible中判断远程主机是Windows还是Linux?

k7fdbhmy  于 2022-12-27  发布在  Windows
关注(0)|答案(2)|浏览(204)

我知道Ansible运行在Linux上,但如果WinRm被用于远程管理Windows系统,有没有办法我可以告诉(检测)远程主机是Windows而不是Linux?

yzxexxkh

yzxexxkh1#

是的,只需读取ansible_system变量。在Linux系统上,它将包含“Linux”,在Windows上,它将包含“Win32NT”。
您还可以检查其他“事实”以获得更高的精度。您可以在Ansible documentation中看到这些事实的示例

nom7f22z

nom7f22z2#

不确定这是否是你想要的,但是这给了你一种使用单一角色来完成windows和linux任务的方法
假设你有一个windows和一个linux服务器配置正确,可以接收ansible命令,在你的inventory中你可以有以下内容:

[windows]
10.0.0.2
[linux]
10.100.0.2

然后创建一个文件group_vars/windows.yml(group_vars是一个文件夹,windows. yml是该文件-名称必须与配置中的组匹配):

ansible_connection: winrm
# The option below is if you have not setup certs for winrm
ansible_winrm_server_cert_validation: ignore
ansible_python_interpreter: /usr/bin/python3

ansible_user: ADMIN     # <- replace with your configured user
ansible_password: PASS  # <- replace with your configured pass

如果使用group_vars文件夹,还可以创建all.ymllinux.yml以添加更多变量。
Ansible查看group_vars文件夹中的文件名,并将其应用于清单中的组。
或者您可以使用[windows:vars]将变量存储在库存中
然后,在您的角色中,您可以拥有以下内容:

.
├── ...
└── tasks
    ├── linux.yml
    ├── main.yml
    └── win32nt.yml

您的main.yml可以是这样的:

- name: Do whatever
  include_tasks: '{{ansible_system|lower}}.yml'

如果要更具体,可以使用:ansible_os_family,它将为您提供:"Windows"、"Debian"、"RedHat"等
这些都是基本的步骤,但应该给你一个起点,你可以改进它为您的需要。
例如,如果您有一个安装Java JDK的角色,并且您和有一个用于安装Java JDK的角色,则这一点非常有用。
参考:
https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_vars_facts.html https://docs.ansible.com/ansible/latest/inventory_guide/intro_inventory.html#hosts-in-multiple-groups
Guide Winrm
Windows setup

相关问题