4

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"
ady8531
  • 689
  • 5
  • 13
  • 24

1 Answers1

6

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

zuazo
  • 5,398
  • 2
  • 23
  • 22
  • Just as a side question: How can i use with_dict in this case? I mean .stdout or .stdout_lines would be a key but how can i use with_dict? Your answer does what i wanted but i'm trying to find a prettyer solution :) – ady8531 Jan 09 '16 at 07:06
  • I added an example using `with_dict`. – zuazo Jan 09 '16 at 07:33