我正在尝试运行此任务:
---
- name: "{{ BANNER }}"
shell: "rpm -qf /etc/issue"
register: rpm
changed_when: False
ignore_errors: True
- shell: 'rpm -q -i "{{ rpm.stdout }}" | grep "Install Date:" | awk ''{ print $4 " " $5 " " $6 }'''
register: rpm
changed_when: False
ignore_errors: True
- shell: 'date -d "{{ rpm.stdout }}" +''%Y-%d-%m'''
register: date
changed_when: False
ignore_errors: True
- debug: var=date.stdout
- debug: var={{ (( date.stdout | to_datetime('%Y-%m-%d')) - ("2020-12-25" | to_datetime('%Y-%m-%d'))).days }}
基本上,我需要传递data.stdout中包含的字符串以过滤to_datetime以进行日期减法,但是我收到此错误:
TASK [RH7-008 : debug] **********************************************************************************************************************************************
ok: [192.168.56.1] => {
"date.stdout": "2019-14-03"
}
TASK [RH7-008 : debug] **********************************************************************************************************************************************
fatal: [192.168.56.1]: FAILED! => {"msg": "the field 'args' has an invalid value ([u'check_mode']), and could not be converted to an dict.The error was: time data '2019-14-03' does not match format '%Y-%m-%d'\n\nThe error appears to have been in '/root/ansible/roles/RH7-008/tasks/check_mode.yml': line 27, column 3, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n- debug: var={{ (( date.stdout | to_datetime('%Y-%m-%d')) - (\"2020-12-25\" | to_datetime('%Y-%m-%d'))).days }}\n ^ here\nWe could be wrong, but this one looks like it might be an issue with\nmissing quotes. Always quote template expression brackets when they\nstart a value. For instance:\n\n with_items:\n - {{ foo }}\n\nShould be written as:\n\n with_items:\n - \"{{ foo }}\"\n\nexception type: <type 'exceptions.ValueError'>\nexception: time data '2019-14-03' does not match format '%Y-%m-%d'"}
to retry, use: --limit @/root/ansible/main.retry
与date.stdout
中指定的格式输入相比,to_datetime('%Y-%m-%d')
中包含的格式输入似乎是错误的。我想念什么?也许date.stdout
中有些奇怪的人物?
提前谢谢! 托马索。
答案 0 :(得分:1)
您要to_datetime
解析格式为%Y-%m-%d
的日期。
您正在传递2019-14-03
形式的数据。
一年中没有14个月。
您希望to_datetime
的format参数与您为date
命令提供的format参数匹配:
to_datetime('%Y-%d-%m')
进行制作(为清晰起见,对其进行了略微重新格式化,并更改了硬编码日期以匹配您的格式):
- debug:
var: >-
(
(date.stdout | to_datetime('%Y-%d-%m')) -
("2020-25-12" | to_datetime('%Y-%d-%m'))
).days
或者,如果您确实需要date
,则将参数交换为%Y-%m-%d
命令。只要确保它们匹配即可。