Execution
Date 22 Jul 2025 12:59:54 +0100
Duration 00:00:05.65
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
10 Tasks
10 Results
1 Plays
1 Files
0 Records

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

---
- name: Gather main physical interface and MAC address
  hosts: all
  become: true
  gather_facts: false

  vars:
    # List of ignored interface prefixes
    ignored_prefixes:
      - "lo"
      - "docker"
      - "br-"
      - "veth"
      - "virbr"
      - "wl"
      - "wlan"
      - "tun"
      - "tap"

  tasks:
    - name: Get default route interface
      command: ip route show default
      register: default_route
      changed_when: false

    - name: Extract main interface from default route
      set_fact:
        main_interface: >-
          {{
            (default_route.stdout.split('dev')[1].split()[0])
            if 'dev' in default_route.stdout else ''
          }}
      when: default_route.stdout != ""

    - name: Fail if no default interface found
      fail:
        msg: "No default route found. Unable to determine main interface."
      when: default_route.stdout == "" or ("dev" not in default_route.stdout)

    - name: Check if main interface matches ignored patterns
      set_fact:
        is_ignored: >-
          {%- set result = [] -%}
          {%- for prefix in ignored_prefixes -%}
          {%- if main_interface.startswith(prefix) -%}
          {%- set _ = result.append('true') -%}
          {%- endif -%}
          {%- endfor -%}
          {{ 'true' if 'true' in result else 'false' }}

    - name: Fail if main interface is virtual/ignored
      fail:
        msg: "Main interface {{ main_interface }} is virtual or wireless and is ignored."
      when: is_ignored == 'true'

    - name: Validate main interface exists and is physical
      stat:
        path: "/sys/class/net/{{ main_interface }}"
      register: interface_stat
      failed_when: not interface_stat.stat.exists

    - name: Get MAC address using /sys/class/net/
      command: "cat /sys/class/net/{{ main_interface }}/address"
      register: mac_result
      changed_when: false

    - name: Set MAC address fact
      set_fact:
        mac_address: "{{ mac_result.stdout }}"

    - name: Write interface and MAC to file
      copy:
        content: |
          # Main Network Interface Information
          interface={{ main_interface }}
          mac_address={{ mac_address }}
        dest: /etc/main_interface_info.txt
        owner: root
        group: root
        mode: '0644'
      notify: Print completion message

  handlers:
    - name: Print completion message
      debug:
        msg: "Interface {{ main_interface }} with MAC {{ mac_address }} written to /etc/main_interface_info.txt"