Reputation: 10470
I am learning ansible and I would like to know how to iterate of the results of a shell command. Here is what I have tried. I have this playbook:
[root@d61311ae17e2 /]# cat loop.yaml
---
- name: Loop Example
hosts: localhost
tasks:
- name:
command: cat /vcs.txt
register: vcs
- name: Nonsense to demo loop
template:
src: /foo.j2
dest: /foo.{{ item.1 }}
with_indexed_items: "{{ vcs }}"
The file /vcs.txt contains this:
[root@d61311ae17e2 /]# cat vcs.txt
vc-one
vc-two
vc-three
vc-four
What I was hoping would happen was the creation of four files: foo.vc-one, foo.vc-two, foo.vc-three and foo.vc-four. But what happens instead when I run ansible-playbook loop.yaml
is this:
PLAY [Loop Example] *********************************************************************************************************************************************
TASK [Gathering Facts] ******************************************************************************************************************************************
ok: [127.0.0.1]
TASK [command] **************************************************************************************************************************************************
changed: [127.0.0.1]
TASK [Nonsense to demo loop] ************************************************************************************************************************************
fatal: [127.0.0.1]: FAILED! => {"msg": "with_indexed_items expects a list"}
to retry, use: --limit @/loop.retry
PLAY RECAP ******************************************************************************************************************************************************
127.0.0.1 : ok=2 changed=1 unreachable=0 failed=1
Upvotes: 1
Views: 4955
Reputation: 11
If you need stdout on a line-by-line basis, with_indexed_items: "{{ vcs.stdout_lines }}"
is equivalent to .split('\n')
and likely simpler/clearer.
Upvotes: 1
Reputation: 10470
I needed to do this with_indexed_items: "{{ vcs.stdout.split('\n')}}"
Upvotes: 3