导入python库时ansible自定义过滤器失败

假口袋

我正在尝试在 Ansible 中编写自定义 Jinja2 过滤器。

我能够编写一个简单的过滤器。但是,对于我想到的实际用例,我想做import boto3.

当我运行时pip list | grep boto3,我看到它已安装。当我运行时python -c 'import boto3',它运行成功。

但是当我插入import boto3自定义过滤器的顶部时,Ansible 无法加载它。

移动电源

目录结构:

  - filter_plugins/
     - custom.py
  - playbook.yaml

custom.py

import hashlib # I can import some things, not others

print("custom filter file loaded")
class FilterModule(object):

    def _square(self,x):
        return(int(x)*int(x))  

    def filters(self):
        return {
            'my_square': self._square
        }

playbook.yaml

---
- hosts: localhost
  connection: local
  tasks:

    - name: test custom filter
      assert:
        that:
          - "( 2 | my_square ) == 4"
      tags:
        - test

当我调用它时:

ansible-playbook playbook.yaml

剧本成功运行。我还可以看到 Ansible 打印的“加载的自定义过滤器文件”

但是当我附加import boto3到顶部时,剧本失败了。

  • Ansible不会打印“加载的自定义过滤器文件”
  • 错误信息是:

致命:[127.0.0.1]:失败!=> {"msg": "条件检查 '( 2 | my_square ) == 4' 失败。错误是:模板字符串时模板错误:没有名为 'my_square' 的过滤器。字符串:{% if ( 2 | my_square ) == 4 %} 真 {% else %} 假 {% endif %}"}

问题:

  • 这是因为我正在使用connection: local,还是因为 Ansible 使用PATH了非交互式 shell?
  • 如何调试自定义过滤器失败的原因?我花了很多时间才弄清楚是import boto3线路导致了故障。Ansible 似乎在剧本运行开始时(有时是其他时间)导入自定义过滤器文件,捕获错误,然后继续直到我尝试使用过滤器。
  • 这是 Python 2 与 Python 3 的对比吗?Python 使用哪个?(我做了pip install boto3,我还没有pip3安装。)
弗拉基米尔·博特卡

问:“ Is this a Python 2 vs Python 3 thing? Which does Python use?

答:是的。很可能ansible-playbook playbook.yaml使用 Python 2。以详细模式运行剧本

ansible-playbook -vvv playbook.yaml

并找到 Python 的版本。例如

python version = 2.7.15+ (default, Nov 27 2018, 23:36:35) [GCC 7.3.0]

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章