是否可以在Ansible Playbook中操纵日期 [英] Is it possible to manipulate the date in an Ansible Playbook
问题描述
我在其中一本剧本中使用ansible_date_time.hour
和ansible_date_time.minute
.
Am using the ansible_date_time.hour
and ansible_date_time.minute
in one of my playbooks.
但是我需要在这些事实上增加时间(或在变量中)..例如,如果ansible_date_time.hour
返回16-我想增加几个小时,或者如果ansible_date_time.minute
返回40-我希望它是50 ..
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..
当然,小时和分钟的上限是23和59 ...正如我所想到的,要从以下位置注册变量:
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 }}"
但是很明显,如果我的剧本在21:00之后上映,那我就不走运了.
But obviously if my playbook runs at after 21:00 I am out of luck.
有人有建议或解决方法吗?
Does anyone have a suggestion or workaround?
推荐答案
AFAIK,无法在Ansible中直接添加/减去时间单位.
AFAIK, there is no way to add/subtract time units out of the box in Ansible.
您可以使用to_datetime
过滤器(Ansible 2.2+)将字符串转换为datetime
对象.
您可以计算日期差.请参阅此答案.
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:
将此代码作为./filter_plugins/add_time.py
拖放到您的剧本附近:
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
}
您可以使用自己的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
与Python中的 timedelta 具有相同的参数
add_time
has same parameters as timedelta in Python.
这篇关于是否可以在Ansible Playbook中操纵日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!