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

Ansible使用set_fact赋值报错:item未找到,请求协助解决

问题原因

第二个set_fact任务未启用循环,但模板中引用了item变量——item是仅在loop循环任务的上下文里才会生成的变量,脱离循环后直接引用必然会提示「item未找到」。

另外第一个任务注册的soe_checks是包含循环结果的对象,所有单个路径的检查结果都存储在soe_checks.results列表中,必须遍历这个列表才能获取每个路径的stat信息。

解决方案

根据不同需求,提供两种常见修正方式:

方式1:记录每个目录的存在状态(字典形式)

如果需要把每个路径是否为目录的结果存成键值对,修改set_fact任务如下:

- name: Set facts for each directory
  ansible.builtin.set_fact:
    soe_dirs: "{{ soe_dirs | default({}) | combine({ item.item: item.stat.isdir | string }) }}"
  loop: "{{ soe_checks.results }}"

执行后,soe_dirs变量会生成类似这样的字典:

{
  "/opt/test1": "True",
  "/opt/test2": "False",
  "/opt/test3": "True"
}

方式2:判断所有目录是否都存在(布尔值)

如果需要判断所有指定目录都存在且是目录时才将soe设为true,否则设为false,可直接用Jinja2过滤器实现,无需循环:

- name: Set fact for all directories status
  ansible.builtin.set_fact:
    soe: "{{ soe_checks.results | map(attribute='stat.isdir') | all | string }}"
  • map(attribute='stat.isdir'):提取所有结果中的stat.isdir布尔值
  • all:判断所有值是否都为True
  • string:将布尔值转为字符串形式的"True"/"False"
完整修正Playbook示例(以方式1为例)
- name: set facts identification
  hosts: all
  gather_facts: false
  become: true
  vars:
    dir_path:
      - /opt/test1
      - /opt/test2
      - /opt/test3
  tasks:
    - name: Check directory status
      ansible.builtin.stat:
          path: "{{ item }}"
      loop: "{{ dir_path }}"
      register: soe_checks
      
    - name: Set facts for each directory
      ansible.builtin.set_fact:
        soe_dirs: "{{ soe_dirs | default({}) | combine({ item.item: item.stat.isdir | string }) }}"
      loop: "{{ soe_checks.results }}"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 20:22:19