Search code examples
linuxansibleansible-facts

Ansible - Is there a way to get access to USB devices?


I'm building a playbook for my Raspberry Pi 4 and I have a podman container that needs to access the printer (in /dev/bus/usb/XXX/YYY) device.

I have a task that does the job, but it uses the shell module, which is not recommended:

- name: "ScannerJS - Detect printer's USB bus"
  block:
    - name: "ScannerJS - Detect printer's USB bus"
      ansible.builtin.shell: |
        set -e -o pipefail
        lsusb | grep Epson | awk '{print "/dev/bus/usb/"$2"/"substr($4, 1, length($4)-1)}'
      args:
        executable: /bin/bash
      register: scUSBBus
      failed_when: scUSBBus.stdout | regex_search("^\/dev\/bus\/usb\/(\\d{3})\/(\\d{3})$") is none

    - name: "ScannerJS - assert the device path exists"
      ansible.builtin.stat:
        path: "{{ scUSBBus.stdout }}"
      register: scUSBBusStat
      failed_when: scUSBBusStat.stat.exists is not true

Is there a cleaner way to obtain the bus/usb for my printer ?

I tried searching in the facts, but there is nothing about USB devices and I can't find any module related to USB devices.


Solution

  • For anyone reading this later on, there is now a facts module to collect information about USB devices.

    You can use it like this:

    - name: Get information about USB devices
      community.general.usb_facts:
    
    - name: Print information about USB devices
      ansible.builtin.debug:
        msg: "On bus {{ item.bus }} device {{ item.device }} with id {{ item.id }} is {{ item.name }}"
      loop: "{{ ansible_facts.usb_devices }}"