问题原文
原帖链接 · yes · CC BY-SA 4.0
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.
社区高分解答
原帖链接 · U880D · CC BY-SA 4.0
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
- How to check if a file exists in Ansible?
- Ansible: Include task only if file exists
- How can I run a Ansible task only if a file or directory does NOT exist?
- Ansible: Test to check file exists
Documentation
摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。
