DevOps / Ansible Interview questions
When should you use loops instead of duplicating tasks?
Whenever the same module is applied repeatedly with only the argument values changing, a loop keeps the playbook shorter and easier to maintain than writing out a near-identical task for each item.
- name: Install several packages ansible.builtin.package: name: "{{ item }}" state: present loop: - nginx - git - curl
This is the right tool when the list of items is either fixed and short, or comes from a variable (including one populated dynamically from facts or a registered result), and each iteration performs conceptually the same action. Duplicating the task manually instead means every future change (adding a package, adjusting an option) has to be repeated in multiple places, which is exactly the kind of copy-paste maintenance burden loops exist to eliminate. For more complex iteration, such as looping over a list of dictionaries with multiple related values, loop with structured data or the older with_items/with_dict family handles that cleanly as well.
More Related questions...