# How to loop over all elements of a list when elements are not known in advance?

**URL:** <https://forum.ansible.com/t/how-to-loop-over-all-elements-of-a-list-when-elements-are-not-known-in-advance/15869>\
**Category:** Ansible Project\
**Created:** [August 6, 2014, 10:58am UTC](https://forum.ansible.com/t/how-to-loop-over-all-elements-of-a-list-when-elements-are-not-known-in-advance/15869 "2014-08-06T10:58:17Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Servermanaged](https://avatars.discourse-cdn.com/v4/letter/s/d6d6ee/32.png) [@Servermanaged](https://forum.ansible.com/u/Servermanaged)\
**Post date:** [August 6, 2014, 10:58am UTC](https://forum.ansible.com/t/how-to-loop-over-all-elements-of-a-list-when-elements-are-not-known-in-advance/15869/1 "2014-08-06T10:58:17Z")

</div>

Hello friends

I’ve some lists of elements which contains values like plugin: “someplugin”, directive: “somedirective”. For reference see

Variables: [https://github.com/valentinogagliardi/collectd/blob/master/README.md#example-playbook](https://github.com/valentinogagliardi/collectd/blob/master/README.md#example-playbook)

Template: [https://github.com/valentinogagliardi/collectd/blob/master/templates/collectd.conf.j2](https://github.com/valentinogagliardi/collectd/blob/master/templates/collectd.conf.j2)

At this moment I’m able to generate a configuration which take this form:

\<Plugin “someplugin”\>  
somedirective

\<Plugin “anotherplugin”\>  
anothersomedirective

What if I want to add more directives to the list?

plugins:

- { plugin: “someplugin”, directive: “somedirective” }
- { plugin: “anotherplugin”, directive: “somedirective”, directive\_x: “anotherdirective” }

Is not clear to me how to loop over all elements when elements are not known in advance, in order to generate a configuration like this:

\<Plugin “someplugin”\>  
somedirective

\<Plugin “anotherplugin”\>  
somedirective  
anotherdirective

Thanks in advance!

---

<div class="post-metadata">

**Author:** ![Michael\_DeHaan1](https://avatars.discourse-cdn.com/v4/letter/m/5e9695/32.png) [@Michael\_DeHaan1](https://forum.ansible.com/u/Michael_DeHaan1)\
**Post date:** [August 7, 2014, 9:16pm UTC](https://forum.ansible.com/t/how-to-loop-over-all-elements-of-a-list-when-elements-are-not-known-in-advance/15869/2 "2014-08-07T21:16:52Z")

</div>

For dictionaries, you can use “.keys()” to get all of them. There is also “.iteritems()” which returns a tuple of both the key and the value.

---

<div class="post-metadata">

**Author:** ![Servermanaged](https://avatars.discourse-cdn.com/v4/letter/s/d6d6ee/32.png) [@Servermanaged](https://forum.ansible.com/u/Servermanaged)\
**Post date:** [August 8, 2014, 8:02am UTC](https://forum.ansible.com/t/how-to-loop-over-all-elements-of-a-list-when-elements-are-not-known-in-advance/15869/3 "2014-08-08T08:02:08Z")

</div>

Sounds interesting! Thanks for the suggestion!
