Is it possible to manipulate the date in an Ansibl

2019-08-11 17:33发布

问题:

Am using the ansible_date_time.hour and ansible_date_time.minute in one of my playbooks.

But I need to add time on to these facts (or in a variable).. i.e. if ansible_date_time.hour returns 16 - I want to add a couple of hours, or if ansible_date_time.minute returns 40 - I want it to be 50..

Of course there is a ceiling of 23 and 59 for the hours and mins... as I thought about registering a variable from:

- name: Register HH  
  shell: date '+%H'
  register: HP_HH
- debug: msg="{{ HP_HH.stdout | int + 3 }}"

But obviously if my playbook runs at after 21:00 I am out of luck.

Does anyone have a suggestion or workaround?

回答1:

AFAIK, there is no way to add/subtract time units out of the box in Ansible.

You can convert strings to datetime object with to_datetime filter (Ansible 2.2+).
You can calculate date difference. See this answer.

But if you don't mind using a simple filter plugin, here you go:

Drop this code as ./filter_plugins/add_time.py near your playbook:

import datetime

def add_time(dt, **kwargs):
    return dt + datetime.timedelta(**kwargs)

class FilterModule(object):

    def filters(self):
        return {
            'add_time': add_time
        }

And you can use your own add_time filter as follows:

- hosts: localhost
  gather_facts: yes
  tasks:
    - debug:
        msg: "Current datetime is {{ ansible_date_time.iso8601 }}"
    - debug:
        msg: "Current time +20 mins {{ ansible_date_time.iso8601[:19] | to_datetime(fmt) | add_time(minutes=20) }}"
      vars:
        fmt: "%Y-%m-%dT%H:%M:%S"

add_time has same parameters as timedelta in Python.



标签: ansible