Ansible regex_search/regex_findall

别等时光非礼了梦想. 提交于 2021-01-28 17:50:17

问题


I'm trying to parse the output of a command that returned a line like this (there's more output, but this is the line that I'm after):

Remaining Time: 3 Minutes and 12 Seconds

And when there is no time left it returns a line like this:

Remaining Time: 0 Seconds

I'd like to extract the amount of minutes and seconds, so I can feed it to GNU date -d. First I tried this:

- name: determine how much time we have left
    set_fact:
      time_left: "{{ cmd_output.stdout | regex_search(time_left_regex, '\\1', '\\2') | join(' ') }}"
    vars:
      time_left_regex: 'Remaining Time: ([0-9]+ Minutes) and ([0-9]+ Seconds)'

But this does not handle the case when there is no time left. So I then tried something like this:

- name: determine how much time we have left
    set_fact:
      time_left: "{{ cmd_output.stdout | regex_findall(time_left_regex, '\\1') }}"
    vars:
      time_left_regex: 'Next Execution:.*([0-9]{1,2} (Minutes|Seconds))'

But this only returns something like:

ok: [localhost] => { "msg": "time left: [[u'2 Seconds', u'Seconds']]" }

I think I'm on the right track but I need a better regex, so maybe somebody can help me out here? Thank you so much in advance.


回答1:


You can make the minutes part optional. The minutes will be in group 1 and the seconds will be in group 2.

Remaining Time: (?:([0-9]+ Minutes) and )?([0-9]+ Seconds)

Regex demo




回答2:


It's possible to split the string (line) and combine a dictionary. For example

    - set_fact:
        time_left: "{{ time_left|default({})|
                       combine({myline[item]: myline[item+1]}) }}"
      loop: "{{ range(0, myline|length + 1, 3)|list }}"
      vars:
        myline: "{{ cmd_output.stdout.split(':').1.split()|reverse|list }}"
    - debug:
        var: time_left

for various command outputs

cmd_output.stdout: 'Remaining Time: 3 Minutes and 12 Seconds'
cmd_output.stdout: 'Remaining Time: 0 Seconds'
cmd_output.stdout: 'Remaining Time: 2 Days and 7 Hours and 3 Minutes and 12 Seconds'

gives (respectively)

    "time_left": {
        "Minutes": "3", 
        "Seconds": "12"
    }
    "time_left": {
        "Seconds": "0"
    }
    "time_left": {
        "Days": "2", 
        "Hours": "7", 
        "Minutes": "3", 
        "Seconds": "12"
    }


来源:https://stackoverflow.com/questions/60785464/ansible-regex-search-regex-findall

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!