0

我有下面的 json 有一个范围。我正在尝试从 json 中获取要用作 ansible 变量的范围中特定条目的值。

例如,我想使用 JSON 查询过滤器从下面的 json 中获取folderof 的值,server002以用作 ansible 变量。请帮忙。

[
{"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"
}}
]
4

2 回答 2

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']
于 2018-12-03T10:37:20.937 回答
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 == ""
...
于 2018-12-04T05:06:44.960 回答