英文:
Using Stat module on multiple files and using a map
问题
- name: 使用 stat 模块检查多个文件并注册结果
 
  - name: 检查 ST 是否成功停止
    stat:
      path: "{{ item }}"
    loop:
      - /var/run/sshd.pid
      - /var/run/httpd.pid
      - /var/run/db.pid
    register: status_stopped
当这些文件未找到或 stat 显示它们不存在时,我想执行以下任务:
  - name: 清空 Axway 临时目录
    shell: rm -rf /var/tmp/*
    when: not status_stopped.results|map(attribute='stat.exists.false')|bool
当文件存在时,步骤仍然执行。是否有更好的处理方式?
英文:
I am using the stat module to check for multiple files and register the result
  - name: Check if ST was successfully stopped
    stat:
      path: "{{ item }}"
    loop:
      - /var/run/sshd.pid
      - /var/run/httpd.pid
      - /var/run/db.pid
    register: status_stopped
When these files are not found or stat states they do not exist, I want to perform a task like so:
  - name: Clear out Axway tmp directory
    shell: rm -rf /var/tmp/*
    when: not status_stopped.results|map(attribute='stat.exists.false')|bool
When the files exists, the step still executes. Is there a better way to handle this?
答案1
得分: 1
以下是翻译的内容:
作为对您问题的直接回答:
  - name: 当所有文件都不存在时,假装执行某些操作
    ansible.builtin.debug:
      msg: "所有文件都不存在。我必须执行的操作"
    when: not (status_stopped.results | map(attribute='stat.exists')) is all
参考链接: 测试列表值是否为真
进一步说:
- 使用
shell来删除文件是不好的实践。使用file模块 并设置state: absent。 - 通过在 
/var/run中的文件存在来检查服务是否正在运行是不好的实践。应正确地在操作系统中注册您的服务,并如 @U880D 在评论中提到的,使用service_facts,service,systemd,sysvinit... 取决于您的环境和需求。 
英文:
As a direct answer to your question:
  - name: Pretend to do something when all files are absent
    ansible.builtin.debug:
      msg: "All files are absent. Doing what I have to do"
    when: not (status_stopped.results | map(attribute='stat.exists')) is all
Reference: Testing if a list value is true
To go further:
- Removing files with 
shellis a bad practice. Use thefilemodule withstate: absent - Checking a service is running by presence of a file in 
/var/runis a bad practice. Register your services correctly in your OS and as already reported by @U880D in comments, useservice_facts,service,systemd,sysvinit... depending on your environment and requirement. 
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论