Science and technology

How I maintain my file folders tidy with Ansible

I attempt to use Ansible usually, even for duties that I understand how to do with a shell script as a result of I do know that Ansible is simple to scale. Even although I would develop an Ansible playbook only for my private workstation, typically it finally ends up being much more helpful than meant, and it is simple to use that very same playbook to all of the computer systems on my community. And in addition to, typically the best enemy of getting actually good at one thing is the impression that it is solely meant for severe professionals, or massive initiatives, or no matter you are feeling that you simply’re not. I take advantage of Ansible as a result of it is an ideal open supply instrument, however I profit from it essentially the most as a result of it scales.

One of the duties I not too long ago assigned to Ansible was the monumental one in every of maintaining my Downloads folder tidy. If you are like me, you find yourself downloading many information from the Internet all through the day after which neglect that the information exist. On the one hand, I do not thoughts this behavior. There have been occasions after I understand I nonetheless want a file in my Downloads folder, so forgetting a couple of file moderately than promptly eradicating it may be useful. However, there are different information that I obtain expressly to make use of as soon as after which must take away.

I made a decision to make use of a extremely particular Ansible process to seek out information I do know I do not want after which take away them.

Ansible boilerplate

Ansible playbooks typically begin in precisely the identical means: Define your hosts and announce a process:

---
- hosts
: localhost
  duties:

Commit these three traces to reminiscence. They’re the “shebang” (#!) of Ansible playbooks. Once you could have these traces in a textual content file, you can begin defining the steps in your process.

Finding information with Ansible

You can find information on a system utilizing the find Ansible module. If an Ansible module is a command, its parameters are its command options. In this instance playbook, I need to discover information explicitly positioned within the ~/Downloads folder and I can outline that utilizing the paths parameter.

This is my course of after I begin writing a playbook: I discover a module within the Ansible module index that appears prone to do what I want, after which I learn by means of its parameters to seek out out what sort of management I’ve over the module.

In my case, the information I by accident acquire in my Downloads folder are CSV information. They get downloaded weekly, processed, after which must disappear. But they grasp round for weeks till I get overwhelmed and delete them. Here’s the right way to discover CSV information in Downloads with Ansible:

---
- hosts
: localhost
  duties
:
    - title
: Find CSV in Downloads
      discover
:
        paths
: ~/Downloads
        recurse
: false
        patterns
: '*.csv,*.CSV'
      register
: consequence

The paths parameter tells Ansible the place to seek for information.

The recurse: false parameter forbids Ansible from looking out in subdirectories of Downloads. This offers me the power to retain CSV information that I’ve downloaded and saved right into a subdirectory. Ansible solely targets the CSV information I save straight to Downloads (which is my behavior).

The patterns parameter tells Ansible what to rely as a match. All of the CSV information I obtain finish in .csv, however I am assured that I am prepared to take away .CSV (in all capital letters) as nicely.

The of entirety to this step is to invoke the register module, which saves the outcomes of the discover course of right into a variable known as consequence.

This is necessary as a result of I would like Ansible to carry out a second motion on the outcomes of discover, so these outcomes must be saved someplace for the subsequent step.

Removing information with Ansible

The subsequent step within the process is to take away the information that discover has uncovered. The module used to take away information is the file module.

This step depends completely on the discover step, so it makes use of a number of variables:

    - title: Remove CSV information
      file
:
        path
: " item.path "
        state
: absent
      with_items
: ""

The path parameter makes use of the built-in " item.path " variable, which confusingly is not really outlined but. The variable has no data on the trail till the file module is utilized in a loop by the with_items key phrase. The with_items step makes use of the contents of the consequence variable to extract one filename at a time, which turns into the merchandise for the path parameter. Once the present merchandise’s path is extracted, Ansible makes use of the state: absent rule to make sure that the file positioned at that path is not left on the system (in different phrases, it is deleted.)

This is a very harmful step, particularly throughout testing. If you get this step fallacious, you possibly can simply take away information you do not intend to delete.

Verify the playbook 

Ansible playbooks are written in YAML, which has a strict syntax. Verify that your YAML is appropriate utilizing the yamllint command:


No outcomes means no errors. This playbook should have been written by somebody who actually knows and loves YAML!

Testing Ansible performs safely

To keep away from deleting my total house listing by chance, I ran my first try with the --check choice. This ensures that Ansible does not really make adjustments to your system.

$ ansible-playbook --check instance.yaml
[WARNING]: supplied hosts listing is empty, solely localhost is on the market.
'all'

PLAY [localhost] ****************************************************

TASK [Gathering Facts] **********************************************
okay: [localhost]

TASK [Find CSV information in Downloads] **********************************
okay: [localhost]

TASK [Remove CSV information] *********************************************
modified: [localhost] => (merchandise={'path': '/house/tux/Downloads/foo.csv', [...]
modified: [localhost] => (merchandise={'path': '/house/tux/Downloads/bar.csv', [...]
modified: [localhost] => (merchandise={'path': '/house/tux/Downloads/baz.csv', [...]

PLAY RECAP **********************************************************
localhost                  : okay=three    modified=1    unreachable=zero [...]

The output could be very verbose, however it reveals that my playbook is appropriate: Only CSV information inside Downloads have been marked for removing.

Running Ansible playbooks

To run an Ansible playbook, you utilize the ansible-playbook command:

$ ansible-playbook instance.yaml

Confirm the outcomes:

$ ls *.csv  ~/Downloads/
ls: can't entry '*.csv': No such file or listing
/house/tux/Downloads/:
file.txt

Schedule the Ansible playbook

The Ansible playbook has been confirmed, however I would like it to run not less than each week. I take advantage of Anacron moderately than Cron, so I created an Anacron job to run weekly:

$ cat << EOF >> ~/.native/and so on/cron.weekly/cleanup
#!/bin/sh
ansible-playbook $HOME/Ansible/cleanup.yaml
EOF
$ chmod +x ~/.native/and so on/cron.day by day/cleanup

What are you able to do with Ansible?

Generally, Ansible is supposed as a system upkeep instrument. It’s finely tuned to bootstrap complicated programs to assist with course correction when one thing’s gone fallacious and to maintain a system in a particular state. I’ve used it for easy however repetitive duties, like establishing a fancy listing tree that will sometimes require a number of instructions or clicks. I’ve additionally used it for duties I do not need to do fallacious, like eradicating outdated information from directories. I’ve additionally used it for duties which can be simply too complicated for me to trouble attempting to recollect, like synchronizing a number of adjustments made to a manufacturing system with its redundant backup system.

I do not use this cleanup script on my servers as a result of I do not obtain CSV information each week on my servers, however I do use a variation of it. Ansible is not a alternative for shell or Python scripting, however for some duties, it is a very exact methodology to carry out some set of duties that you simply would possibly need to run on many extra programs.

Most Popular

To Top