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

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

我正在尝试执行此任务:

---
- 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有一些奇怪的角色?

提前致谢!托马索。

ansible
1个回答
1
投票

您要求to_datetime解析%Y-%m-%d形式的日期。

您正在传递2019-14-03形式的数据。

一年中没有14个月。

您希望to_datetime的format参数与您为date命令提供的格式参数匹配:

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命令。只要确保它们匹配。

© www.soinside.com 2019 - 2024. All rights reserved.