lovi
lovi

Reputation: 105

Remove backslash in string with ansible

Im struggling with removing backslash in a string like this :

- name: Set var
set_fact:
     var: "{{ _var.stdout_lines[0].replace('\\\\', ' ').split(' ')[1] }}"

where _var is :

    "_var": {
    "changed": true,
    "delta": "0:00:00.406263",
    "end": "2020-10-20 09:03:36.332342",
    "failed": false,
    "rc": 0,
    "start": "2020-10-20 09:03:35.926079",
    "stderr": "",
    "stderr_lines": [],
    "stdout": "MYSERVER\\myuser\r\n",
    "stdout_lines": [
        "MYSERVER\\myuser"
    ]
}

As Im looking to catch only myuser as a result.

Upvotes: 0

Views: 3988

Answers (1)

ilias-sp
ilias-sp

Reputation: 6685

you can use regex_replace to extract the username from the above string of stdout_lines[0].

here is a task to do it:

---
- hosts: localhost
  gather_facts: false
  vars:
    myvar: "SERVER\\myuser"
    
  tasks:
  - name: extract the username
    debug:
      msg: '{{ myvar | regex_replace("^(.+)([\\]+)(.+)$", "\3") }}'

The 2nd group in the regex was defined to match any number of backslashes.

Upvotes: 2

Related Questions