Different servers need different values but the template has dozens of `if` blocks. How do you simplify?
IntermediateScenarioVariables, Facts and Templates
Answer
Situation read → Template complexity is a smell.
What I'd do →
- Push decisions into variables (
group_vars), not template branching. - Use a dictionary lookup by OS or role instead of if/elif chains.
- Split into several templates if the files genuinely differ.
pkg: "{{ {'Debian':'apache2','RedHat':'httpd'}[ansible_facts['os_family']] }}"
Why → Data-driven config is easier to review and test.
Interview tip → Templates should format data, not decide policy.
More on Variables, Facts and Templates
A variable you set in `group_vars` is being overridden and you do not know where. How do you find the source?IntermediateYou need different values per environment without copying playbooks.BeginnerYou must render an Nginx config with one `server` block per site from a list.IntermediateA template needs the IPs of all hosts in the `db` group, for example for a replication config.IntermediateNothing should be rendered unless a mandatory variable is supplied.BeginnerPer-host values, like `server_id` for MySQL, must be unique and stable.Intermediate