Ansible如何生成符合指定条件的Cisco设备主机信息列表
实现方案
步骤1:为每台设备设置NTP同步状态的布尔fact
修改你现有NTP检查任务,新增set_fact任务为每台主机标注同步状态,该任务可并行执行无需串行:
- name: CHECK NTP STATUS ios_command: commands: - show ntp status register: ntp_status - name: SET NTP SYNC STATUS FACT set_fact: ntp_synched: "{{ 'Clock is synchronized' in ntp_status.stdout[0] }}"
步骤2:集中提取符合条件的设备信息生成列表
在所有设备的NTP检查任务完成后,新增运行在控制节点的任务,通过Ansible内置hostvars全局变量拉取所有设备的事实,筛选生成目标列表:
- name: GENERATE NTP SYNCED DEVICE LIST run_once: yes delegate_to: localhost set_fact: ntp_synced_devices: >- {% set device_list = [] %} {% for host in groups['替换为你的思科设备Inventory组名'] %} {% if hostvars[host].ntp_synched | default(false) %} {% set _ = device_list.append({ 'hostname': hostvars[host].ansible_net_hostname | default(host), 'ansible_host': hostvars[host].ansible_host | default(host) }) %} {% endif %} {% endfor %} {{ device_list }}
如果需要筛选所有Inventory主机,把组名替换为all即可。
(可选)生成CSV文件
直接通过copy模块把列表导出为CSV文件:
- name: EXPORT TO CSV run_once: yes delegate_to: localhost copy: content: | hostname,ansible_host {% for dev in ntp_synced_devices %} {{ dev.hostname }},{{ dev.ansible_host }} {% endfor %} dest: ./ntp_synced_devices.csv
内容的提问来源于stack exchange,提问作者sTz
相关产品推荐
相关产品推荐

