What is Jinja2?
Jinja2 is a modern templating engine for Python that allows you to generate text output with:- Variable substitution
- Control flow (loops, conditionals)
- Filters and functions
- Template inheritance
- Macros for reusable logic
Creating a Jinja2 Transform
1. Define a GraphQL Query
First, create a GraphQL query to retrieve the data you need:2. Create the Jinja2 Template
Create a template file that uses the GraphQL query data:3. Register in .infrahub.yml
Add the query and transform to your repository configuration:Data Structure
The GraphQL query response is passed to the template as adata dictionary with the exact structure returned by GraphQL:
Template Syntax Reference
Variables
Access and output variables:Conditionals
Control flow with if/elif/else:Loops
Iterate over lists:Namespace Variables
Use namespace to share variables across scopes:Filters
Modify variables with filters:Comments
Add comments that won’t appear in output:Real-World Example: Arista Device Configuration
Complete example from Infrahub’s demo repository:Simple Example: Data Transformation
For simpler use cases like data extraction:Using with Artifacts
Combine Jinja2 transforms with artifact definitions:- Target devices are identified from the
edge_routergroup - For each device, the
deviceparameter is extracted - GraphQL query executes with
devicevariable - Jinja2 template renders with query response
- Result is stored as an artifact
Error Handling
Infrahub catches and reports template errors:- Undefined variables: Accessing data that doesn’t exist
- Template syntax errors: Invalid Jinja2 syntax
- Type errors: Attempting invalid operations on data
Best Practices
-
Check for existence: Always verify data exists before accessing
-
Use meaningful variable names: Make templates readable
-
Add comments: Explain complex logic
- Keep templates focused: One template per configuration type
- Test with sample data: Validate templates before production
-
Handle missing data gracefully: Provide defaults or skip sections
- Use consistent indentation: Match output format requirements
- Optimize GraphQL queries: Request only needed fields
Template Execution
Templates are rendered using the Infrahub SDK’sJinja2Template class:
- Loads template from repository worktree
- Validates template syntax
- Passes GraphQL query response as
datavariable - Renders template with Jinja2 engine
- Returns rendered string
Timeout Configuration
Jinja2 transforms have configurable timeouts:Related Topics
- Transformations Overview - Understanding transformation concepts
- Artifacts - Using templates to generate artifacts
- Python Transforms - Alternative to Jinja2 for complex logic
- GraphQL Queries - Writing queries for templates
Next Steps
- Create your first Jinja2 template transformation
- Learn about Python transforms for complex logic
- Build artifacts using your templates
- Explore GraphQL queries to retrieve data