Извлечение элементов из списка, вложенного в другой список - PullRequest
0 голосов
/ 06 июня 2018

У нас есть большой список переменных (файлы xml, 4000+ строк), которые я запускал через конвертер xml-> yml.Выходной yaml похож на упрощенную версию ниже.

Из шаблона я пытаюсь извлечь значение из списка файлов var в другом списке.Мне нужны элементы из 'level4', когда _type = listType1, из файла var:

Файл Var:

---
# Site-specific vars

level1:
  level2:
    -
      _type: listType1
      _instance: 1
      level3:
        level4:
         - "theImportanStuff1"
         - "theImportanStuff2"
    -
      _type: notListType1
      _instance: 1
      level3:
        level4:
         - "notImportanStuff1"
         - "notImportanStuff2"

Файл шаблона (я пробовал много, много вариантов,это происходит с последним):

# TEST FILE
# Insert Info Here6
{% for item in [level1.level2|selectattr('_type','match','listType1')|selectattr('level3.level4') | list ] %}
myInfo: {{ item }}
{% endfor %}

Файл задачи:

---
- name: set
  set_fact:
    testit: "{{level1.level2|selectattr('_type','match','listType1')| map(attribute='level3') | join (', ') }}"

- debug:
     msg="{{ testit }}"

- name: set2
  set_fact:
    testit2: "{{level1.level2|selectattr('_type','match','listType1')| list }}"

- debug:
     msg="{{ testit2 }}"

- name: set3
  set_fact:
    testit3: "{{level1.level2|selectattr('_type','match','listType1') }}"

- debug:
     msg="{{ testit3 }}"

# tasks file for ansible-role snmp
- name: "Gather OS specific variables"
  include_vars: "{{ item }}"
  with_first_found:
    - "{{ ansible_distribution|lower }}-{{ ansible_distribution_version }}.yml"
    - "{{ ansible_distribution|lower }}.yml"
    - "{{ ansible_os_family|lower }}.yml"

- name: Copy TEST configuration file
  template:
    src: test.conf.j2
    dest: /root/test.conf
    mode: 0600
    owner: root
    group: root

Вывод из прогона:

[root@AnsibleServer2 ansible]# ansible-playbook -i inventory/staging/host_vars/hostname2  playbook/testit.yml

PLAY [Test-c7-1] ******************************************************************************************************************************************************************

TASK [Gathering Facts] ************************************************************************************************************************************************************
ok: [Test-c7-1]

TASK [john.test : set] ************************************************************************************************************************************************************
ok: [Test-c7-1]

TASK [john.test : debug] **********************************************************************************************************************************************************
ok: [Test-c7-1] => {
    "msg": {
        "level4": [
            "theImportanStuff1",
            "theImportanStuff2"
        ]
    }
}

TASK [john.test : set2] ***********************************************************************************************************************************************************
ok: [Test-c7-1]

TASK [john.test : debug] **********************************************************************************************************************************************************
ok: [Test-c7-1] => {
    "msg": [
        {
            "_instance": 1,
            "_type": "listType1",
            "level3": {
                "level4": [
                    "theImportanStuff1",
                    "theImportanStuff2"
                ]
            }
        }
    ]
}

TASK [john.test : set3] ***********************************************************************************************************************************************************
ok: [Test-c7-1]

TASK [john.test : debug] **********************************************************************************************************************************************************
ok: [Test-c7-1] => {
    "msg": "<generator object _select_or_reject at 0x1aa9730>"
}

TASK [john.test : Gather OS specific variables] ***********************************************************************************************************************************
ok: [Test-c7-1] => (item=/etc/ansible/roles/john.test/vars/redhat.yml)

TASK [john.test : Copy TEST configuration file] ***********************************************************************************************************************************
ok: [Test-c7-1]

PLAY RECAP ************************************************************************************************************************************************************************
Test-c7-1                  : ok=9    changed=0    unreachable=0    failed=0

Все, что я пробовал, либо не удаетсязапустите или добавьте один из них к значениям в test.conf:

myInfo: <generator object _select_or_reject at 0x1b93cd0>

myInfo: [{u'_type': u'listType1', u'level3': {u'level4': [u'theImportanStuff1', u'theImportanStuff2']}, u'_instance': 1}]

Где бы я хотел видеть:

myInfo: theImportanStuff1
myInfo: theImportanStuff2

1 Ответ

0 голосов
/ 06 июня 2018

Если ваше условие _type = listType1 возвращает только один элемент:

{% for item in  (level1.level2|selectattr('_type','match','listType1') | first).level3.level4 %}
myInfo: {{ item }}
{% endfor %}

Если ваше условие _type = listType1 возвращает список, вам нужны два цикла, но это неясно из разобранного примера в вашем вопросечто вы хотите напечатать в таком случае.В любом случае шаблон:

{% for outer in level1.level2|selectattr('_type','match','listType1') %}
{% for inner in outer.level3.level4 %}
myInfo: {{ inner }}
{% endfor %}
{% endfor %}
...