Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform Ansible task if given directory is not empty?

I am using Ansible to move logs to backup directory (using shell module, mv command).

mv command fails if there are no files to move. By default, it causes whole Ansible play to fail. I can proceed with play, even if task fails (ignore_errors: yes)

I am not satisfied with this solution, because it produces error message

TASK [move files to backup directory] ****************************************** fatal: [xx.xx.xx.xx]: FAILED! =...?No such file or directory", "stdout": "", "stdout_lines": [], "warnings": []} ...ignoring

How to check if directory is empty in Ansible, and if empty jus skip task?

like image 543
Bartosz Bilicki Avatar asked May 19 '16 10:05

Bartosz Bilicki


People also ask

How do you know if a variable is empty in Ansible?

I use | trim != '' to check if a variable has an empty value or not. I also always add the | default(..., true) check to catch when myvar is undefined too.

Can an empty file be created in Ansible if yes how?

Creating an empty file in AnsibleYou can Create an empty file using the file module. You just need to set two parmaters. Path – This is the location where you want the file to be created. It can be either a relative path or an absolute path.

How do I run Ansible tasks once?

The easiest way to run only one task in Ansible Playbook is using the tags statement parameter of the “ansible-playbook” command. The default behavior is to execute all the tags in your Playbook with --tags all .

How do you handle fatal errors in Ansible?

If you set any_errors_fatal and a task returns an error, Ansible finishes the fatal task on all hosts in the current batch, then stops executing the play on all hosts. Subsequent tasks and plays are not executed. You can recover from fatal errors by adding a rescue section to the block.


2 Answers

You can use find module in ansible 2.0 to find files with .log extension in directory then execute move if files is found

- find: paths=DIRECTORY file_type=directory patterns="*.log"
  register: dir_files

- shell: mv *.log /tmp
  when: dir_files.matched|int != 0
like image 191
Nasr Avatar answered Sep 26 '22 07:09

Nasr


There is accepted answer that uses find module.

Another option (less readable and more verbose) is to use native Linux commands- test result of ls command

- name: "backup logs"
  shell: test "$(ls /var/logs/)"
  register: logsPresent
  changed_when: false

- name: "move files to backup directory"
  when: "logsPresent.rc != 0"
  shell: "mv /var/logs/ /backup/logs"
like image 20
Bartosz Bilicki Avatar answered Sep 23 '22 07:09

Bartosz Bilicki