Ansible - regex_findall (grep)

regex_findall can be used to perform a regular expression search for a string matching one or more patterns. Let's say the foo variable contains the following.

Line One
Line Two
Line Three

 

The debug module can be used to output the out variable.

- name: "display the content of the 'out' variable"
  debug: 
    msg: "{{ out }}"

 

Which should return the following.

TASK [display the content of the 'out' variable]
ok: [server1.example.com] => {
    "msg": "Line One\nLine Two\nLine Three"
}

 

Here is how to use regex_findall, matching each line containing "Two".

- name: "display the content of the 'out' variable, matching 'Two'"
  debug: 
    msg: "{{ out | regex_findall('.*two.*', ignorecase=True) }}"

 

Which should now return the following.

TASK [display the content of the 'out' variable, matching 'Two'']
ok: [server1.example.com] => {
    "msg": "Line Two"
}

 

It is important to recognize that regex_search will only return the first match, whereas regex_findall will return every match. In this example, regex_search would only return the first line that contains "Line".

- name: "display the content of the 'out' variable, matching 'Line'"
  debug: 
    msg: "{{ out | regex_search('.*Line.*') }}"

 

Notice in this example the only "Line One" is returned, meaning "Line Two" and "Line Three" are not returned.

TASK [display the content of the 'out' variable, matching 'Line'']
ok: [server1.example.com] => {
    "msg": "Line One"
}

 

On the other hand, regex_findall can be used to return every pattern match, not just the first match. In this example, regex_findall would only return every match of "Line".

- name: display the content of the 'out' variable, matching 'Line'
  debug: 
    msg: "{{ out | regex_findall('.*Line.*') }}"

 

Notice in this example that "Line One" and "Line Two" and "Line Three" are returned.

TASK [display the content of the 'out' variable, matching 'Line'']
ok: [server1.example.com] => {
    "msg": "Line One"
}

 

And here is how to search for two (or more) different strings.

- name: display lines containing One or Two
  debug: 
    msg: "{{ out | regex_findall('.*One|Two.*') }}"

 

Let's say the foo variable contains a value of "Hello World". Here is how you would match all lines in the "out" variable that contain Hello World, using the foo variable.

- name: display the content of the 'out' variable, matching the 'foo' variable
  debug: 
    msg: "{{ out | regex_findall('(.*' + foo + '.*)') }}"

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.





Please enter 6650b in the box below so that we can be sure you are a human.




Comments

Web design by yours truely - me, myself, and I   |   jeremy.canfield@freekb.net   |