我想在另一个使用模板变量的项目中使用
ansible
优秀的模板引擎(基于Jinja2
)。
模板变量可以使用所有
ansible
查找和过滤器。
我想建立一个类似于这样的渲染管道:
input.yaml.j2
=> ansible (template engine)
=> output.yaml
示例:
input.yaml.j2
vars:
users: "{{ lookup('file', '/tmp/users.json') }}"
template:
- name: "{{ item.name }}"
type: "user"
fist_user_group: "{{ item.user_groups.0 }}"
with_items:
- "{{ users }}"
/tmp/users.json
[
{'John': 'groups': ['apache', 'webapp']},
{'Rohit': 'groups': ['rabbitmq', 'postgresql']}
]
output.yaml
- name: "John"
type: "user"
first_user_group: "apache"
- name: "Rohit"
type: "user"
first_user_group: "rabbitmq"
问题:
如何使用
ansible
渲染引擎来解析我自己的模板?
简单的剧本:
---
- hosts: localhost
connection: local
gather_facts: no
tasks:
- template:
src: input.j2
dest: output.file
执行:
ansible-playbook myplaybook.yml
。
供您参考,Ansible 使用稍微扩展版本的 Jinja2 模板引擎。
看看它——这可能是你真正想要的东西。
扩展 @larsks 评论,将
template
模块作为 ad-hoc 命令运行 对于简单用途来说效果很好:
ansible localhost -m template -a 'src=input.j2 dest=output.file
但是...它非常慢,即使在快速 CPU 上也需要 >600 毫秒来评估 1 行模板。
您可以通过直接调用 Ansible 模板 Python API 来更快地完成此操作:
>>> from ansible.template import Templar
>>> Templar(loader=None).template('abc')
'abc'
>>> Templar(loader=None).template('{{"abc"|split("b")}}')
['a', 'c']
>>> Templar(loader=None, variables={'some_var': 1234}).template('{{some_var+1}}')
1235
...
这是 Ansible 的模块源代码、测试和文档
template
:
您还可以执行更高级的操作,例如加载本地/库存变量、查找插件等: