Using ansible to manage disk space

Question:

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

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

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

Answer:

Here is what I used:

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.

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.)

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.

Leave a Reply