【问题标题】:How to import and use Jinja macros in a python script (Saltstack setup)如何在 python 脚本中导入和使用 Jinja 宏(Saltstack 设置)
【发布时间】:2023-01-10 05:43:13
【问题描述】:

我有一个盐堆设置我的支柱文件之一是用 python 编写的。这个支柱文件从 json 文件中提取一些数据。在此 python 脚本中,有 2 个函数。在第二个函数中,我想导入并使用现有的盐宏之一。这个支柱文件的结构是这样的

我的柱子.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
}

如果这是一个 sls 文件,我知道它可以像这样导入

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

我已经使用上面的命令在我的其他几个 sls 文件中使用了这个宏。它在那里完美地工作。但是,我不确定这是否可以用于我的柱子.sls文件,它实际上是一个 python 脚本。

我尝试了以下命令来导入:

  • {% from 'my/code/struct/macros1.sls' import getMacro %}
  • {{ 从 'my/code/struct/macros1.sls' 导入 getMacro }}
  • from my.code.struct.macros1.sls import getMacro - 这是 python 风格,但它找不到“我的”目录,所以卡住了

所以我只想在 python 脚本中重用这个宏。

【问题讨论】:

    标签: python jinja2 salt-stack


    【解决方案1】:

    你不能。 Jinja 宏是 Jinja 代码,如果不设置完整的 Jinja 上下文并提供模板,则无法在 Python 中运行。

    如果你想在 Salt 中的 Python 和 Jinja 之间共享代码,那么他们都可以使用 write a custom python module

    # salt://_module/macros.py
    
    def some_function():
      ...
    
    #!py
    
    def secondfunc{
      val = __salt__["macros.some_function"]()
      ...
    }
    
    #!jinja|yaml
    
    key: {{ salt["macros.some_function"]() }}
    

    另请注意,pillar 是为向 minions 分发秘密而设计的。如果您在此处构建非机密数据时有很多复杂的模板逻辑,那么您应该考虑将其移至状态树以提高性能。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-13
      • 2021-07-19
      • 2015-09-01
      相关资源
      最近更新 更多