if statements can be used inside of inline expressions. This can be useful in some scenarios where additional new lines are not desired. Let's construct a scenario where we need to define an API as either cinder or cinderv2, as shown in the following code:
API = cinder{{ 'v2' if api.v2 else '' }}
This example assumes that api.v2 is defined as Boolean True or False. Inline if expressions follow the syntax of <do something> if <conditional is true> else <do something else>. In an inline if expression, there is an implied else; however, that implied else is meant to be evaluated as an undefined object, which will normally create an error. We protect against this by defining an explicit else, which renders a zero-length string.
Let's modify our playbook to demonstrate an inline conditional. This time, we'll use the debug module to render the simple template, as follows:
--- - name: demo the template hosts: localhost gather_facts: false vars: api: v2: true tasks: - name: pause with render debug: msg: "API = cinder{{ 'v2' if api.v2 else '' }}"
Execution of the playbook will show the following template being rendered:
Changing the value of api.v2 to false leads to a different result, as shown in the following screenshot:
In this way, we can create very concise, but powerful code that defines values based on an Ansible variable, as we have seen here.