How do you write an inline conditional value?
IntermediateConceptJinja2, Conditionals and Loops
Answer
Use the ternary filter or a Jinja2 inline if.
log_level: "{{ (env == 'prod') | ternary('warn', 'debug') }}"
mode: "{{ 'secure' if tls_enabled | bool else 'plain' }}"
replicas: "{{ 3 if env == 'prod' else 1 }}"
ternary takes an optional third value for the None case. For several branches, a dictionary lookup is clearer: {{ {'prod': 'warn', 'stage': 'info'}[env] | default('debug') }}.
More on Jinja2, Conditionals and Loops
What role does Jinja2 play in Ansible?BeginnerWhat are the three Jinja2 delimiters?BeginnerShow a template with a loop and a conditional, and how it is deployed.BeginnerWhich filters do you use every day?BeginnerHow do you transform lists and dicts with filters (`map`, `select`, `selectattr`, `unique`, `flatten`)?IntermediateHow does `when` work and which operators can you use?Beginner