Saturday, November 27, 2021

 How to find MAC addresses using Ansible

There are many ways to get MAC addresses of the remote host in an array using Ansible. I found out that this was the best way. I am removing the colons from the address while adding to the array. But you do not have to do that part if you do not need to.

The code below skips interfaces which does not have MAC addresses:

- name: Find MAC addresses
  ansible.builtin.set_fact:
    host_mac_addresses: "{{ host_mac_addresses | default([]) }} +
      [
        {% if ansible_facts[item].macaddress != 'unknown' %}
             '{{ ansible_facts[item].macaddress | replace(':','') }}'
        {% endif %}
      ]"
  with_items:
    - "{{ ansible_interfaces }}" 
This loops through the interfaces and collects MAC addresses which are not `unknown`