0

In the Ansible documentation on filters, the following example is shown, which executes a JSON query on a data structure, selecting certain fields name and port:

- name: "Display all server ports and names from cluster1"
  debug: var=item
  with_items: "{{domain_definition|json_query(server_query)}}"
  vars:
    server_query: "domain.server[?cluster=='cluster2'].{name: name, port: port}"

I managed to use this logic to parse the JSON response of a REST service, but I would like to not only print out the result, but reuse it several times again during my playbook.

How is it possible to persist the above variable var for later use?

dokaspar
  • 8,186
  • 14
  • 70
  • 98
  • You always do this with `set_fact`. I'm not sure what this question is about. There is a method to use `set_fact` in a loop. And it's not a `var` variable, it's an argument called `var`. – techraf Sep 05 '17 at 06:19

1 Answers1

3

Just replace debug call with set_fact. For example:

- name: "Display all server ports and names from cluster1"
  set_fact:
    'name_{{ item.name }}': '{{ item.port }}'
  with_items: "{{domain_definition|json_query(server_query)}}"
  vars:
    server_query: "domain.server[?cluster=='cluster2'].{name: name, port: port}"

This will generate two persistent facts (based on docs data): name_server21 with value 9080 and name_server22 = 9090.

Konstantin Suvorov
  • 65,183
  • 9
  • 162
  • 193
  • Thanks. I actually tried using `set_fact`, but apparently not the correct way... With your hint I could achieve what I want :) – dokaspar Sep 05 '17 at 06:29