I have a task for a Cisco device where I register zero or more lines to come back to later:
- name: gather non-standard usernames
ios_command:
commands: - show running-config | include username
register: usernames
I would like the next task to run through each registered line individually and if the line doesn’t contain the word “root”, then it should print the line. This was my first attempt at the task:
- debug:
msg: “{{ item }}”
when: “‘root’ in item.stdout”
loop: “{{ usernames.stdout_lines }}”
If I debug the entire usernames variable I get this:
TASK [network-common : debug] ****************************************************************************************************************************************************
ok: [rtr01] => {
“usernames”: {
“changed”: false,
“failed”: false,
“stdout”: [
“username root privilege 15 secret 5 *******\nusername temp privilege 15 secret 4 *******”
],
“stdout_lines”: [
[
“username root privilege 15 secret 5 *******”,
“username temp privilege 15 secret 4 *******”
]
]
}
}
Apparently it returns the lines inside two arrays. Since the outer array always includes the word “root”, it returns the entire contents of the outer array, which includes both lines. I tried to flatten the arrays like so:
- debug:
msg: “{{ lookup(‘flattened’,item) }}”
when: “‘root’ not in item”
loop: “{{ usernames.stdout_lines }}”
But that flattens them too much, into a single string, resulting in this:
TASK [network-common : debug] ****************************************************************************************************************************************************
ok: [rtr01] => (item=[u’username root privilege 15 secret 5 *******‘, u’username temp privilege 15 secret 4 *******’]) => {
“item”: [
“username root privilege 15 secret 5 *******”,
“username temp privilege 15 secret 4 *******”
],
“msg”: “username root privilege 15 secret 5 *******,username temp privilege 15 secret 4 ********”
}
If I use the operator “with_items”, this works correctly, as apparently with_items flattens the first level but nothing after that. However, the deprecation warning has suggested that we migrate to “loop” instead. Does anybody know how to emulate the flattening behavior of with_items with the loop operator?
Thanks,
Ian