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

Ansible第二Play出现‘skipping: no hosts matched’的原因及解决方法

Ansible Playbook问题:第二个Play出现skipping: no hosts matched的原因及解决方案

问题背景

我有一个包含2个Play的Ansible Playbook:

  • 第一个Play:通过shell模块执行命令,将清单中指定主机的输出保存到控制节点(localhost)的结果文件中
  • 第二个Play:仅在控制节点运行,用于修改该结果文件的所有权权限

Playbook代码:

---
 - name: Run and save shell command - 1st play
   hosts: all
   gather_facts: False
   serial: 10
   become_flags: -i
   become: yes

   vars:
    res: "/home/myuser/test"

   tasks:
     - name: run shell command
       shell: 'pwd'
       register: myshellout

     - name: save output
       shell: echo -e "{{ inventory_hostname }}{{ myshellout.stdout }}\n" >> "{{ res }}"
       delegate_to: localhost

 - name: change ownership - 2nd play
   hosts: localhost
   gather_facts: no
   tasks:
     - name: change ownership task
       file:
         path: "{{ res }}"
         owner: myuser
         group: myuser
      #  delegate_to: localhost
      #  run_once: true

执行命令:

ansible-playbook -i myinventory -e 'res=/home/myuser/mycustomfile' --limit 'host1,host2,host3' myansibleplaybook.yml

执行后第二个Play出现skipping: no hosts matched提示,需要明确原因及实现“修改所有权的任务仅在剧本末尾执行一次”的方法。

原因分析

--limit参数会作用于整个Playbook的所有Play,你指定了仅在host1,host2,host3上执行任务,但第二个Play的目标主机是localhost,该主机不在你指定的limit列表内,因此Ansible会跳过这个Play,触发skipping: no hosts matched的提示。

解决方案

以下是两种简洁有效的解决方式,任选其一即可:

方案1:给第二个Play添加limit: localhost参数

通过在第二个Play中添加limit: localhost,覆盖全局的--limit限制,确保localhost不受外部limit参数影响:

- name: change ownership - 2nd play
  hosts: localhost
  gather_facts: no
  limit: localhost  # 新增该行,强制针对localhost执行
  tasks:
    - name: change ownership task
      file:
        path: "{{ res }}"
        owner: myuser
        group: myuser

方案2:将权限修改任务合并到第一个Play的post_tasks中

把权限修改任务放到第一个Play的post_tasks区块,配合run_once: true和delegate_to: localhost,确保任务在所有目标主机的主任务执行完成后仅执行一次:

---
 - name: Run and save shell command - 1st play
   hosts: all
   gather_facts: False
   serial: 10
   become_flags: -i
   become: yes

   vars:
    res: "/home/myuser/test"

   tasks:
     - name: run shell command
       shell: 'pwd'
       register: myshellout

     - name: save output
       shell: echo -e "{{ inventory_hostname }}{{ myshellout.stdout }}\n" >> "{{ res }}"
       delegate_to: localhost

   # 新增post_tasks区块,在所有主机任务执行完成后运行
   post_tasks:
     - name: change ownership task
       file:
         path: "{{ res }}"
         owner: myuser
         group: myuser
       delegate_to: localhost
       run_once: true  # 确保任务仅执行一次

这种方式无需单独的第二个Play,逻辑更紧凑,且符合“在剧本末尾执行一次”的需求。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 04:10:25