在ansible中检查文件是否存在20小时



我可以使用Ansiblestat模块获取文件的时间戳。

- stat:
path: "/var/test.log"
register: filedets
- debug:
msg: "{{ filedets.stat.mtime }}"

上面将mtime打印为1594477594.631616,这很难理解。

我想知道如何进行when条件检查,以查看文件的使用时间是否小于20小时?

您也可以通过find及其age参数来实现这类任务,而无需进行任何计算

在您的情况下,您需要age:的负值

选择年龄等于或大于指定时间的文件。使用负年龄查找等于或小于指定时间的文件。您可以通过指定任何单词的第一个字母(例如"1w"(来选择秒、分钟、小时、天或周。

来源:https://docs.ansible.com/ansible/latest/modules/find_module.html#parameter-年龄

给出剧本:

- 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  
- stat:
path: "/var/test.log"
register: filedets
- debug:
msg: "{{ (ansible_date_time.epoch|float - filedets.stat.mtime ) > (20 * 3600) }}"

最新更新