ansible - 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]
解决方案
如果我正确理解了您的期望,那么您也可以使用grep
andcommand
模块来实现结果。这是一个示例:
- 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 逻辑。
推荐阅读
- sql - SQL Server:从多个表中选择
- javascript - 没有括号的Javascript调用函数
- java - 多表 JPA 规范
- datetime - Kubernetes 中 Pod 和主机之间的日期和时间同步
- excel - ODBC 查询 - 刷新数据下推最后一行数据
- google-colaboratory - xgboost 是否将 TPU 用于“gpu-hist”(如果 TPU 可用)?
- javascript - 根据与对象中的多个字段进行比较的关键字返回搜索结果的最有效方法
- java - 如何检查查询过程是否在firebase中完成
- python - 为什么只有一个值写入字典?
- python-3.x - 将同一列的值合二为一