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, I'm a passionate Tech Lead DevOps Engineer. 👋

With 16+ years of open-source contributions, 12+ years of hands-on experience in DevOps, and an M.Sc. in Data Engineering from Edinburgh Napier University (UK), I enjoy facilitating the growth of both businesses and individuals.

I specialize in Cloud-Native and Kubernetes. I'm also a Free/Open source geek and book author. My favorite topics are DevOps transformation, automation, data, and metrics.

Contact Me

Name

Email *

Message *

Start Your DevOps Engineer Journey!

Start Your DevOps Engineer Journey!
Start your DevOps career for free the Agile way in 2024 with the Dynamic DevOps Roadmap ⭐

Latest Post

2023 Highlights

Image generated with Craiyon . Finally, 2023 is over! What a year! One more crazy year, but it was the culmination ...

Popular Posts

Blog Archive