Skip to content

Instantly share code, notes, and snippets.

@mixja
Created January 11, 2018 06:15
Show Gist options
  • Save mixja/71750dd74234aa9b7c165b555332ae34 to your computer and use it in GitHub Desktop.
Save mixja/71750dd74234aa9b7c165b555332ae34 to your computer and use it in GitHub Desktop.
Interacting with Jinja Templates
# Requires Jinja2 and Ansible 2.4+ installed
# Assumes you have custom filters
from jinja2 import Template,FileSystemLoader,Environment
# filter_loader includes all Ansible plugins
from ansible.plugins.loader import filter_loader
# Import locally defined filters
filter_loader.add_directory('filter_plugins')
# Create a dictionary of filters keyed by filter name with filter function as the value
filters = { k:v for filter in filter_loader.all() for k,v in filter.filters().items() }
# Create a Jinja2 environment pathed to local folder
environment = Environment()
environment.loader = FileSystemLoader('.')
# Add the ansible and local filters to the environment
environment.filters = dict(environment.filters.items() + filters.items())
# Load template
template = environment.get_template('templates/network.yml.j2')
# Create config object expected by template
config = {'Config':{'Vpcs':{'Default':{'Cidr':'192.168.0.0/20','Domain':'awsdockerstaging.org'}}}}
# Render the template
stack = template.render(config)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment