Execution
Date 22 Jul 2025 13:19:24 +0100
Duration 00:00:02.31
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 address of main physical interface
  hosts: all
  gather_facts: no
  vars:
    output_file: "./mac_addresses.txt"

  tasks:
    - name: Get default interface
      command: ip route get 1.1.1.1
      register: route_output

    - name: Extract interface name from default route
      set_fact:
        default_interface: "{{ route_output.stdout | regex_search('dev\\s+(\\S+)', '\\1') }}"

    - name: Check if interface is a bridge
      command: nmcli -t -f TYPE device show {{ default_interface }}
      register: iface_type
      failed_when: false
      changed_when: false

    - name: Get bridge's underlying interface if default is a bridge
      command: nmcli -t -f GENERAL.CONNECTION device show {{ default_interface }}
      when: "'bridge' in iface_type.stdout"
      register: bridge_conn

    - name: Get slave interfaces from bridge connection
      command: nmcli -t -f SLAVE connection show "{{ bridge_conn.stdout.split(':')[-1] }}"
      when: bridge_conn is defined and bridge_conn.stdout != ""
      register: bridge_slaves

    - name: Set physical interface if bridge
      set_fact:
        physical_interface: "{{ bridge_slaves.stdout_lines[0] }}"
      when: bridge_slaves is defined and bridge_slaves.stdout_lines | length > 0

    - name: Set physical interface if not a bridge
      set_fact:
        physical_interface: "{{ default_interface }}"
      when: physical_interface is not defined

    - name: Get MAC address of the physical interface
      command: cat /sys/class/net/{{ physical_interface }}/address
      register: mac_address_output

    - name: Save MAC address to local file
      delegate_to: localhost
      run_once: true
      copy:
        content: |
          Host: {{ inventory_hostname }}
          Interface: {{ physical_interface }}
          MAC Address: {{ mac_address_output.stdout }}
        dest: "{{ output_file }}"
        mode: '0644'
        force: no  # append manually in the next step

    - name: Append MAC address to local file (if multiple hosts)
      delegate_to: localhost
      lineinfile:
        path: "{{ output_file }}"
        line: "Host: {{ inventory_hostname }}, Interface: {{ physical_interface }}, MAC: {{ mac_address_output.stdout }}"
        create: yes
        insertafter: EOF
      when: ansible_play_hosts_all | length > 1