大网数据广告活动
服务器运维问答

How to perform an action when a file is not present with Ansible?

· 52CE 我爱测

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 …

问题原文

原帖链接 · 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

Documentation

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2022-07-07)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。