file - 检查文件是否存在 20 小时前的 ansible
问题描述
我可以使用 Ansiblestat
模块获取文件的时间戳。
- stat:
path: "/var/test.log"
register: filedets
- debug:
msg: "{{ filedets.stat.mtime }}"
上面打印的 mtime1594477594.631616
很难理解。
我想知道如何进行when
条件检查以查看文件是否少于 20 小时?
解决方案
您也可以完成此类任务,而无需通过find
及其age
参数进行任何计算:
在您的情况下,您将需要一个负值age
:
选择年龄等于或大于指定时间的文件。使用负年龄来查找等于或小于指定时间的文件。您可以通过指定这些单词的第一个字母(例如,“1w”)来选择秒、分钟、小时、天或周。
来源:https ://docs.ansible.com/ansible/latest/modules/find_module.html#parameter-age
鉴于剧本:
- hosts: all
gather_facts: no
tasks:
- file:
path: /var/test.log
state: touch
- find:
paths: /var
pattern: 'test.log'
age: -20h
register: test_log
- debug:
msg: "The file is exactly 20 hours old or less"
when: test_log.files | length > 0
- file:
path: /var/test.log
state: touch
modification_time: '202007102230.00'
- find:
paths: /var
pattern: 'test.log'
age: -20h
register: test_log
- debug:
msg: "The file is exactly 20 hours old or less"
when: test_log.files | length > 0
这给出了回顾:
PLAY [all] **********************************************************************************************************
TASK [file] *********************************************************************************************************
changed: [localhost]
TASK [find] *********************************************************************************************************
ok: [localhost]
TASK [debug] ********************************************************************************************************
ok: [localhost] => {
"msg": "The file is exactly 20 hours old or less"
}
TASK [file] *********************************************************************************************************
changed: [localhost]
TASK [find] *********************************************************************************************************
ok: [localhost]
TASK [debug] ********************************************************************************************************
skipping: [localhost]
PLAY RECAP **********************************************************************************************************
localhost : ok=5 changed=2 unreachable=0 failed=0 skipped=1 rescued=0 ignored=0