Reputation: 341
i work with Ansible 2.4.2.0.
I have a playbook and defined a variable host: mymachine
. I have a registered variable that looks like:
"json": {
"results": [
{
[...],
"item": "myname",
"stdout_lines": "abc"
[...]
},
{
[...],
"item": "myname2",
"stdout_lines": "xyz"
[...]
{
]
}
I now want to use the values of item
as keys of a new hash (together with my host
).
Something like this task:
-name Create Hash
set_fact:
"{{ host[item.item] }}": "{{ item.stdout_lines }}"
with_items:
- "{{ json.results }}" `
I want my hash to look like:
"mymachine": {
"myname": "abc",
"myname2": "xyz"
}
I know the iteration of json.results
works and item.item
and item.stdout_lines
are accessible. But the "{{ host[item.item] }}":
-part won't work. I tried all combinations of brackets, I get different error messages, depending on what combination of brackets I use.
Hope someone can tell me the correct syntax.
Upvotes: 0
Views: 2001
Reputation: 68559
I want my Hash to look like:
"mymachine": { "myname": "abc", "myname2": "xyz" }
If you want to define a dictionary named mymachine
, why does your code not even contain the string mymachine
?
the
"{{ host[item.item] }}":
-part won't work
Why should it work, if trying to use it is the first occurrence of host
in your code? You refer to a variable without defining it.
Here's correct syntax for what you want to achieve:
- name: Create Hash
set_fact:
mymachine: "{{ mymachine | default({}) | combine(myelement) }}"
vars:
myelement: "{ '{{ item.item }}':'{{ item.stdout_lines }}' }"
with_items:
- "{{ json.results }}"
Upvotes: 2