使用 ansible 管理磁盘空间 [英] Using ansible to manage disk space

查看:47
本文介绍了使用 ansible 管理磁盘空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简单的问题:如果分区利用率超过一定百分比,我想删除一些文件.

Simple ask: I want to delete some files if partition utilization goes over a certain percentage.

我可以通过ansible_mounts"访问size_total"和size_available".即:

I have access to "size_total" and "size_available" via "ansible_mounts". i.e.:

ansible myhost -m setup -a 'filter=ansible_mounts'
myhost | success >> {
"ansible_facts": {
    "ansible_mounts": [
        {
            "device": "/dev/mapper/RootVolGroup00-lv_root", 
            "fstype": "ext4", 
            "mount": "/", 
            "options": "rw", 
            "size_available": 5033046016, 
            "size_total": 8455118848
        }, 

如何访问这些值,以及如何使用 Ansible 基于它们有条件地执行操作?

How do I access those values, and how would I perform actions conditionally based on them using Ansible?

推荐答案

Slava 的回答绝对是正确的,这是我使用的:

Slava's answer definitely was on the right track, here is what I used:

- name: test for available disk space
  assert:
    that: 
      - not {{ item.mount == '/' and ( item.size_available < item.size_total - ( item.size_total|float * 0.8 ) ) }}
      - not {{ item.mount == '/var' and ( item.size_available < item.size_total - ( item.size_total|float * 0.8 ) ) }}
  with_items: ansible_mounts
  ignore_errors: yes
  register: disk_free

- name: free disk space
  command: "/some/command/that/fixes/it"
  when: disk_free|failed

assert 任务只是简单地测试条件,通过设置 ignore_errors,并将测试结果注册到一个新变量,我们可以在稍后执行一个有条件的任务,而不是在断言结果失败时失败.

The assert task simply tests for a condition, by setting ignore_errors, and registering the result of the test to a new variable we can perform a conditional task later in the play instead of just failing when the result of the assert fails.

测试本身可能可以更有效地编写,但以可读性为代价.所以我没有在示例中使用多列表循环.在这种情况下,任务会遍历已挂载文件系统列表中的每一项(ansible 创建的事实,称为 ansible_mounts.)

The tests themselves could probably be written more efficiently, but at the cost of readability. So I didn't use a multiple-list loop in the example. In this case the task loops over each item in the list of mounted filesystems (an ansible-created fact, called ansible_mounts.)

通过否定测试,我们避免了不在我们列表中的文件系统挂载失败,然后简单的数学处理剩下的.令我失望的部分是 size_available 和 size_total 变量是字符串,因此 jinja 过滤器在计算百分比之前将它们转换为浮点数.

By negating the test we avoid failing on file system mounts not in our list, then simple math handles the rest. The part that tripped me up was that the size_available and size_total variables were strings, so a jinja filter converts them to a float before calculating the percentage.

这篇关于使用 ansible 管理磁盘空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆