Logic for Ansibles
Ansible logic is how playbooks make decisions and handle data. Variables hold values from many sources with a defined precedence, facts describe the target host, and conditionals with when, loops and registered results let a task run only in the right situation or repeat over a list.
Stage: Playbook Skills · Part of the Ansible roadmap · Last reviewed 19 November 2026
What to learn in Logic
- Define variables in playbooks, group_vars and host_vars
- Use gathered facts such as ansible_os_family in a when condition
- Loop over a list of packages or users
- Capture a task result with register and test it
- Explain the order in which variable sources override each other
Logic interview questions
How does variable precedence work in Ansible?
Ansible has a fixed order of sources, from lowest to highest, with role defaults at the bottom and extra variables passed with -e at the top. Inventory variables, group_vars, host_vars, play vars and task vars sit between. Knowing this order explains surprising overrides.
How do you run a task only on certain hosts?
Use a when condition on the task, often testing a fact like ansible_distribution or a variable. You can also restrict the play to a group using hosts, or limit a run with the --limit option. when is evaluated per host, so each host decides separately.
Where Logic fits in the Ansible roadmap
Logic belongs to the Playbook Skills stage (intermediate level). Write better automation.
Other units in this stage
Back to the full Ansible roadmap