Filter 在过滤器中访问可转换变量
我一直在尝试创建一个过滤器,它为一些输入添加前缀。前缀应该由我的case inventory_dir和role_name中的某个ansible变量组成 我尝试实现以下代码:Filter 在过滤器中访问可转换变量,filter,ansible,Filter,Ansible,我一直在尝试创建一个过滤器,它为一些输入添加前缀。前缀应该由我的case inventory_dir和role_name中的某个ansible变量组成 我尝试实现以下代码: from ansible import errors def role_file(self): try: return inventory_dir + "/roles/" + role_name except Exception, e: raise errors.Ansibl
from ansible import errors
def role_file(self):
try:
return inventory_dir + "/roles/" + role_name
except Exception, e:
raise errors.AnsibleFilterError(
'role_file plugin error: {0}, self={1},'.format(str(e), str(self)))
class FilterModule(object):
''' prefix a file resource to the inventory directory '''
def filters(self):
return {
'role_file': role_file
}
我的剧本如下:
---
- hosts: messagebus
tasks:
- debug:
msg: "Hello World {{ 'abc' | role_file }}"
我收到以下错误消息:
致命:[localhost]:失败!=>{“msg”:“角色\u文件插件错误:未定义全局名称'inventory\u dir',self=abc,”}
有人能看到实施的问题吗
提前感谢回复评论:
您可以定义变量
inv_prefix:“{{inventory_dir+'/roles/'+role_name}}”
并在copy
/template
中使用它作为src:{inv_prefix}/myfile
还可以将变量传递给python过滤器,如:
{{ 'abc' | role_file(param2,param3) }}"
def role_file(self, param1,param2,param3):
try:
return param2 + "/roles/" + param3
为什么您认为Python代码中应该有
inventory\u dir
?这个过滤器的真正原因是什么?我原以为任何ansible变量都可以在Python代码中使用,因为代码是在Python中执行的。但最好是在一些健全的API。关于第二个问题。如果你看看这一部分。他们正在推广一种布局,其中每个目录在每个文件夹中都是分开的。在我目前的位置,这很可能是构造文件的更好方式,我也希望将需要复制的任何文件放在那里。您可以定义变量inv_prefix:“{{inventory_dir+'/roles/'+role_name}}”
并将其作为src:{inv_prefix}在copy
/template
中使用/myfile“
。它似乎起到了作用。非常感谢。它似乎很管用。谢谢。即使您在group_vars/allI中将表达式设置为全局,我也必须在您的评论中添加+1,但不幸的是,我需要15或更多的声誉。但是谢谢你的回答