I'm trying to iterate over a list in Ansible and search for a string in each item in it, and then assigning the matched item to a variable. To be more specific, I'm pulling all MAC addresses on each node into a list and looking for a specific manufacturer prefix in each interface.
The list is created from Ansible facts - I create it at the start of the play:
vars:
mac_addresses: []
And then add found facts into it:
- name: Find MAC addresses
shell: "echo {{ ansible_facts[item]['macaddress']|default(None) }}"
register: mac_addresses
with_items:
- "{{ ansible_interfaces }}"
I then tried to iterate over that list - I tried using the match
method:
- name: Find correct MAC address
debug:
msg: "{{ item }} is the correct NIC"
when: "{{ item }}" is match("*[mac prefix]*")
with_items:
- "{{ mac_addresses }}"
I've also tried registering the prefix to a variable and using a conditional by replacing the above's when
line with:
when: correct_prefix in mac_addresses
Both of which fail to run or produce unwanted results.
How would I go about finding a string in a list, and registering the result in a variable? I've looked around the internet and in documentation and could not figure it out - any help would be greatly appreciated.
Thanks!
EDIT: The MAC address found by the code above produced an array or results, from which I've extracted the stdout thanks to the answer here: https://stackoverflow.com/questions/29512443/register-variables-in-with-items-loop-in-ansible-playbook
Using Vladimir's answer below, I've come up with the following:
- debug: var="mac_addresses"
- debug: msg="item.item={{item.item}}, item.stdout={{item.stdout}}, item.changed={{item.changed}}"
with_items: "{{ mac_addresses.results }}"
- debug:
msg: "{{ item.stdout }} is the correct NIC"
loop: "{{ mac_addresses.results }}"
when: item[0:8] in mac_prefix
...Which I can't get to work either - even after setting the desired prefix in a variable. Any clarification would be greatly appreciated - I'm not even sure which docs to seek out.
Thanks!