外部使用Ansible模板引擎

时间:2017-10-03 16:19:45

标签: python templates ansible jinja2 templating

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

1 个答案:

答案 0 :(得分:1)

简单的剧本:

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

执行:ansible-playbook myplaybook.yml

为您提供信息Ansible使用Jinja2模板引擎的略微扩展版本 看看它 - 这可能是你真正想要的东西。