2

I want to make a list of servers that don't have a particular file.

I made the following Ansible playbook:

 - name: "If file not in /apps"
   hosts: all
   tasks:

    - name: Find apps
      find:
        paths: /apps/
        patterns: "*"
        file_type: directory
      register: apps

    - name: Show file paths
      with_items: "{{ apps.files }}"
      debug:
        msg: "{{ item.path }}"

This returns a message with the app directories. I would like to check if a certain file is present in a subfolder, and if the file is not present, I want to run a script.

A pseudocode example of what I want:

for folder in "/apps/*":    
    if file not in folder:
        print(item.path)

How do I do that? I just can't find anything and I've been trying for several hours now.

The target server

Paul
  • 3,037
  • 6
  • 27
  • 40
yes
  • 31
  • 1
  • 6

1 Answers1

2

Regarding your question

I would like to check if a certain file is present in a subfolder, and if the file is not present

you may use the following approach.

---
- hosts: test
  become: false
  gather_facts: false

  vars:

    SEARCH_PATH: "/home/user"
    SEARCH_FILE: "test.txt"

  tasks:

  - name: Check if file exists
    stat:
      path: "{{ SEARCH_PATH }}/{{ SEARCH_FILE }}"
    register: result

  - name: Show result
    debug:
      msg: "The file does not exist!"
    when: not result.stat.exists

  - name: Show result
    debug:
      msg: "The file does exist!"
    when: result.stat.exists

resulting into an output of

TASK [Show result] ************
ok: [test.example.com] =>
  msg: The file does not exist!

or

TASK [Show result] ********
ok: [test.example.com] =>
  msg: The file does exist!

depending on when the file under /home/user or the path exists at all.

Thanks to further Q&A

Documentation

U880D
  • 1,017
  • 2
  • 12
  • 18
  • Thank you! The problem is that the file has version numbering at the end, and not necessarily the same version number. `stat` cannot deal with that, right? I would also like a list of apps without the file but that is trivial to add I'd say. Although I don't quite understand how to select just the path from the result of the `find` method. – yes Jul 10 '22 at 21:32
  • `stat` will need the directory or filename. To get just the path from a `find` result without the filename you can use the filter `result.path | basename `. – U880D Jul 11 '22 at 06:12