You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 23:15:03