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

Ansible问题:使用gather_subset无法获取含下划线的事实信息

问题:Ansible挂载信息报告无法获取带下划线的字段(如size_total)

问题现象

  • 尝试生成包含mount.device、mount.mount和mount.size_total的CSV报告
  • 只要不包含带下划线的字段(如size_total、inode_total、block_size),Playbook可正常运行
  • 添加这类带下划线的字段时,会抛出变量未定义错误

错误信息

failed | msg: The task includes an option with an undefined variable. The error was: 'dict object' has no attribute 'size_total'

预期输出

localhost,/dev/mapper/sda1,/boot,533377024

使用的Playbook代码

---

  - name: make a csv file
    hosts: g3prdapp
    gather_facts: false

    tasks:

      - ansible.builtin.setup:
          gather_subset:
            - all_ipv4_addresses
            - mounts
            - user_id

      - debug:
          var: ansible_mounts

      - debug:
          var: ansible_all_ipv4_addresses

      - debug:
          var: ansible_user_id

      - copy:
          dest: mount_output.csv
          content: |
            hostname,filesystem,mountpoint,size_total
            {% for hostname in ansible_play_hosts %}
            {% for mount in hostvars[hostname]['ansible_mounts'] %}
            {{ hostname }},{{ mount.device }},{{ mount.mount }},{{ mount.size_total }}
            {% endfor %}
            {% endfor %}
#        run_once: true
        delegate_to: localhost

问题原因及解决方法

原因分析

Ansible的setup模块在指定gather_subset: mounts时,默认只会收集挂载点的基础信息,不会自动获取磁盘容量、inode这类统计数据,需要显式配置收集相关子集。

解决步骤

  1. 修改setup模块收集范围
    在gather_subset中添加hardware子集,该子集包含挂载点的容量、inode等统计信息:

    - ansible.builtin.setup:
        gather_subset:
          - all_ipv4_addresses
          - mounts
          - user_id
          - hardware
    

    若想精准控制收集内容,可使用filter参数指定需要的字段:

    - ansible.builtin.setup:
        gather_subset:
          - all_ipv4_addresses
          - mounts
          - user_id
        filter:
          - ansible_mounts
          - ansible_mounts.*size*
          - ansible_mounts.*inode*
    
  2. 添加默认值容错处理
    为避免个别特殊挂载点缺失字段导致报错,可在模板中给变量添加默认值:

    {{ hostname }},{{ mount.device }},{{ mount.mount }},{{ mount.size_total | default('N/A') }}
    

修改完成后,Playbook即可正常获取size_total等带下划线的挂载统计字段,生成符合预期的CSV报告。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 17:12:55