1 minute read

Ansible provides various loop constructs that allow you to iterate over lists, dictionaries, and other data structures. Loops are useful for performing repetitive tasks or executing a set of actions on multiple hosts. Here’s a simple explanation of working with Ansible loops along with examples to illustrate their usage.

  1. Standard Loop: The with_items loop is used to iterate over a list of items. It executes the specified tasks for each item in the list.
- name: Install packages
  package:
    name: "{{ item }}"
    state: present
  with_items:
    - nginx
    - apache2
    - mysql

In this example, Ansible will install the nginx, apache2, and mysql packages on the target hosts.

  1. Dictionary Loop: The with_dict loop allows you to iterate over a dictionary. It assigns each key-value pair of the dictionary to individual variables that you can use within the loop.
- name: Create users
  user:
    name: "{{ item.key }}"
    state: present
    password: "{{ item.value.password | password_hash('sha512') }}"
  with_dict:
    user1:
      password: secret1
    user2:
      password: secret2

Here, Ansible will create two users (user1 and user2) with their respective passwords on the target hosts.

  1. Looping over a Range: Ansible also provides a with_sequence loop that allows you to iterate over a sequence of numbers. It is useful when you need to perform a task multiple times.
- name: Print numbers
  debug:
    msg: "Number: {{ item }}"
  with_sequence: start=1 end=5

This loop will print numbers from 1 to 5.

  1. Loop Control: Ansible loops also provide control mechanisms like loop_var and loop_control to manipulate loop behavior.
- name: Copy files with loop control
  copy:
    src: "{{ item.src }}"
    dest: "{{ item.dest }}"
  with_items:
    - { src: 'file1.txt', dest: '/tmp/file1.txt' }
    - { src: 'file2.txt', dest: '/tmp/file2.txt' }
  loop_control:
    loop_var: item
    label: "{{ item.src }} => {{ item.dest }}"

In this example, the loop_var option sets the loop variable to item, and the label option customizes the output labels for each iteration.

These are just a few examples of how you can work with Ansible loops. Ansible provides more loop constructs like with_fileglob, with_lines, and with_nested to cater to different looping requirements. The loops help in automating repetitive tasks and managing multiple hosts efficiently.