Conditionals

A conditional within a template creates a decision path. The engine will consider the conditional and choose from two or more potential blocks of code. There is always a minimum of two: a path if the conditional is met (evaluated as true), and either an explicitly defined else path if the conditional is not met (evaluated as false), or alternatively, an implied else path consisting of an empty block.

The statement for conditionals is the if statement. This statement works much the same as it does in Python. An if statement can be combined with one or more optional elif with an optional final else, and unlike Python, requires an explicit endif. The following example shows a config file template snippet combining both regular variable replacement and an if else structure:

setting = {{ setting }} 
{% if feature.enabled %} 
feature = True 
{% else %} 
feature = False 
{% endif %} 
another_setting = {{ another_setting }} 

In this example, the feature.enabled variable is checked to see if it exists, and is not set to False. If this is True, then the text feature = True is used; otherwise, the text feature = False is used. Outside of this control block, the parser does the normal variable substitution for the variables inside the curly braces. Multiple paths can be defined by using an elif statement, which presents the parser with another test to perform should the previous tests equate to False.

To demonstrate rendering the template, we'll save the example template as demo.j2 and then make a playbook named template-demo.yaml that defines the variables in use, and then uses a template lookup as part of a pause task to display the rendered template on the screen:

--- 
- name: demo the template 
  hosts: localhost 
  gather_facts: false  
  vars: 
    setting: a_val 
    feature: 
      enabled: true 
    another_setting: b_val  
  tasks: 
    - name: pause with render 
      pause: 
        prompt: "{{ lookup('template', 'demo.j2') }}" 

Executing this playbook will show the rendered template on screen while waiting for input. We can simply press Enter to complete the playbook:

If we were to change the value of feature.enabled to False, the output would be slightly different, as shown in the following screenshot:

As we can see from these simple tests, Jinja2 provides a very simple, yet powerful way of defining data through conditionals in a template.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.97.189