1

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
0

2 Answers 2

3

I needed to do this with_indexed_items: "{{ vcs.stdout.split('\n')}}"

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.