首页 > 解决方案 > Ansible 将事实与列表进行比较

问题描述

我尝试将 ios_facts 模块中的模型与我的列表“new_models”进行比较,但到目前为止我找不到任何好的解决方案。

我的列表:

---
#
new_models:
  - name: WS-C3650-48PS #1 
  - name: WS-C3750X-48P #2 
  - name: C9200-48P #3
  - name: C9200L-24P-4G #

我的剧本:

tasks:
  
    - name: Check facts
      ios_facts:
        gather_subset: hardware

    - name: Check switch model
      debug: 
       msg: "{{ ansible_net_model }}"
      register: switch_model
      
    - name: Remove file
      file:
        path: /root/ansible/pb-outputs/ios_counters/{{ inventory_hostname }}.txt
        state: absent
     
    - name: Create file for new model switches
      lineinfile:
        path: /root/ansible/pb-outputs/ios_counters/{{ inventory_hostname }}.txt
        line: "1"
        create: yes
      loop: "{{ new_models }}"
      when: switch_model.msg == item.name

    - name: Clear range of counters
      ios_command:
        commands:
          - command: clear counters gigabitEthernet {{ start }}/{{ middle }}/{{ item }}
            prompt: Clear "show interface" counters on this interface \[confirm\]
            answer: y
      with_sequence: start="{{ ifacefrom }}" end="{{ ifaceto }}"
      when: "{{ lookup('file', '/root/ansible/pb-outputs/ios_counters/{{ inventory_hostname }}.txt') }} == 1"

我也知道我不应该在条件句中使用 J2,但这是迄今为止对我有用的唯一方法,但我想为此找到更好的解决方案。对不起,我对ansible还很陌生。

是否可以将 with_items 和 with_sequence 组合成一个循环?我也试过这个,但我无法弄清楚这个的语法......

标签: ansible

解决方案


根据您的问题,我的理解是,您希望ios_commandswitch_model.msgnew_models.

如果是这样,您可以使用set_fact 模块从列表中提取name属性new_models,以便可以直接进行比较,如when: item in list.

使用json_query()

- name: get the model names into new_model_names var
  set_fact:
    new_model_names: "{{ new_models | json_query('[].name') }}"

或使用map()

- name: get the model names into new_model_names var
  set_fact:
    new_model_names: "{{ new_models | map(attribute='name') | list }}"

这将为我们提供一个列表,其中仅包含 name in 的值new_model_names

"new_model_names": [
  "WS-C3650-48PS",
  "WS-C3750X-48P",
  "C9200-48P",
  "C9200L-24P-4G"
]

现在比较会很容易,即when: switch_model.msg in new_model_names. 这应该消除为此目的删除/创建文件的需要。

剧本现在可以有:

    - name: Check switch model
      debug: 
       msg: "{{ ansible_net_model }}"
      register: switch_model

    - name: get the model names into new_model_names var
      set_fact:
        new_model_names: "{{ new_models | json_query('[].name') }}"

    - name: Clear range of counters
      ios_command:
        commands:
          - command: clear counters gigabitEthernet {{ start }}/{{ middle }}/{{ item }}
            prompt: Clear "show interface" counters on this interface \[confirm\]
            answer: y
      with_sequence: start="{{ ifacefrom }}" end="{{ ifaceto }}"
      when: switch_model.msg in new_model_names

推荐阅读