How do I do looping on playbook?

Hello, below is my play book

Look up “with_items” in the documentation for examples for the looping construct in Ansible. You would then use the “item” variable to represent what is looped over in each cycle of the loop inside the task.

Also, I should point out that “only_if” is rather dated in Ansible, look at the 1.2 documentation for how to use “when” and things get much simpler.

when: value == 'hello"

etc

Thanks Michael for the reply. Awesome. I tried this:

You can simplify:

with_items:

  • motd1
  • motd2

Otherwise you’d have to do {{ item.item }}

the way you had it.

Hope this helps!

Hi, I simplified my declaration. Unfortunately, i still got the same error. ERROR: /home/me/ Documents/${item} does not exist.

can lookup read ${item}? Seems like it cannot.

And is there other way to do iteration?

with_item is good for small number of variables eg. motd1 to motd5. However, if i want motd1 to motd1000, i will have to have with_items 1 to 1000? is it possible to have a variable i and loop it iteratively? eg motd[i]

Thanks

Change your lookup call to look like this…

value: “{{ lookup(‘file’,‘/home/me/Documents/’ + item) }}”

${foo} is old school stuff and shouldn’t be mixed with {{ foo }}

Hi,

Despite other problems, the biggest is that you are trying to iterate in the vars section! You can only iterate in tasks (or handlers).

Probably something like:

you are doing with_items at the play level, it is normally done at the task level

hosts: all

user: xyz

tasks:

  • action: copy src=/home/me/Documents/“{{lookup(‘file’,'/home/me/ Documents/”’ + item )}}" dest=/home/me2/Desktop/{{item}}

name: to copy

with_items:

  • ‘motd1’

  • ‘motd2’

Brian Coca

I am guessing he/she probably wants to loop all the tasks, not jus that task itself. But reiterate all the tasks in that playbook. Can that be done?

There is an unsupported way to include multiple tasks based on a loop, but it’s not supported because it’s hyper-confusing and people try to do it with inventory variables.

It is preferred to loop on individual tasks only.