I want to use this output (from a previous command) as an array of key-values or as an inventory for the next command in the same playbook
stdout:
hot-01: 10.100.0.101
hot-02: 10.100.0.102
hot-03: 10.100.0.103
....
hot-32: 10.100.0.132
like this:
- shell: "echo {{ item.key }} has value {{ item.value }}"
with_items: "{{ output.stdout_lines }}"
or:
- add_host: name={{ item.key }} ansible_ssh_host={{ item.value }}
with_items: "{{ output.stdout_lines }}"
Desired output of the echo command:
hot-01 has value 10.100.0.101
I also tried with with_dict: "{{ output.stdout }}" but still no luck
"fatal: [ANSIBLE] => with_dict expects a dict"
AFAIK there are no Jinja2 filters to convert strings to dictionaries.
But in your specific case, you can use the python's split
string function to separate the key from the value:
- shell: "echo {{ item.split(': ')[0] }} has value {{ item.split(': ')[1] }}"
with_items: "{{ output.stdout_lines }}"
I know, having to use split twice is a bit sloppy.
As in this case your output is a valid YAML, you can also do the following:
- shell: "echo {{ item.key }} has value {{ item.value }}"
with_dict: "{{ output.stdout | from_yaml }}"
As a last resort, you can also create your own ansible module to create a Jinja2 filter to cover your case. There is an split
module filter that you can use as inspiration here: https://github.com/timraasveld/ansible-string-split-filter
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With