Extracting part of the string using Ansible regex_search and save the output as a variable

Solution 1:

You need to add a group to your regex and a second parameter that specifies which group to return:

- set_fact:
    my_var: "{{ zoo_config_content.stdout | regex_search('dataDir=(.+)', '\\1') | first }}"

This would return an array with a single element, so I added | first to get only one element directly as a string.

Result:

ok: [localhost] => {
    "my_var": "/var/lib/zookeeper"
}

If the config file resides on the Ansible machine you can make it even easier using a lookup:

- set_fact:
    my_var: "{{ lookup('file', 'zoo.cfg') | regex_search('dataDir=(.+)', '\\1') | first }}"