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?
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.
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.
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 .
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.
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
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With