具有值范围的JMESPath查询表达式

时间:2018-12-03 06:06:34

标签: ansible ansible-2.x jmespath

我有以下具有范围的json。我正在尝试从json中获取范围内特定条目的值,以用作ansible变量。

例如,

我想从json下面获取defaultImporter := importer.For("gc", nil) modelsPkg, err := defaultImporter.Import("github.com/foo/bar/models") 的{​​{1}}值,以用作使用JSON查询过滤器的ansible变量。请帮忙。

folder

2 个答案:

答案 0 :(得分:0)

在您的示例中没有看到server002,但是下面是在列表中搜索第二台服务器的示例。 (将“ json_file_path”更改为JSON文件所在的路径。)

- name: Set search facts
  set_fact:
     host_to_find: 'server061:080'
     json_file_path: <path to json file>
- name: Get data for host
  vars:
    hosts_data: "{{ lookup('file', json_file_path) | from_json }}"
  set_fact:
    host: "{{ hosts_data | selectattr('hosts', 'match', host_to_find) | list | first }}"
- name: Display value of folder var
  debug:
    var: host['values']['folder']

答案 1 :(得分:0)

以下是一个可以满足您的用例的工作方式:

---
- name: JSON range extraction
  hosts: 127.0.0.1
  connection: local
  gather_facts: no
  tasks:
    - name: Set facts for search
      set_fact:
        host_to_find: '002'
        hosts_json_string: '[{"hosts":"server001:060","values":{"folder":"/my_folder1/","pool":"pool1","dsname":"DS1","network":"nw_1"}},{"hosts":"server061:080","values":{"folder":"/my_folder2/","pool":"pool2","dsname":"DS2","network":"nw_2"}}]'

    - name: Convert json string to facts
      set_fact:
        hosts_data: "{{ hosts_json_string | from_json }}"

    - name: Sort json by hosts and replace the value of hosts to make range extraction easier
      set_fact:
        sorted_hosts: "{{hosts_data|sort(attribute='hosts')|regex_replace('(server(\\d+):(\\d+))','\\2-\\3')}}"

    - name: Find index of host_to_find in sorted_hosts and set_fact
      vars:
        hosts_range: "{{sorted_hosts| json_query('[*].hosts')}}"
      set_fact:
        host_index: "{% for range in hosts_range %}{% set range_split = range.split('-') %}{% if ((host_to_find|int >= range_split[0]|int) and (host_to_find|int <= range_split[1]|int)) %}{{ loop.index0 }}{% endif %}{% endfor %}"

    - name: Get the folder location
      set_fact:
        folder_location: "{{ sorted_hosts[host_index|int].get('values').folder }}"
      when: not host_index == ""
...