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

Ansible动态Inventory创建后,第二个Play提示无匹配主机的问题

问题原因分析

你遇到的「skipping: no hosts matched」问题,核心是第二个Play无法正确识别第一个Play通过add_host动态创建的targets组,同时任务中存在变量引用错误。

修正步骤

  1. 修复变量引用错误
    第二个Play里的with_items: "{{targets}}"是无效写法——targets不是可直接调用的变量,组内的主机列表需要通过全局变量groups.targets来引用。修改后的任务:
- name: Print the dynamic inventory
  debug:
    msg: "{{ item }}"
  with_items: "{{ groups.targets }}"
  1. 验证动态组加载状态
    在第二个Play开头添加debug任务,确认targets组是否被正确加载到全局inventory中:
- name: Sequential tasks
  hosts: targets
  gather_facts: false
  connection: local
  serial: 1

  tasks:
    - name: Check if targets group exists
      debug:
        var: groups.targets

    - name: Print each target host
      debug:
        msg: "{{ item }}"
      with_items: "{{ groups.targets }}"

    - name: Ping Server if it is part of the dynamic inventory
      import_role:
        name: ping
  1. 确认add_host的有效性
    add_host是全局生效模块,会将主机添加到整个Playbook的inventory中。如果依然无法识别,检查两个关键点:

    • 第一个Play的when: item.id == another.id条件是否确实匹配到目标服务器;
    • item.fqdn是否返回了格式正确的主机名(避免空值或无法解析的字符串)。
  2. 排查版本兼容性
    部分旧版本Ansible在动态inventory处理上存在bug,尝试升级到2.10及以上的稳定版本,验证是否解决问题。

完整可运行Playbook示例

---
- name: Create dynamic inventory
  hosts: mgmt-vip.us.acme.com
  gather_facts: false
  tasks:
    - name: Create dynamic inventory by combining facts from previous tasks
      add_host:
        name: "{{ item.fqdn }}"
        groups: targets
      with_items: "{{ server_details }}"
      when: item.id == another.id
      no_log: true

    - name: Print the dynamic inventory from first play
      debug:
        var: groups.targets

- name: Sequential tasks
  hosts: targets
  gather_facts: false
  connection: local
  serial: 1

  tasks:
    - name: Verify targets group is available
      debug:
        var: groups.targets

    - name: Print each target host
      debug:
        msg: "Processing host: {{ item }}"
      with_items: "{{ groups.targets }}"

    - name: Ping Server if it is part of the dynamic inventory
      import_role:
        name: ping

内容的提问来源于stack exchange,提问作者piercjs

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 08:12:49