0

I'm sorry if this is a duplicate - I've found some similar questions online but could not quite get any to work.

I'm trying to create a playbook that finds all available network intefaces on a server, and then loop over them and extracts each interface's MAC address. I'd then like Ansible to print a message to the user.

Finding all interfaces was fairly straightforward:

  - name: Find NICs
    ansible.builtin.debug:
      msg: Found network interface {{ item }}
    with_items:
    - "{{ ansible_interfaces }}"

This outputs the interface's name in the OS - strings such as ens123, enp456 and so forth.

Finding the MAC was also quite simple:

  - name: Find NICs MAC
    ansible.builtin.debug:
      msg: "{{ ansible_facts[' {{ item }}']['macaddress'] }}"
    with_items:
    - "{{ ansible_interfaces }}"

Now, the {{ item }} variable is meant to be the found interface name (ex: ens123). If I replace it with the actual name every time, the command works.

I'm also aware that this is likely a simple task via shell, but it is meant to work across a wide range of systems and so I'm trying an Ansible-only solution.

I've pored over the documentation and could not figure it out - any assistance would be greatly appreciated.

Thanks!

4
  • 2
    Try this msg: "{{ ansible_facts[item]['macaddress']|default(None) }}" May 2, 2021 at 17:09
  • 1
  • Thank you both! Vladimir, your answer worked perfectly. Zeitounator - That seems to be exactly the doc I'm looking for. Thanks!
    – dkd6
    May 3, 2021 at 11:15
  • 1
    I rolled back your tagging of the question as "(solved)" in the title. If the issue has a solution, please post an answer below. You then have the option to accept that answer (or any other answer that happens to appear). When a question has an accepted answer, the issue is properly marked as resolved. You are definitely allowed to answer your own questions: unix.stackexchange.com/help/self-answer
    – Kusalananda
    May 3, 2021 at 11:28

1 Answer 1

0

The solution, as Vladimir suggested above, was the following:

msg: "{{ ansible_facts[item]['macaddress']|default(None) }}"

Whole block:

  - name: Find NICs MAC
    ansible.builtin.debug:
      msg: " interface {{ item }}'s MAC is {{ ansible_facts[item]['macaddress']|default(None) }}"
    with_items:
    - "{{ ansible_interfaces }}"

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .