Interview Prep/Ansible/Jinja2, Conditionals and Loops

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') }}.

All Ansible questions Roadmap: Ansible

More on Jinja2, Conditionals and Loops