How to import and use Jinja macros in a python script (Saltstack setup)

Question:

I have a saltstack setup where one of my pillar file is written in python. This pillar file is pulling some data from a json file. In this python script, there are 2 functions. In the second function, I want to import and use one of the existing salt macros. The structure of this pillar file is something like this

mypillar.sls

#!py
import json

def somefunc{
some code here which is pulling data from a json file
}


def secondfunc{
  This is where I want to use the macro
}

If this would have been an sls file, I know it can be imported like

{% from 'my/code/struct/macros1.sls' import getMacro %}

And I’ve used this macro in few of my other sls files using the above command. It works flawlessly there. However, I’m not sure if this can be used in mypillar.sls file which is actually a python script.

I tried the below commands to import:

  • {% from ‘my/code/struct/macros1.sls’ import getMacro %}
  • {{ from ‘my/code/struct/macros1.sls’ import getMacro }}
  • from my.code.struct.macros1.sls import getMacro – This is python style but it couldn’t find "my" directory only so stuck

So all I want is this macro to be reused in python script.

Asked By: Sammy

||

Answers:

You can’t. Jinja macros are Jinja code, and cannot be run in Python without setting up a full Jinja context and providing a template.

If you want to share code between Python and Jinja in Salt, then write a custom python module that they can then both use.

# salt://_module/macros.py

def some_function():
  ...
#!py

def secondfunc{
  val = __salt__["macros.some_function"]()
  ...
}
#!jinja|yaml

key: {{ salt["macros.some_function"]() }}

Note also that pillar is designed for distributing secrets to minions. If you have a lot of complex template logic here building non-secret data then you should consider moving it out to the state tree for improved performance.

Answered By: OrangeDog
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.