如果你不想启用 gather_facts 或需要在本地主机上获取日期和时间,可以使用 lookup 插件结合 date 命令。
示例:不使用 gather_facts 获取日期和时间
Playbook 文件:datetime_nofact.yml
---
- name: date and time demo
hosts: all
gather_facts: false
tasks:
- name: date and time
ansible.builtin.debug:
msg: "{{ lookup('pipe', 'date +%Y-%m-%d@%H:%M:%S') }}"
- name: iso8601 manual
ansible.builtin.debug:
msg: "{{ lookup('pipe', 'date +%Y-%m-%dT%H:%M:%S%z') }}"
- name: iso8601
ansible.builtin.debug:
msg: "{{ lookup('pipe', 'date --iso8601=seconds') }}"
ignore_errors: true
执行命令
$ ansible-playbook -i virtualmachines/demo/inventory variables/datetime_nofact.yml
执行结果
PLAY [date and time demo] **********************************
TASK [date and time] ***************************************
ok: [demo.example.com] => {
"msg": "2022-05-22@14:57:33"
}
TASK [iso8601 manual] **************************************
ok: [demo.example.com] => {
"msg": "2022-05-22T14:57:33+0200"
}
TASK [iso8601] **********************************************
date: illegal option -- -
usage: date [-jnRu] [-d dst] [-r seconds] [-t west] [-v[+-]val[ymwdHMS]] ...
[-f fmt date | [[[mm]dd]HH]MM[[cc]yy][.ss]] [+format]
fatal: [demo.example.com]: FAILED! => {"msg": "An unhandled exception occurred while running the lookup plugin 'pipe'. Error was a <class 'ansible.errors.AnsibleError'>, original message: lookup_plugin.pipe(date --iso8601=seconds) returned 1. lookup_plugin.pipe(date --iso8601=seconds) returned 1"}
...ignoring
PLAY RECAP *************************************************
demo.example.com : ok=3 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=1
解释
lookup('pipe', 'date +%Y-%m-%d@%H:%M:%S'): 使用date命令生成自定义格式的日期和时间。lookup('pipe', 'date +%Y-%m-%dT%H:%M:%S%z'): 手动生成 ISO 8601 格式的时间戳,包括时区偏移。lookup('pipe', 'date --iso8601=seconds'): 直接生成 ISO 8601 格式的时间戳。注意:某些平台(如 macOS)可能不支持--iso8601参数,因此需要手动构建格式。