【问题标题】:ansible parse date using regex search使用正则表达式搜索 ansible 解析日期
【发布时间】:2021-01-28 00:25:23
【问题描述】:

我正在尝试使用 regex_search 从显示时钟输出中解析月、日和年,但出现错误。

从路由器的 cli 我看到了这个 -

sh clock
16:22:12.975 PST Wed Jan 27 2021
    - name: Run sh log
      cisco.ios.ios_command:
           commands:
             - sh clock
      register: output1

    - name: sh clock output
      debug:
        msg: "{{ output1.stdout_lines | regex_search('(Jan(uary)?|Feb(ruary)?|Mar(ch)?|Apr(il)?|May|Jun(e)?|Jul(y)?|Aug(ust)?|Sep(tember)?|Oct(ober)?|Nov(ember)?|Dec(ember)?)^\s+\d{1,2}\s+\d{4}' }}"

错误

The offending line appears to be:

      debug:
        msg: "{{ output1.stdout_lines | regex_search('(Jan(uary)?|Feb(ruary)?|Mar(ch)?|Apr(il)?|May|Jun(e)?|Jul(y)?|Aug(ust)?|Sep(tember)?|Oct(ober)?|Nov(ember)?|Dec(ember)?)\s+\d{1,2}\s+\d{4}' }}"
                                                                                                                                                                              ^ here
We could be wrong, but this one looks like it might be an issue with
missing quotes. Always quote template expression brackets when they
start a value. For instance:

    with_items:
      - {{ foo }}

Should be written as:

    with_items:
      - "{{ foo }}"

想要/想要的调试信息在下面,我不需要时间,只需要月日和年

Jan 27 2021

【问题讨论】:

    标签: regex ansible


    【解决方案1】:

    使用regex_replace。将正则表达式放入单独的单引号变量中。例如,下面的任务完成了这项工作

        - name: sh clock output
          debug:
            msg: "{{ output1.stdout_lines|regex_replace(my_regex, my_replace) }}"
          vars:
            my_regex: '^(.*)(Jan(uary)?|Feb(ruary)?|Mar(ch)?|Apr(il)?|May|Jun(e)?|Jul(y)?|Aug(ust)?|Sep(tember)?|Oct(ober)?|Nov(ember)?|Dec(ember)?)\s+(\d{1,2})\s+(\d{4})$'
            my_replace: '\2 \14 \15'
    

    拆分更简单。例如,下面的任务给出了相同的结果

        - debug:
            msg: "{{ arr[-3] }} {{ arr[-2] }} {{ arr[-1] }}"
          vars:
            arr: "{{ output1.stdout_lines.split() }}"
    

    Handling dates and times

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-06
      • 2018-03-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多