是否可以在 Ansible Playbook 中操作日期 [英] Is it possible to manipulate the date in an Ansible Playbook

查看:19
本文介绍了是否可以在 Ansible Playbook 中操作日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的一本剧本中使用了 ansible_date_time.houransible_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_timetimedelta<具有相同的参数/a> 在 Python 中.

add_time has same parameters as timedelta in Python.

这篇关于是否可以在 Ansible Playbook 中操作日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆