Ansible - Increment date by 'X' days/minut

2019-05-10 13:31发布

问题:

The variable ansible_date_time.date gives the current date and time stamp, however I wish to increment this date by 'X' minutes/days. Is there any built in method or logic to do this?

The - operator seems to work with date operands, however there doesn't seem to be any straightforward way to increment a date.

I want to accomplish this in a yml script itself and not by using additional Python scripting as described in Is it possible to manipulate the date in an Ansible Playbook

回答1:

In Ansible 2.4 you can use strftime to accomplish this by using epoch times and then converting back to a string using the strftime filter.

For example, taking one day as 86400 seconds, to add 3 days would be:

- debug:
    msg: "{{ '%Y-%m-%d' | strftime( ( ansible_date_time.epoch | int ) + ( 86400 * 3 )  ) }}"

For minutes, the multiplier would be 60 seconds, and the datetime format string at the start should include the appropriate time granularity (e.g. %H, %M, %S, ...).

There is some documentation on this filter here.



回答2:

The command module can be used as shown in the following snippet to increment the current date. This worked for me as expected.

- command: "date +'%d-%m-%Y' -d '+3 days'"
  register: result

- debug: msg="{{result.stdout}}"

This will return the date in dd-mm-yyyy format. For example, if today's date is "03-07-2017", it will increment the date by 3 days (as mentioned in the command shown in above example snippet) and would return "06-07-2017".