【问题标题】:External use of Ansible templating engineAnsible模板引擎的外部使用
【发布时间】:2017-10-03 16:19:45
【问题描述】:

我想在另一个使用模板变量的项目中使用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渲染引擎解析我自己的模板?

【问题讨论】:

  • 为什么不使用执行template模块的小剧本?
  • 这可能工作正常。你能举个例子吗?我对ansible 不是很熟悉,但对渲染功能印象深刻。我将如何从 Python 代码本地运行这个剧本?有没有办法可以在内存中而不是文件中获取输出模板?

标签: python templates ansible jinja2 templating


【解决方案1】:

简单的剧本:

---
- hosts: localhost
  connection: local
  gather_facts: no
  tasks:
    - template:
        src: input.j2
        dest: output.file

执行:ansible-playbook myplaybook.yml.

供您参考 Ansible 使用 Jinja2 模板引擎的略微扩展版本。
看看它——这可能是你真正想要的东西。

【讨论】:

  • 这就是我最终所做的。它工作得很好。我希望我们可以直接从 Python 调用负责渲染的模块。 (更快),而不是使用 ansible CLI 加载整个 Ansible 工厂。
  • 我意识到这是一个老问题,但我在我的一些Makefiles 中做了一些稍微不同的事情,而不是依赖剧本,我只是在 ad-hoc 模式下使用 Ansible:ansible localhost -m template -a 'src=input.j2 dest=output.file。这使得将 $<$@ 等 Makefile 变量替换到任务中变得容易。
猜你喜欢
  • 2014-03-24
  • 2014-08-09
  • 2014-01-02
  • 2011-04-10
  • 1970-01-01
  • 1970-01-01
  • 2016-08-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多