如何将时间添加到 Ansible 中的当前时间戳?

How to add time to the current timestamp in Ansible?

我正在尝试在 Ansible 中自动执行一些任务,虽然我已经完成了所有其他工作,但我需要一个 start_time 和 end_time 变量来将时间添加到当前时间戳因为 ServiceNow 系统在创建更改请求时不接受当前时间戳。

例如,我有一个变量 start_time 作为 "{{ lookup('pipe', date +\"%Y-%m-%d %r\"') }}" 但我需要它是当前时间 +5 分钟。同样在 end_date 上,但大约 +15 分钟。

如果您打算使用 lookup_plugins and pipe,您可以使用 date +"%Y-%m-%d %r" -d "5 mins" 添加 5 分钟。

感谢

  • Incrementing current date by 5 minutes

尽管如此,还是建议使用像 ansible_date_time 这样的 Ansible 变量。

date_time:
  date: '2021-11-23'
  day: '23'
  epoch: '1637678908'
  hour: '15'
  iso8601: '2021-11-23T14:48:28Z'
  iso8601_basic: 20211123T154828773386
  iso8601_basic_short: 20211123T154828
  iso8601_micro: '2021-11-23T14:48:28.773386Z'
  minute: '48'
  month: '11'
  second: '28'
  time: '15:48:28'
  tz: CET
  tz_offset: '+0100'
  weekday: Tuesday
  weekday_number: '2'
  weeknumber: '47'
  year: '2021'

在那里您可以使用 epochminute 或适合您的用例的内容。

类似的东西?

{{ ansible_date_time.date }}
{{ ansible_date_time.hour|int +1|int }}
{{ ansible_date_time.minute|int +15|int }}

您可以使用 strftime 过滤器来格式化时间,使用 Ansible 的内置事实收集来获取当前时间,并使用一点算术来添加偏移量。

- hosts: localhost
  tasks:
    - debug:
        msg:
          - "{{ '%Y-%m-%d %r' | strftime(ansible_facts.date_time.epoch | int + 300 ) }}"
          - "{{ '%Y-%m-%d %r' | strftime(ansible_facts.date_time.epoch | int + 900 ) }}"
TASK [debug] *******************************************************************
ok: [localhost] => {
    "msg": [
        "2021-11-23 01:10:45 PM",
        "2021-11-23 01:20:45 PM"
    ]
}