anarchist
anarchist

Reputation: 393

check if file/folder exists and perform actions in ansible

I have the following code:

- name: check if file/folder exists
  stat:
    path: "{{ item }}"
  register: check_file
  with_items:
  - ['{{ source_folder }}','/etc/file', '/usr/file', '/root/dir', '/etc/test']

- debug:
    msg: "{{ check_file }}"
    #msg: "{{ check_file.stat.exists }}"
    #msg: "{{ check_file.results }}"

- name: Backup files
  copy:
   src: "{{ item }}"
   dest: "{{ backup_folder }}/{{ datetime }}/files"
  with_items:
  - ['{{ source_folder }}','/etc/file', '/usr/file', '/root/dir', '/etc/test']
  ignore_errors: "{{ not failure_is_critical }}

What I'm trying to do is check for the files/folders and if they don't exist continue the backup and write some info in the logs, something like:

folder1 found - OK
file1   found - OK
folder2 not found -skipping
file2   not found -skipping

And at the end show a result of full backup (success) or partial backup (fail)

Upvotes: 0

Views: 7304

Answers (2)

anarchist
anarchist

Reputation: 393

I wrote it like this to get the result:

- name: Set check files result
  set_fact:
    store_check_file: "{{ check_file.results | map(attribute='stat.exists') | list }}"

- name: Set backup result
  set_fact:
    backup_result: "{{ 'partial' if false in store_check_file else 'full'}}"

Then i can print it with debug

Upvotes: 0

tassinp
tassinp

Reputation: 954

maybe your can try this : loop onto your stat results, and add condition of existence for each item

- name: Backup files
  copy:
    src: "{{ 'item.stat.path }}"
    dest: "{{ backup_folder }}/{{ datetime }}/files"
  loop: "{{ check_file.results }}"
  when: item.stat.exists      
  ignore_errors: "{{ not failure_is_critical }}

[EDIT] replaced item.item.name with item.stat.path like suggested by @anarchist

Upvotes: 4

Related Questions