How to detect if host is WSL in Ansible playbook?

95 Views Asked by At

In Ansible, I need to run some roles only if the host is a WSL host.

How to detect that? I am looking for a form of:

- name: "Run only in WSL"
  when: # what to put here?
  # task definition

What to put in the when section? I am looking for a way to detect that automatically, NOT to configure a variable on my host in the inventory.

2

There are 2 best solutions below

0
U880D On BEST ANSWER

Just gather Ansible facts. There is no need for command, shell, register and parse stdout at all. From a minimal example playbook

---
- hosts: test
  become: true

  gather_facts: true
  gather_subset:
    - "!all"
    - "min"
  # - "hardware"

  tasks:

  - name: Show Facts
    debug:
      msg: "{{ ansible_facts }}"

the output result will already contain the requested information

    os_family: RedHat
    product_name: VMware7,1
    system: Linux
    system_vendor: VMware, Inc.
    virtualization_role: guest
    virtualization_type: VMware

or

    os_family: RedHat
    product_name: Virtual Machine
    product_version: Hyper-V UEFI Release v1.0
    system: Linux
    system_vendor: Microsoft Corporation

or

    os_family: RedHat
    product_name: HVM domU
    system: Linux
    system_vendor: Xen
    virtualization_role: guest
    virtualization_type: xen

It also contains the ansible_facts.kernel versions

3.10.0-1160.108.1.el7.x86_64
4.18.0-513.11.1.el8_9.x86_64
5.14.0-362.18.1.el9_3.x86_64

With this information Conditionals based on ansible_facts is trivial. Like in

when: ansible_facts['os_family'] == "Debian" and ansible_facts['system_vendor'] == "Microsoft Corporation"
1
bazza On

The command uname -a reports something like:

Linux DESKTOP 5.15.133.1-microsoft-standard-WSL2 #1 SMP Thu Oct 5 21:02:42 UTC 2023 x86_64 x86_64 x86_64 GNU/Linux

Could be OK for what you're looking for! This was for Ubuntu 22.04 installed in WSL 2. I'm not sure how this would fit in with Ansible, but there's probably a way to make the call and filter the result for WSL2.