mgmt/deployment/ansible/playbooks/disk/disk-cleanup.yml

96 lines
2.8 KiB
YAML

---
- name: 磁盘清理工具
hosts: all
become: yes
vars:
cleanup_logs: true
cleanup_cache: true
cleanup_temp: true
cleanup_containers: false # 谨慎操作
tasks:
- name: 检查磁盘使用情况 (清理前)
shell: df -h
register: disk_before
- name: 显示清理前磁盘使用情况
debug:
msg: |
=== {{ inventory_hostname }} 清理前磁盘使用情况 ===
{{ disk_before.stdout }}
- name: 清理系统日志 (保留最近7天)
shell: |
journalctl --vacuum-time=7d
find /var/log -name "*.log" -type f -mtime +7 -exec truncate -s 0 {} \;
find /var/log -name "*.log.*" -type f -mtime +7 -delete
when: cleanup_logs | bool
register: log_cleanup
- name: 清理包管理器缓存
block:
- name: 清理 APT 缓存 (Debian/Ubuntu)
shell: |
apt-get clean
apt-get autoclean
apt-get autoremove -y
when: ansible_os_family == "Debian"
- name: 清理 YUM/DNF 缓存 (RedHat/CentOS)
shell: |
if command -v dnf >/dev/null 2>&1; then
dnf clean all
elif command -v yum >/dev/null 2>&1; then
yum clean all
fi
when: ansible_os_family == "RedHat"
when: cleanup_cache | bool
- name: 清理临时文件
shell: |
find /tmp -type f -atime +7 -delete 2>/dev/null || true
find /var/tmp -type f -atime +7 -delete 2>/dev/null || true
rm -rf /tmp/.* 2>/dev/null || true
when: cleanup_temp | bool
- name: 清理 Podman 资源 (谨慎操作)
block:
- name: 停止所有容器
shell: podman stop --all
ignore_errors: yes
- name: 删除未使用的容器
shell: podman container prune -f
ignore_errors: yes
- name: 删除未使用的镜像
shell: podman image prune -f
ignore_errors: yes
- name: 删除未使用的卷
shell: podman volume prune -f
ignore_errors: yes
when: cleanup_containers | bool
- name: 清理核心转储文件
shell: |
find /var/crash -name "core.*" -type f -delete 2>/dev/null || true
find / -name "core" -type f -size +10M -delete 2>/dev/null || true
ignore_errors: yes
- name: 检查磁盘使用情况 (清理后)
shell: df -h
register: disk_after
- name: 显示清理结果
debug:
msg: |
=== {{ inventory_hostname }} 清理完成 ===
清理前:
{{ disk_before.stdout }}
清理后:
{{ disk_after.stdout }}
🧹 清理操作完成!