Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

ansible parse date using regex search

I am trying parse month,day and year from show clock output using regex_search, getting error.

from cli of a router i see this -

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}' }}"

error

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 }}"

desired/wanted debug msg is below ,i don't want time, just need month day and year

Jan 27 2021
question from:https://stackoverflow.com/questions/65929365/ansible-parse-date-using-regex-search

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use regex_replace. Put the regex into a separate single-quoted variable. For example, the task below does the job

    - 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'

The splitting is simpler. For example, the task below gives the same result

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

See Handling dates and times


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...