Need help with regex_replace

Hi guys,

I’ve a problem with regex_replace module. It seems that my expression is correct but I’m not getting the expected result.

So I’m using a raw command and use register to get the result.
Here’s my debug:

- name: Get virtual info
  ansible.builtin.debug:
    msg:  " vminfo : {{ vminfo.stdout_lines }}"

Here’s the result:

ok: [vm01-vm-dev01.local.com] =>
  msg: ' vminfo : [''1 vm01-vm-dev01'']'

I need to retrieve the second part of this string : vm01-vm-dev01 and here is my code:

- name Get virtual info
  ansible.builtin.debug:
    msg:  " vminfo : {{ vminfo.stdout_lines | regex_replace('^([0-9])\\s(vm.*)$', '\\2') }}"

With regex_replace I tried to isolate the elements separated by a space and retrieve the second one but unfortunately nothing happens!

As anyone an idea what’s wrong by my regex? Any ideas?

Regards,

If you only want the first item in the list you could use vminfo.stdout_lines[0] and then split to get the second part of the string, for example something like this might work (untested):

- name: Set a fact for the VM name
  ansible.builtin.set_fact:
    vmname: "{{ (vminfo.stdout_lines[0] | ansible.builtin.split)[1] }}"
1 Like

Notice the “[” and " ]" surrounding the string you want. That means that the variable vminfo.stdout_lines is a list, and it contains a single string. That means that you are passing a list to regex_replace instead of a string.

ok: [vm01-vm-dev01.local.com] =>
  msg: ' vminfo : [''1 vm01-vm-dev01'']'

As @chris shows in his example, you need to identify which item in stdout_lines that you want to pass to regex_replace.

Edit: Corrected vminfo reference to vminfo.stdout_lines

2 Likes

Thanks a lot for your answer.
It’s now clear and I have now been able to solve my problem.

3 Likes

Please, don’t forget to mark @chris message as the solution so others can more easily find the answer to similar issue.
:slight_smile:

2 Likes

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.