0

範囲を持つ以下のjsonがあります。ansible variable として使用される範囲から特定のエントリの json から値を取得しようとしています。

たとえば、JSON Query Filter を使用して ansible 変数として使用される json の下からのfolder値を取得したいと考えています。server002助けてください。

[
{"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

以下は、ユースケースを満たす必要がある実用的なプレイです。

---
- 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 に答える