使用Stat模块在多个文件上并使用映射函数。

huangapple go评论54阅读模式
英文:

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

参考链接: 测试列表值是否为真

进一步说:

  1. 使用shell 来删除文件是不好的实践。使用 file 模块 并设置 state: absent
  2. 通过在 /var/run 中的文件存在来检查服务是否正在运行是不好的实践。应正确地在操作系统中注册您的服务,并如 @U880D 在评论中提到的,使用 service_factsservicesystemdsysvinit... 取决于您的环境和需求。
英文:

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:

  1. Removing files with shell is a bad practice. Use the file module with state: absent
  2. Checking a service is running by presence of a file in /var/run is a bad practice. Register your services correctly in your OS and as already reported by @U880D in comments, use service_facts, service, systemd, sysvinit... depending on your environment and requirement.

huangapple
  • 本文由 发表于 2023年3月1日 16:13:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/75601033.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定