Reputation: 144
I have created below playbook to archive log files on remote server. The script perform based on the key work in the host file.
tasks:
- name: Create a tar.gz archive of log files.
archive:
path:
- "{{item.path}}"
dest: "{{item.dest}}"
format: gz
force_archive: yes
owner: ubuntu
become: true
when: "inventory_hostname is search(item.key)"
with_items:
- {path: "/var/log/grafana/grafana.log", dest: "/tmp/grafana.log.gz", key: "grafana"}
Is it possible to archive the files based on a date variable. For example, if I pass the date 11-11-2020 at the time of execution, then the script has to archive only the file created at this date?
Upvotes: 1
Views: 1202
Reputation: 1954
stat
module to retrieve facts for files, this module reaturns ctime
value wich is Time of last metadata update or creation (depends on OS)
and register the return values on a variable.archive
task use wiht_nested
with files
and file_data
with a when condition where validate the items of both are the same and the ctime
is equal to a date
variable.date
variable as extra-vars
.playbook.yml
- name: Archive files
hosts: all
gather_facts: no
vars:
files:
- {path: "/home/vagrant/l1.txt", dest: "/tmp/grafana.log.gz", key: "grafana"}
- {path: "/home/vagrant/l2.txt", dest: "/tmp/grafana.log.gz", key: "grafana"}
- {path: "/etc/host.conf", dest: "/tmp/grafana.log.gz", key: "grafana"}
tasks:
- name: Get file data
stat:
path: "{{ item.path }}"
with_items: "{{ files }}"
register: file_data
- name: Create a tar.gz archive of log files.
archive:
path: "{{item[0].path}}"
dest: "{{item[0].dest}}"
format: gz
force_archive: yes
owner: ubuntu
become: true
when: "inventory_hostname is search(item[0].key) and item[0].path == item[1].stat.path and '%d-%m-%Y' | strftime(item[1].stat.ctime) == {{ date }}"
with_nested:
- "{{ files }}"
- "{{ file_data.results }}"
Execute playbook
ansible-playbook playbook.yml -i inventory -e "date='11-11-2020'"
Upvotes: 2