我想确保表示用户设置的文件夹的变量具有结束斜杠,因此我可以避免与缺少斜杠或双斜杠相关的错误。
主要是我正在考虑以下维修任务:
- when: my_path[-1] != '/'
set_fact:
my_path: "{{ mypath }}/"
如果这个条件可以用纯 jinja2 写得更好,因为我可以避免创建额外的set_fact并将该技巧放在"vars"块中。
有什么更好的方法来实现它吗?显然,没有内置的 jinja2 过滤器来格式化路径。
您可以编写自己的过滤器。
在ansible.cfg
中,您可以指定过滤器目录:
[defaults]
filter_plugins=<path/to/your/library/of/filters>
现在你输入<path/to/your/library/of/filters>/path_filter.py
:
from ansible.module_utils import basic
def canonical_path(path):
''' Verify that path ends with / and add / if not '''
if path[-1] != '/':
return path + '/'
return path
class FilterModule(object):
''' Ansible Filter to provide canonical_path '''
def filters(self):
return {'canonical_path': canonical_path}
这使您可以编写剧本
- name: Show canonical_path
debug:
msg: "Path is : {{ mypath | canonical_path }}"