Created
January 11, 2018 06:15
-
-
Save mixja/71750dd74234aa9b7c165b555332ae34 to your computer and use it in GitHub Desktop.
Interacting with Jinja Templates
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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