Ansible playbook使用date.stdout过滤器和来自stdout的变量

Ansible playbook使用date.stdout过滤器和来自stdout的变量,ansible,Ansible,我正在尝试运行此任务: --- - 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 c

我正在尝试运行此任务:

---
- 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中包含的字符串传递到_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
与to_datetime“%Y-%m-%d”中指定的格式相比,date.stdout中包含的格式输入似乎是错误的。我错过了什么?也许date.stdout里有个奇怪的角色

提前谢谢! Tommaso.

您要求使用datetime来解析格式为%Y-%m-%d的日期

您正在传递2019-14-03表格中的数据

一年中没有14个月

您希望format参数与您提供给date命令的format参数匹配:

为清晰起见,将其稍微重新格式化,并将硬编码日期替换为符合您的格式:

- debug:
    var: >-
      (
      (date.stdout | to_datetime('%Y-%d-%m')) -
      ("2020-25-12" | to_datetime('%Y-%d-%m'))
      ).days

或者,如果确实需要%Y-%m-%d,请将参数替换为date命令。确保它们匹配。

谢谢你的帮助这是一个愚蠢的错误,但我真的没有注意到:
- debug:
    var: >-
      (
      (date.stdout | to_datetime('%Y-%d-%m')) -
      ("2020-25-12" | to_datetime('%Y-%d-%m'))
      ).days