如何在 Ansible Playbook 中使用日期、时间和时间戳(ISO 8601 格式)

Ansible 提供了 ansible_date_time 变量,它包含了许多与日期和时间相关的信息。这些信息可以直接在 Playbook 中使用,非常适合用于调试信息、日志文件名或任务输出。

使用 ansible_date_time 变量

ansible_date_time 是一个事实变量,包含了许多与日期和时间相关的键值对。以下是一些常用的键:

  • date:当前日期(如 2022-05-18)
  • time:当前时间(如 15:23:28)
  • iso8601:ISO 8601 格式的时间戳(如 2022-05-18T15:23:28Z)
  • epoch:自 Unix 纪元(1970-01-01)以来的秒数
  • weekday:星期几(如 Wednesday)
  • year、month、day:年、月、日
  • hour、minute、second:小时、分钟、秒

注意:ansible_date_time 需要启用 gather_facts,因此在 Playbook 中需要设置 gather_facts: true。

示例:在 Playbook 中显示日期和时间

Playbook 文件:datetime_fact.yml

---
- name: date and time demo
  hosts: all
  gather_facts: true
  tasks:
    - name: date and time
      ansible.builtin.debug:
        var: ansible_date_time

    - name: ISO8601
      ansible.builtin.debug:
        var: ansible_date_time.iso8601

执行命令

$ ansible-playbook -i virtualmachines/demo/inventory variables/datetime_fact.yml

执行结果

PLAY [date and time demo] **********************************
TASK [Gathering Facts] *************************************
ok: [demo.example.com]
TASK [date and time] ***************************************
ok: [demo.example.com] => {
    "ansible_date_time": {
        "date": "2022-05-19",
        "day": "19",
        "epoch": "1652970190",
        "epoch_int": "1652970190",
        "hour": "14",
        "iso8601": "2022-05-19T14:23:10Z",
        "iso8601_basic": "20220519T142310777257",
        "iso8601_basic_short": "20220519T142310",
        "iso8601_micro": "2022-05-19T14:23:10.777257Z",
        "minute": "23",
        "month": "05",
        "second": "10",
        "time": "14:23:10",
        "tz": "UTC",
        "tz_dst": "UTC",
        "tz_offset": "+0000",
        "weekday": "Thursday",
        "weekday_number": "4",
        "weeknumber": "20",
        "year": "2022"
    }
}
TASK [ISO8601] **********************************************
ok: [demo.example.com] => {
    "ansible_date_time.iso8601": "2022-05-19T14:23:10Z"
}
PLAY RECAP *************************************************
demo.example.com           : ok=3    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0