首页 > 解决方案 > ansible 检查 lineinfile 的字符串失败

问题描述

真的希望有人能够提供帮助,我有这个任务,检查字符串 XYZ 是否存在于日志中

如果它不存在,它应该失败(ignore_errors:yes)然后踢另一个任务,但是,即使它失败了,它也会跳过另一个任务

 - name: check if file is empty
       lineinfile:
          path: /path/to/log.log
          line: "XYZ"
          state: present
       check_mode: yes
       register: exists
       failed_when: exists is changed
       ignore_errors: yes

     - name: send mail
       when: exists is not changed
       mail:
          from: mail@123.com
          subject: xyz
          body: No xyz found
          to:
           - John Doe <john.doe@123.com>
          cc: Marie Smith <marie.smit@123.com>

     - name: read files
       when: exists is changed
       do abc...

问题是当文件为空且没有XYZ时,它仍然失败,但跳过邮件发送并继续读取文件任务


TASK [check if file is empty] ***********************************************************************************************************************************************************************************

fatal: [server123]: FAILED! => {"backup": "", "changed": true, "failed_when_result": true, "msg": "line added"}

...ignoring



TASK [send mail] ************************************************************************************************************************************************************************************************

skipping: [server123]



TASK [read files] ***********************************************************************************************************************************************************************************************

changed: [server123]

标签: ansible

解决方案


如果我正确理解了您的期望,那么您也可以使用grepandcommand模块来实现结果。这是一个示例:

- name: check if file is empty
  command: grep -xq 'XYZ' /path/to/log.log
  register: exists
  ignore_errors: yes

- name: send mail
  mail:
    from: mail@123.com
    subject: xyz
    body: No xyz found
    to:
      - John Doe <john.doe@123.com>
    cc: Marie Smith <marie.smit@123.com>
  when: exists.failed

- name: read files
  debug:
    msg: do abc...
  when: not exists.failed

您可以调整适合的 grep 逻辑。


推荐阅读