Search code examples
pythontemplatesansiblejinja2templating

External use of Ansible templating engine


I want to use ansible excellent templating engine (based on Jinja2) in another project, that use template variables.

The template variables can make use of all ansible lookups and filters.

I'd like to establish a pipeline for rendering similar to this:

input.yaml.j2 => ansible (template engine) => output.yaml

Example:

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"

Question:

How can I use ansible rendering engine to parse my own templates ?


Solution

  • Simple playbook:

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

    Execution: ansible-playbook myplaybook.yml.

    For you information Ansible uses slightly extended version of Jinja2 template engine.
    Take a look at it – this can be the thing you actually want.