# \[Python API\] How to render jinja2 template from within python / retrieve list of variables for the currently executed play&task.

**URL:** <https://forum.ansible.com/t/python-api-how-to-render-jinja2-template-from-within-python-retrieve-list-of-variables-for-the-currently-executed-play-task/33292>\
**Category:** Ansible Developer\
**Created:** [July 1, 2020, 9:09am UTC](https://forum.ansible.com/t/python-api-how-to-render-jinja2-template-from-within-python-retrieve-list-of-variables-for-the-currently-executed-play-task/33292 "2020-07-01T09:09:19Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![Cukier](https://avatars.discourse-cdn.com/v4/letter/c/c77e96/32.png) [@Cukier](https://forum.ansible.com/u/Cukier)\
**Post date:** [July 1, 2020, 9:09am UTC](https://forum.ansible.com/t/python-api-how-to-render-jinja2-template-from-within-python-retrieve-list-of-variables-for-the-currently-executed-play-task/33292/1 "2020-07-01T09:09:19Z")

</div>

Recently I’ve been trying to mess a little with Ansible’s Python API (I am well aware it is not recommended, and python API is meant only for internal use, however…).

My goal was to create a function that’s able to retrieve data from ansible-playbook, which basically means two things:

1. retrieve the raw data by parsing YAML files,

> the simplest solution, is to let ansible do this, and then pass “{{ vars }}” to the module/plugin (at the level of YAML file)  
> a more complicated solution is to use: ansible.vars.manager.VariableManager

1. render the jinja2 template

> because ansible stores them, inside variables, instead of what they evaluate to.  
> that’s why I need/want to render jinja2 using ansible’s API, at the level of .py file.

Questions:

1. is there any way to retrieve current play & current task from within a .py file from within a module/plugin (when a said module/plugin is being executed, just like the code below), so I can pass it to the variables = variable\_manager.get\_vars(…) 2. is there a better way to do what I am trying to do?

`

from ansible import context  
from ansible.inventory.manager import InventoryManager  
from ansible.parsing.dataloader import DataLoader  
from ansible.template import Templar  
from ansible.vars.manager import VariableManager

def render(template):  
“”"  
Render jinja2 template using Anisble’s API.  
“”"  
options = context.CLIARGS  
sources = options[‘inventory’]  
loader = DataLoader()  
inventory = InventoryManager(  
loader = loader,  
sources = sources  
)  
variable\_manager = VariableManager(  
loader = loader,  
inventory = inventory  
)  
templar = Templar(  
loader = DataLoader(),  
variables = variable\_manager.get\_vars(…) # \<\<\< HERE  
)  
return templar.template(template)

def filter\_render\_test(\*args, \*\*kwargs):  
return render(“{{ foo }}”)

class FilterModule(object):  
def filters(self):  
return {  
‘render\_test’: filter\_render\_test,  
}

`  
and the corresponding playbook:

`
