Execution
Date 22 Jul 2025 11:24:10 +0100
Duration 00:00:04.08
Controller ssh-gw-4.layershift.com
User root
Versions
Ansible 2.16.11
ara 1.7.2 / 1.7.2
Python 3.10.10
Summary
1 Hosts
5 Tasks
5 Results
1 Plays
1 Files
0 Records

File: /home/ssh-gateway/ansible/kuly/get_mac_addresses.yaml

---
- name: Get MAC of eno1 (or first physical NIC) and save to file
  hosts: all
  gather_facts: yes
  vars:
    output_file: "/tmp/ansible_host_macs.txt"  # All results go here

  tasks:
    - name: Gather facts (interfaces)
      ansible.builtin.setup:
        filter: "ansible_interfaces"

    - name: Filter physical interfaces (en*, eth*, em*, ens*, eno*, enp*)
      ansible.builtin.set_fact:
        physical_interfaces: >-
          {{
            ansible_facts.interfaces
            | select('match', '^(en|eth|em|ens|eno|enp)')
            | map('extract', ansible_facts)
            | selectattr('macaddress', 'defined')
            | list
          }}

    - name: Debug filtered interfaces
      ansible.builtin.debug:
        msg: "Physical interfaces: {{ physical_interfaces | map(attribute='device') | list }}"

    - name: Assert at least one physical interface found
      ansible.builtin.assert:
        that:
          - "physical_interfaces | length > 0"
        fail_msg: "No physical network interfaces found"
        success_msg: "Found physical interfaces"

    - name: Try to find eno1 specifically
      ansible.builtin.set_fact:
        target_interface: >-
          {{
            physical_interfaces
            | selectattr('device', 'match', '^eno1$')
            | first(False)
          }}

    - name: Fall back to first physical interface if eno1 not found
      ansible.builtin.set_fact:
        target_interface: >-
          {{
            (target_interface is defined and target_interface)
            or physical_interfaces[0]
          }}

    - name: Build line for output
      ansible.builtin.set_fact:
        output_line: "{{ inventory_hostname }} - {{ target_interface.device }} - {{ target_interface.macaddress }}"

    - name: Append result to shared file on control node
      ansible.builtin.copy:
        content: "{{ output_line }}\n"
        dest: "{{ output_file }}"
        mode: 'a'  # append mode
      delegate_to: localhost
      run_once: true