【发布时间】:2019-07-31 07:13:42
【问题描述】:
我正在尝试在 Ansible 中编写自定义 Jinja2 过滤器。
我可以编写一个简单的过滤器。
但是对于我想到的实际用例,我想做import boto3。
当我运行pip list | grep boto3 时,我看到它已安装。
当我运行python -c 'import boto3' 时,它运行成功。
但是当我在自定义过滤器顶部插入 import boto3 时,Ansible 无法加载它。
MWE
目录结构:
- 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 使用了非交互式 shell 的PATH? - 如何调试自定义过滤器失败的原因?我花了很多时间才弄清楚是
import boto3行导致了失败。 Ansible 似乎在 playbook 运行开始时(有时是其他时间)导入自定义过滤器文件,捕获错误,然后继续,直到我尝试使用过滤器。 - 这是 Python 2 与 Python 3 的区别吗? Python使用哪个? (我安装了
pip install boto3,但我没有安装pip3。)
【问题讨论】:
标签: python path ansible jinja2 boto3