首页 > 解决方案 > 在 Anible 中使用计数器控制循环

问题描述

我正在尝试从不属于端口通道的交换机收集接口列表。我正在尝试使用计数器控制列表的位置,以便我可以指定键以便我可以看到值,但我没有成功。

但是当我使用计数器时,我得到列表对象没有属性。

- name: Check for port-channel config in the Ethernet
  nxos_command:
    commands: sh run int {{ item }} | include channel-group
  register: output
  with_items: "{{ ethernet }}"

- name: Trim down conf output
  set_fact:
    int_config: "{{ output['results'] }}"

- debug:
    msg:
      - "The counter is {{ counter | int }}"
      - "Found interface with channgel-group, interface {{ item }}"
   name: show the results
   loop: "{{ int_config[counter] }}"
   loop_control:
     index_var: counter

标签: ansible

解决方案


这是你要找的吗?

- debug:
    msg: "Counter: {{ item|int }} Interface: {{ int_config[item] }}"
  loop: "{{ range(0, int_config|length)|list }}"

此任务与以下数据

int_config:
  - abc
  - def
  - ghi

"msg": "Counter: 0 Interface: abc"
"msg": "Counter: 1 Interface: def"
"msg": "Counter: 2 Interface: ghi"

推荐阅读