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

编写Ansible Playbook检查/home目录用户磁盘使用率遇错误求助

问题原因

错误的核心是Ansible的command模块不会通过shell解析通配符*——它会把/home/*当作一个字面量的文件名去查找,而非展开为/home下的所有子目录,因此du命令找不到对应的路径,返回错误。

另外,你已经在playbook中设置了become: true,无需在命令中重复使用sudo,这属于冗余操作。

解决方案

方案1:改用shell模块(快速修复)

shell模块会通过系统的/bin/sh执行命令,支持shell通配符解析,修改后的playbook如下:

---
- name: User Home Directory Stat
  hosts: linux7
  become: true

  tasks:
    - name: Check user home directory disk utilization
      ansible.builtin.shell: du -sh /home/*
      register: msg
    - debug:
        var: msg.stdout_lines

方案2:使用find模块(Ansible最佳实践)

如果需要更精准的目录控制(比如排除特定目录、处理空/home场景),推荐用find模块先获取所有用户目录,再循环执行du命令:

---
- name: User Home Directory Stat
  hosts: linux7
  become: true

  tasks:
    - name: Fetch all user home directories
      ansible.builtin.find:
        path: /home
        file_type: directory
        recurse: no
      register: home_directories

    - name: Calculate disk usage for each directory
      ansible.builtin.command: du -sh {{ item.path }}
      register: disk_usage_results
      loop: "{{ home_directories.files }}"

    - name: Display disk utilization
      ansible.builtin.debug:
        msg: "{{ item.stdout }}"
      loop: "{{ disk_usage_results.results }}"

这种方式能避免shell通配符的依赖,同时让逻辑更清晰,便于后续扩展(比如添加条件判断过滤目录)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 10:05:23