我正在尝试在 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
到顶部时,剧本失败了。
致命:[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 似乎在剧本运行开始时(有时是其他时间)导入自定义过滤器文件,捕获错误,然后继续直到我尝试使用过滤器。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] 删除。
我来说两句