从Jinja表达式中减去日期

问题描述 投票:1回答:1

我只想在Ansible任务中将date_operation删除1个月

vars:
  # for example current
  current_date_operation: "{{ ansible_date_time.date }}" 
  previous_date_operation : "{{ '%Y-%m-%d'|strftime(current_date_operation.epoch|int - 2592000) }}"

我想从current_date_operation中减去date_operation 1个月,但以上代码给了我以下错误:

“ msg”:“任务包括带有未定义变量的选项。错误是:'ansible.utils.unsafe_proxy.AnsibleUnsafeText对象'没有属性'epoch'

任何想法?

谢谢

date ansible jinja2 subtraction
1个回答
0
投票

vars声明中,您首先是从对象date获取ansible_date_time键。

[在下一行,您正在使用该设置变量(它是一个字符串),并在其上调用键epoch,该键不存在,因为它是父对象(即ansible_date_time)的属性。由于您的var声明无法正确解析,因此var本身是未定义的。

以下剧本演示您可以通过修改vars定义来获得预期的结果:

---
 - hosts: localhost

   vars:
     current_date_operation: "{{ ansible_date_time.date }}"
     previous_date_operation : "{{ '%Y-%m-%d' | strftime(ansible_date_time.epoch | int - 2592000) }}"

   tasks:
     - debug:
         var: current_date_operation
     - debug:
         var: previous_date_operation

试运行:

$ ansible-playbook playbook.yml 

PLAY [localhost] **************************************************************************************************************************************************************************************************

TASK [Gathering Facts] ********************************************************************************************************************************************************************************************
ok: [localhost]

TASK [debug] ******************************************************************************************************************************************************************************************************
ok: [localhost] => {
    "current_date_operation": "2020-01-14"
}

TASK [debug] ******************************************************************************************************************************************************************************************************
ok: [localhost] => {
    "previous_date_operation": "2019-12-15"
}

PLAY RECAP ********************************************************************************************************************************************************************************************************
localhost                  : ok=3    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
© www.soinside.com 2019 - 2024. All rights reserved.