Creating SaltStack modules - Python.

One of things I like in SaltStack is his modules system. It's as simple as Ansible modules.

All what you need is creating a module with Python (or Cython) and place it inside "_modules" directory at the root of the Salt fileserver path.

For example I needed to extend "replace" function in Jinja which doesn't support Regex (also I added "match" with Regex too). But instead creating a Jinja custom filter, I did create a simple SaltStack module to do that.

This simple module is just using default Python Regex module to achieve that goal.
For example, let's give this module a name "regex.py":

vim salt/_modules/regex.py

It will have:

import re

def replace(pattern, replace, string):
    return re.sub(pattern, replace, string)

def match(pattern, string):
    return re.match(pattern, string)

Don't forget to sync the new module:

salt * saltutil.sync_modules

Once you did, you can use it inside Jinja or SLS files (this is just an arbitrary example):

{% set foo = "xyz123" %}
{%- if salt[regex.match]('\d+', foo) -%}{#- This will return True -#}
    {{ salt[regex.replace](r"\d+(\d)","\g<1>", foo) }}
{%- endif -%}

Just remember, modules will work on client side (minion), so you need to take care of comparability.

This was a quick intro to SaltStack modules, Salt has a lot of capabilities for modules like cross calling execution and so on ... you can find more details on SaltStack documentation: Writing Execution Modules.

Powered by Blogger.

Hello, my name is Ahmed AbouZaid and this is my "lite" technical blog!

I'm a passionate DevOps, Linux system administrator, RedHat Certified Engineer (RHCE), AWS SysOps/Solutions Architect, Free/Open source geek, author, interested in environment, calligraphy, and I believe that “Details Matter”!

Automation, data, and metrics are my preferred areas. I have a built-in monitoring chip, and too lazy to do anything manually :D

Popular Posts