25/12/2016

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 engineer, Cloud/Kubernetes specialist, Free/Open source geek, and an author.

I believe in self CI/CD (Continuous Improvements/Development), also that "the whole is greater than the sum of its parts".

DevOps transformation, automation, data, and metrics are my preferred areas. And I like to help both businesses and people to grow.

Latest Post

🔀Merger🔀, a schemaless strategic merge plugin - Kustomize

Kustomize is a great tool. I've been using Kustomize for almost 4 years and am happy with it. However, it's ...

Popular Posts