How to write selected values to a file from a list of JSON arrays?

I have a task that I am scratching my head on, and my google foo is just getting some really basic examples of the COPY - CONTENT method of writing a file.

my variable returned from the URI module is data, which is a 4 variable JSON array. data.json.devices is the list I want to dump to a file to use as my future hosts file for cli config operations.

ok: [localhost] => {
“msg”: [
{
“hostname”: “host1”,
“id”: “0093253e”,
“mgmtIP”: “10.10.10.1”
},
{
“hostname”: “host2”,
“id”: “00e75962”,
“mgmtIP”: “10.10.10.8”
},
<snip the other 378 entries in list>

I’d like to spit this to a ./inventory/hosts file in a format that my playbook can then use in the next set of tasks. So just the “hostname” and “mgmtIP” variables written to a line.

How might that look?

Nick

You can use the template or the copy module, the jinja template code is the same in both so i just show the copy module

- name: Create inventory
  copy:
    content: |
      {% for i in data.json.devices %}
      {{ i.hostname }} ansible_host={{ i.mgmtIP }}
      {% endfor %}
    dest: inventory/hosts

WOW!

That worked SLICK! And thank you for the much better example, that is very readable but I had a hell of a time finding anything like that on google.

OK, so you mentions jinja… I have heard this term and I hear it is something I need to learn as well… what might this look like using jinja, if you have time? (I have a working file now, thank you very much!)

The code in content: is Jinja so it look exactly like that.

Jinja is a template language for Python that Ansible is also using.
{{ <some_variable }} is actually Jinja, and everything after a when: in Ansible is Jinja.

For more information about Jinja the documentation is here
http://jinja.pocoo.org/docs/2.10/templates/