Spec-Zone.ru › Ansible 2.11

ansible.utils.index_of – Нахождение индексов элементов в списке, соответствующих определённым критериям

Примечание

Этот плагин входит в состав коллекции ansible.utils (версия 2.0.0).

Для его установки используйте: ansible-galaxy collection install ansible.utils.

Для использования в плейбуке укажите: ansible.utils.index_of.

В версии 1.0.0: из ansible.utils

  • Обзор
  • Параметры
  • Примеры
  • Возвращаемые значения

Обзор

  • Этот плагин возвращает индексы элементов в списке, соответствующих заданным критериям.
  • При работе со списком словарей можно указать ключ для проверки.
  • index_of также доступен в качестве плагина фильтрации для удобства.
  • Используя параметры ниже- lookup('ansible.utils.index_of', data, test, value, key, fail_on_missing, wantlist).

Параметры

Параметр Варианты/Значения по умолчанию Конфигурация Комментарии
data
список / элементы=строка / обязательный
Список элементов для перечисления и проверки.
fail_on_missing
логический
    Варианты:
  • нет
  • да
При предоставлении списка словарей, завершать выполнение, если ключ отсутствует в одном или нескольких словарях.
key
строка
Если предоставленные данные представляют собой список словарей, выполняется проверка по этому ключу словаря. При использовании параметра key, параметр data должен содержать только словари. См. fail_on_missing ниже, чтобы определить поведение, когда key отсутствует в словаре data.
test
строка / обязательный
Название теста для проверки списка; допустимый тест Jinja2 или плагин проверки Ansible. Jinja2 включает следующие тесты http://jinja.palletsprojects.com/templates/#builtin-tests. Обзор тестов, включённых в Ansible https://docs.ansible.com/ansible/latest/user_guide/playbooks_tests.html.
value
сырые данные
Значение, используемое для проверки каждого элемента списка. Не требуется для простых тестов (например: true, false, even, odd) Может быть string, boolean, number, regular expression dict и так далее, в зависимости от используемого test.
wantlist
логический
    Варианты:
  • нет
  • да
Если соответствует только один элемент в data, индекс этого элемента возвращается как целое число. Если установлено значение True, возвращаемое значение всегда будет списком, даже если соответствует только один элемент. Это также можно сделать, используя query или q вместо lookup. https://docs.ansible.com/ansible/latest/plugins/lookup.html

Примеры

#### Simple examples

- ansible.builtin.set_fact:
    data:
    - 1
    - 2
    - 3

- name: Find the index of 2
  ansible.builtin.set_fact:
    indices: "{{ lookup('ansible.utils.index_of', data, 'eq', 2) }}"

# TASK [Find the index of 2] *************************************************
# ok: [nxos101] => changed=false
#   ansible_facts:
#     indices: '1'

- name: Find the index of 2, ensure list is returned
  ansible.builtin.set_fact:
    indices: "{{ lookup('ansible.utils.index_of', data, 'eq', 2, wantlist=True) }}"

# TASK [Find the index of 2, ensure list is returned] ************************
# ok: [nxos101] => changed=false
#   ansible_facts:
#     indices:
#     - 1

- name: Find the index of 3 using the long format
  ansible.builtin.set_fact:
    indices: "{{ lookup('ansible.utils.index_of', data=data, test='eq', value=value, wantlist=True) }}"
  vars:
    value: 3

# TASK [Find the index of 3 using the long format] ***************************
# ok: [nxos101] => changed=false
#   ansible_facts:
#     indices:
#     - 2

- name: Find numbers greater than 1, using loop
  debug:
    msg: "{{ data[item] }} is {{ test }} than {{ value }}"
  loop: "{{ lookup('ansible.utils.index_of', data, test, value) }}"
  vars:
    test: '>'
    value: 1

# TASK [Find numbers great than 1, using loop] *******************************
# ok: [sw01] => (item=1) =>
#   msg: 2 is > than 1
# ok: [sw01] => (item=2) =>
#   msg: 3 is > than 1

- name: Find numbers greater than 1, using with
  debug:
    msg: "{{ data[item] }} is {{ params.test }} than {{ params.value }}"
  with_ansible.utils.index_of: "{{ params }}"
  vars:
    params:
      data: "{{ data }}"
      test: '>'
      value: 1

# TASK [Find numbers greater than 1, using with] *****************************
# ok: [nxos101] => (item=1) =>
#   msg: 2 is > than 1
# ok: [nxos101] => (item=2) =>
#   msg: 3 is > than 1


#### Working with lists of dictionaries

- ansible.builtin.set_fact:
    data:
    - name: sw01.example.lan
      type: switch
    - name: rtr01.example.lan
      type: router
    - name: fw01.example.corp
      type: firewall
    - name: fw02.example.corp
      type: firewall

- name: Find the index of all firewalls using the type key
  ansible.builtin.set_fact:
    firewalls: "{{ lookup('ansible.utils.index_of', data, 'eq', 'firewall', 'type') }}"

# TASK [Find the index of all firewalls using the type key] ******************
# ok: [nxos101] => changed=false
#   ansible_facts:
#     firewalls:
#     - 2
#     - 3

- name: Find the index of all firewalls, use in a loop
  debug:
    msg: "The type of {{ device_type }} at index {{ item }} has name {{ data[item].name }}."
  loop: "{{ lookup('ansible.utils.index_of', data, 'eq', device_type, 'type') }}"
  vars:
    device_type: firewall

# TASK [Find the index of all firewalls, use in a loop, as a filter] *********
# ok: [nxos101] => (item=2) =>
#   msg: The type of firewall at index 2 has name fw01.example.corp.
# ok: [nxos101] => (item=3) =>
#   msg: The type of firewall at index 3 has name fw02.example.corp.

- name: Find the index of all devices with a .corp name
  debug:
    msg: "The device named {{ data[item].name }} is a {{ data[item].type }}"
  loop: "{{ lookup('ansible.utils.index_of', data, 'regex', expression, 'name') }}"
  vars:
    expression: '\.corp$' # ends with .corp

# TASK [Find the index of all devices with a .corp name] *********************
# ok: [nxos101] => (item=2) =>
#   msg: The device named fw01.example.corp is a firewall
# ok: [nxos101] => (item=3) =>
#   msg: The device named fw02.example.corp is a firewall


#### Working with complex structures from resource modules

- name: Retrieve the current L3 interface configuration
  cisco.nxos.nxos_l3_interfaces:
    state: gathered
  register: current_l3

# TASK [Retrieve the current L3 interface configuration] *********************
# ok: [sw01] => changed=false
#   gathered:
#   - name: Ethernet1/1
#   - name: Ethernet1/2
#   <...>
#   - name: Ethernet1/128
#   - ipv4:
#     - address: 192.168.101.14/24
#     name: mgmt0

- name: Find the indices interfaces with a 192.168.101.xx ip address
  ansible.builtin.set_fact:
    found: "{{ found + entry }}"
  with_indexed_items: "{{ current_l3.gathered }}"
  vars:
    found: []
    ip: '192.168.101.'
    address: "{{ lookup('ansible.utils.index_of', item.1.ipv4|d([]), 'search', ip, 'address', wantlist=True) }}"
    entry:
    - interface_idx: "{{ item.0 }}"
      address_idxs: "{{ address }}"
  when: address

# TASK [debug] ***************************************************************
# ok: [sw01] =>
#   found:
#   - address_idxs:
#     - 0
#     interface_idx: '128'

- name: Show all interfaces and their address
  debug:
    msg: "{{ interface.name }} has ip {{ address }}"
  loop: "{{ found|subelements('address_idxs') }}"
  vars:
    interface: "{{ current_l3.gathered[item.0.interface_idx|int] }}"
    address: "{{ interface.ipv4[item.1].address }}"

# TASK [Show all interfaces and their address] *******************************
# ok: [nxos101] => (item=[{'interface_idx': '128', 'address_idxs': [0]}, 0]) =>
#   msg: mgmt0 has ip 192.168.101.14/24


#### Working with deeply nested data

- ansible.builtin.set_fact:
    data:
      interfaces:
        interface:
          - config:
              description: configured by Ansible - 1
              enabled: True
              loopback-mode: False
              mtu: 1024
              name: loopback0000
              type: eth
            name: loopback0000
            subinterfaces:
              subinterface:
                - config:
                    description: subinterface configured by Ansible - 1
                    enabled: True
                    index: 5
                  index: 5
                - config:
                    description: subinterface configured by Ansible - 2
                    enabled: False
                    index: 2
                  index: 2
          - config:
              description: configured by Ansible - 2
              enabled: False
              loopback-mode: False
              mtu: 2048
              name: loopback1111
              type: virt
            name: loopback1111
            subinterfaces:
              subinterface:
                - config:
                    description: subinterface configured by Ansible - 3
                    enabled: True
                    index: 10
                  index: 10
                - config:
                    description: subinterface configured by Ansible - 4
                    enabled: False
                    index: 3
                  index: 3


- name: Find the description of loopback111, subinterface index 10
  debug:
    msg: |-
      {{ data.interfaces.interface[int_idx|int]
          .subinterfaces.subinterface[subint_idx|int]
            .config.description }}
  vars:
    # the values to search for
    int_name: loopback1111
    sub_index: 10
    # retrieve the index in each nested list
    int_idx: |
      {{ lookup('ansible.utils.index_of',
             data.interfaces.interface,
                 'eq', int_name, 'name') }}
    subint_idx: |
      {{ lookup('ansible.utils.index_of',
             data.interfaces.interface[int_idx|int].subinterfaces.subinterface,
                 'eq', sub_index, 'index') }}

# TASK [Find the description of loopback111, subinterface index 10] ************
# ok: [sw01] =>
#   msg: subinterface configured by Ansible - 3

Возвращаемые значения

Общие возвращаемые значения описаны здесь, следующие являются полями, уникальными для этого поиска:

Ключ Возвращаемое значение Описание
_raw
строка
успех
Один или несколько индексов (от 0) соответствующих элементов списка.
См. wantlist если список всегда требуется.



Авторы

  • Bradley Thornton (@cidrblock)

© 2012–2018 Michael DeHaan
© 2018–2021 Red Hat, Inc.
Licensed under the GNU General Public License version 3.
https://docs.ansible.com/ansible/2.11/collections/ansible/utils/index_of_lookup.html

Spec-Zone.ru

Настройки Оффлайн Что нового Помощь О нас
Spec-Zone .ru
спецификации, руководства, описания, API