Question:
I was given a task to verify some routing entries for all Linux server and here is how I did it using an Ansible playbook
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
--- - hosts: Linux serial: 1 tasks: - name: Check first command: /sbin/ip route list xxx.xxx.xxx.xxx/24 register: result changed_when: false - debug: msg="{{result.stdout}}" - name: Check second command: /sbin/ip route list xxx.xxx.xxx.xxx/24 register: result changed_when: false - debug: msg="{{result.stdout}}" |
You can see I have to repeat same task for each routing entry and I believe I should be able to avoid this. I tried use with_items
loop but got following error message
1 2 |
One or more undefined variables: 'dict object' has no attribute 'stdout' |
is there a way to register variable for each command and loop over them one by one ?
Answer:
Starting in Ansible 1.6.1, the results registered with multiple items are stored in result.results
as an array. So you can use result.results[0].stdout
and so on.
Testing playbook:
1 2 3 4 5 6 7 8 9 10 |
--- - hosts: localhost gather_facts: no tasks: - command: "echo {{item}}" register: result with_items: [1, 2] - debug: var: result |
Result:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
$ ansible-playbook -i localhost, test.yml PLAY [localhost] ************************************************************** TASK: [command echo {{item}}] ************************************************* changed: [localhost] => (item=1) changed: [localhost] => (item=2) TASK: [debug ] **************************************************************** ok: [localhost] => { "var": { "result": { "changed": true, "msg": "All items completed", "results": [ { "changed": true, "cmd": [ "echo", "1" ], "delta": "0:00:00.002502", "end": "2015-08-07 16:44:08.901313", "invocation": { "module_args": "echo 1", "module_name": "command" }, "item": 1, "rc": 0, "start": "2015-08-07 16:44:08.898811", "stderr": "", "stdout": "1", "stdout_lines": [ "1" ], "warnings": [] }, { "changed": true, "cmd": [ "echo", "2" ], "delta": "0:00:00.002516", "end": "2015-08-07 16:44:09.038458", "invocation": { "module_args": "echo 2", "module_name": "command" }, "item": 2, "rc": 0, "start": "2015-08-07 16:44:09.035942", "stderr": "", "stdout": "2", "stdout_lines": [ "2" ], "warnings": [] } ] } } } PLAY RECAP ******************************************************************** localhost : ok=2 changed=1 unreachable=0 failed=0 |