Salt - howto simple custom module and jinja

From Skytech
Jump to navigation Jump to search


Stolen from some stackoverflow post

I have a couple custom execution modules that hold nothing but utility functions for use within state files. So, something along the lines of:

/srv/salt/_modules/tplutils.py

import re

def __virtual__():
  return __name__

def rematch(pattern, target):
  """ 
      (because Jinja makes me want to cut myself)

      args:
          regex pattern (str)
          target text (str)
  """

  return True if re.match(r'{}'.format(pattern), target) else False

could then be called like

/etc/ntp.conf:
  file.managed:
    - source:
      {% if salt.tplutils.rematch(grains['id'], 'host(1|2)c') %}
      - salt://ntp/files/ntp.conf.server
      {% else %}
      - salt://ntp/files/ntp.conf.{{ grains['fqdn'] }}
      - salt://ntp/files/ntp.conf.default
      {% endif %}
    - user: root
    - group: root
    - mode: 644