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

30,929

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 }}"
Share:
30,929
AnujAroshA
Author by

AnujAroshA

෴ http://anujarosha.lk/ ෴

Updated on September 18, 2022

Comments

  • AnujAroshA
    AnujAroshA over 1 year

    I'm having a content like below inside a file.

    dataDir=/var/lib/zookeeper
    4lw.commands.whitelist=mntr,conf,ruok,stat
    syncLimit=2
    

    I wanted to read the value for dataDir using Ansible and set it to a variable. I have written following code but regular expression and storing the variable both have some issues.

      - name: Read zoo.cfg content
        shell:
          cmd: cat zoo.cfg
        register: zoo_config_content
    
      - set_fact:
          my_var: "{{ zoo_config_content.stdout | regex_search('dataDir.*')}}"
    
      - name: Print
        debug:
          var: my_var
    

    Q1.) How can I improve the regular expression to get only /var/lib/zookeeper ?

    Q2.) How can I store that extracted value to use in another task?

    • Admin
      Admin over 3 years
      Please don't ask multiple questions in one question, add a separate question for your second part. But with set_fact you already stored the value and can use it. If you open an additional question please elaborate more what's your problem with that variable.
  • AnujAroshA
    AnujAroshA over 3 years
    Thanks set_fact works with the regular expression. But lookup will not work on the remote machine. Will it? The other thing that's issue with lookup is, the same code lookup('url',... runs in Linux machine but not in macOS.
  • dortegaoh
    dortegaoh over 3 years
    You are right, lookup works locally, my fault.
  • divay singhal
    divay singhal about 3 years
    - set_fact: my_var: "{{ zoo_config_content.stdout | regex_search('dataDir=(.+)', '\\1') | first }}" what if the value is not avaiable will it give below result my_var: ""
  • dortegaoh
    dortegaoh about 3 years
    You should ask this as a question. You can link here as a reference.