ansible - 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 组合成一个循环?我也试过这个,但我无法弄清楚这个的语法......
解决方案
根据您的问题,我的理解是,您希望ios_command
仅switch_model.msg
在new_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
推荐阅读
- python - 仅对系数子集的python线性回归非负限制
- c++ - 无法让我的排序规则适合 std::map
- google-apps-script - 使用 Google App 脚本的 Twilio 彩信不起作用
- android - 无法解决:support-v4
- javascript - 传递多个字段值并通过 HTML 链接提交
- bash - 如何找到我在 ubuntu 上升级节点的时间?
- javascript - 用于聊天应用程序的 Mongodb 架构
- java - 等效的 lambda 表达式,用于获取列表中每个对象的属性
- php - Laravel 计数车辆 W/O 图像
- mysql - 使用命令提示符执行 MySQL 存储过程的命令