Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex matching in jinja2 filters (for use in saltstack)

It seems Jinja2 (as supported in Saltstack) doesn't support regex matching, unless I'm missing something? A number of frameworks that leverage Jinja2, such as Ansible have custom support for regex filters. Elsewhere people are directed to write custom filters.

Some questions for those in the know, would probably help understand this state of affairs:

  1. What would be the best way to leverage regex matching in Saltstack? (my use-case here is reasonably simple: testing if a string ends with a substring but the question is more general).
  2. In the absence of a standard solution in Jinja2, would it be a good idea for this to be offered as a standard extension in Saltstack (akin to the Ansible solution)?
  3. What's the rationale for not having standard regex support in Jinja2? In a world where even Windows Powershell supports regex matching, there must be a reason I'm missing since this perceived regression from Jinja2 compared to the previous version has been complained about since 2010; however there isn't even an issue for this in Jinja's github that I could find?
like image 552
sxc731 Avatar asked Jul 25 '16 10:07

sxc731


3 Answers

Even if its old this is still the top post when googling for salt match regex. In 2018.3.3 it is possible to write following code:

{% if "abc" is match("*b*") %}
...
{% endif %}

The relevant documentation link: https://docs.saltstack.com/en/latest/topics/jinja/index.html#match

like image 151
bluefish Avatar answered Sep 17 '22 15:09

bluefish


This is an oldish post, but I came across it and to help other people that do the same..

SaltStack does now have regex_search and regex_match as of 2017.7.0:

https://docs.saltstack.com/en/latest/topics/jinja/index.html#regex-search

like image 22
Brad Avatar answered Sep 19 '22 15:09

Brad


You can match both State and Pillar files like this,

for example, Top.sls

base:
 '*':
   - servers.{{ grains.id }}
   {% if grains.id | regex_match('nyc(.*)', ignorecase=True) %}
   - data.region.nyc
   {% endif %}
   - ignore_missing: True

any node matching nyc* will get these pillar values. This also works inside State files (tested on 2018.3.4)

like image 35
perfecto25 Avatar answered Sep 17 '22 15:09

perfecto25