# Loading vars into a dictionary

**URL:** <https://forum.ansible.com/t/loading-vars-into-a-dictionary/24396>\
**Category:** Ansible Project\
**Created:** [May 4, 2017, 2:03am UTC](https://forum.ansible.com/t/loading-vars-into-a-dictionary/24396 "2017-05-04T02:03:44Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Pshem\_Kowalczyk](https://avatars.discourse-cdn.com/v4/letter/p/e480ec/32.png) [@Pshem\_Kowalczyk](https://forum.ansible.com/u/Pshem_Kowalczyk)\
**Post date:** [May 4, 2017, 2:03am UTC](https://forum.ansible.com/t/loading-vars-into-a-dictionary/24396/1 "2017-05-04T02:03:44Z")

</div>

Hi,

I’d like to load variables from a file into a dictionary, so I can later iterate over that dictionary.

I’ve managed to load vars into their own dictionaries based on their name:

- name: load services definitions for the product  
include\_vars:  
file: “…/model/service/{{ item }}.yaml”  
name: “service\_data\_{{ item }}”  
with\_items: “{{ product\_data.services }}”

I’ve tried various syntax with the ‘name’ parameter, but I always end up with it being treated as a string.

This ends up looking like this:

“service\_data\_access\_interface”: {  
“resources”: [  
“interface”  
],  
“service\_name”: “access\_interface”,  
“service\_vars”: [  
{  
“mandatory”: true,  
“name”: “description”,  
“type”: “string”  
}  
]  
},  
“service\_data\_l2vpn”: {  
“resources”: [  
“routing\_instance”  
],  
“service\_name”: “l2vpn”,  
“service\_vars”: [  
{  
“mandatory”: true,  
“name”: “description”,  
“type”: “string”  
}  
]  
},

Which makes it very difficult to iterate over. Id like to iterate of this to get to the inner level of ‘service\_vars’, names like ‘l2vpn’ or ‘access\_interface’ come from another dictionary (that’s loaded earlier)

Any idea how to either import into into a dictionary (so i could use subelements) or iterate over the ‘service\_vars’ (knowing part of the string used to create the key)?

kind regards  
Pshem

---

<div class="post-metadata">

**Author:** ![Pshem\_Kowalczyk](https://avatars.discourse-cdn.com/v4/letter/p/e480ec/32.png) [@Pshem\_Kowalczyk](https://forum.ansible.com/u/Pshem_Kowalczyk)\
**Post date:** [May 5, 2017, 9:38am UTC](https://forum.ansible.com/t/loading-vars-into-a-dictionary/24396/2 "2017-05-05T09:38:19Z")

</div>

After a bit of trying I came up with this solution - perhaps not the cleanest but does the job:

- name: load services definitions for the product  
include\_vars:  
file: “…/model/service/{{ item }}.yaml”  
name: “service\_data\_{{ item }}”  
with\_items: “{{ product\_data.services }}”

- name: repack services definitions  
set\_fact: “services={{ services | default() + [hostvars[inventory\_hostname][‘service\_data\_’ + item] ] }}”  
with\_items: “{{ product\_data.services }}”

This builds an array of dictionaries that can be iterated over.

kind regards  
Pshem
