AnswerBun.com

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

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?

Server Fault Asked by AnujAroshA on January 2, 2021

1 Answers

One Answer

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 }}"

Correct answer by Gerald Schneider on January 2, 2021

Add your own answers!

Related Questions

How do i mount a Raid disk in linux

2  Asked on January 25, 2021

 

AH01630: client denied by server configuration Apache

3  Asked on January 24, 2021 by koulapic

     

Postfix/Dovecot-LMTP configuration confusion

2  Asked on January 24, 2021 by user8056359

         

Cannot sign in to aws console

0  Asked on January 22, 2021 by rosencreuz

     

Router drops connection

1  Asked on January 22, 2021 by deniz-zoeteman

     

Windows 10 computer won’t update

2  Asked on January 22, 2021 by hagen-von-eitzen

     

Error while mounting partition with Live CD

1  Asked on January 21, 2021 by sat

     

logrotate not rotating the logs

4  Asked on January 21, 2021 by carmen

 

How to troubleshoot GRE tunnel issues?

1  Asked on January 21, 2021 by linux911

     

Dell PowerEdge R430 iDRAC8 snmp OIDs for hardware

1  Asked on January 20, 2021 by alex_90

 

Snort in KVM machines

1  Asked on January 20, 2021 by emilio-macias

   

check_nrpe: ssocket time out after 10 seconds

1  Asked on January 19, 2021 by suganya

       

Ask a Question

Get help from others!

© 2022 AnswerBun.com. All rights reserved.